123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626 |
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- 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;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- __.prototype = b.prototype;
- d.prototype = new __();
- };
- var BABYLON;
- (function (BABYLON) {
- BABYLON.ToGammaSpace = 1 / 2.2;
- BABYLON.ToLinearSpace = 2.2;
- BABYLON.Epsilon = 0.001;
- var MathTools = (function () {
- function MathTools() {
- }
- MathTools.WithinEpsilon = function (a, b, epsilon) {
- if (epsilon === void 0) { epsilon = 1.401298E-45; }
- var num = a - b;
- return -epsilon <= num && num <= epsilon;
- };
- MathTools.ToHex = function (i) {
- var str = i.toString(16);
- if (i <= 15) {
- return ("0" + str).toUpperCase();
- }
- return str.toUpperCase();
- };
- // Returns -1 when value is a negative number and
- // +1 when value is a positive number.
- MathTools.Sign = function (value) {
- value = +value; // convert to a number
- if (value === 0 || isNaN(value))
- return value;
- return value > 0 ? 1 : -1;
- };
- MathTools.Clamp = function (value, min, max) {
- if (min === void 0) { min = 0; }
- if (max === void 0) { max = 1; }
- return Math.min(max, Math.max(min, value));
- };
- return MathTools;
- })();
- BABYLON.MathTools = MathTools;
- var Color3 = (function () {
- function Color3(r, g, b) {
- if (r === void 0) { r = 0; }
- if (g === void 0) { g = 0; }
- if (b === void 0) { b = 0; }
- this.r = r;
- this.g = g;
- this.b = b;
- }
- Color3.prototype.toString = function () {
- return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
- };
- // Operators
- Color3.prototype.toArray = function (array, index) {
- if (index === undefined) {
- index = 0;
- }
- array[index] = this.r;
- array[index + 1] = this.g;
- array[index + 2] = this.b;
- return this;
- };
- Color3.prototype.toColor4 = function (alpha) {
- if (alpha === void 0) { alpha = 1; }
- return new Color4(this.r, this.g, this.b, alpha);
- };
- Color3.prototype.asArray = function () {
- var result = [];
- this.toArray(result, 0);
- return result;
- };
- Color3.prototype.toLuminance = function () {
- return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
- };
- Color3.prototype.multiply = function (otherColor) {
- return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
- };
- Color3.prototype.multiplyToRef = function (otherColor, result) {
- result.r = this.r * otherColor.r;
- result.g = this.g * otherColor.g;
- result.b = this.b * otherColor.b;
- return this;
- };
- Color3.prototype.equals = function (otherColor) {
- return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
- };
- Color3.prototype.equalsFloats = function (r, g, b) {
- return this.r === r && this.g === g && this.b === b;
- };
- Color3.prototype.scale = function (scale) {
- return new Color3(this.r * scale, this.g * scale, this.b * scale);
- };
- Color3.prototype.scaleToRef = function (scale, result) {
- result.r = this.r * scale;
- result.g = this.g * scale;
- result.b = this.b * scale;
- return this;
- };
- Color3.prototype.add = function (otherColor) {
- return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
- };
- Color3.prototype.addToRef = function (otherColor, result) {
- result.r = this.r + otherColor.r;
- result.g = this.g + otherColor.g;
- result.b = this.b + otherColor.b;
- return this;
- };
- Color3.prototype.subtract = function (otherColor) {
- return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
- };
- Color3.prototype.subtractToRef = function (otherColor, result) {
- result.r = this.r - otherColor.r;
- result.g = this.g - otherColor.g;
- result.b = this.b - otherColor.b;
- return this;
- };
- Color3.prototype.clone = function () {
- return new Color3(this.r, this.g, this.b);
- };
- Color3.prototype.copyFrom = function (source) {
- this.r = source.r;
- this.g = source.g;
- this.b = source.b;
- return this;
- };
- Color3.prototype.copyFromFloats = function (r, g, b) {
- this.r = r;
- this.g = g;
- this.b = b;
- return this;
- };
- Color3.prototype.toHexString = function () {
- var intR = (this.r * 255) | 0;
- var intG = (this.g * 255) | 0;
- var intB = (this.b * 255) | 0;
- return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
- };
- Color3.prototype.toLinearSpace = function () {
- var convertedColor = new Color3();
- this.toLinearSpaceToRef(convertedColor);
- return convertedColor;
- };
- Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
- convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
- convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
- convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
- return this;
- };
- Color3.prototype.toGammaSpace = function () {
- var convertedColor = new Color3();
- this.toGammaSpaceToRef(convertedColor);
- return convertedColor;
- };
- Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
- convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
- convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
- convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
- return this;
- };
- // Statics
- Color3.FromHexString = function (hex) {
- if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
- //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
- return new Color3(0, 0, 0);
- }
- var r = parseInt(hex.substring(1, 3), 16);
- var g = parseInt(hex.substring(3, 5), 16);
- var b = parseInt(hex.substring(5, 7), 16);
- return Color3.FromInts(r, g, b);
- };
- Color3.FromArray = function (array, offset) {
- if (offset === void 0) { offset = 0; }
- return new Color3(array[offset], array[offset + 1], array[offset + 2]);
- };
- Color3.FromInts = function (r, g, b) {
- return new Color3(r / 255.0, g / 255.0, b / 255.0);
- };
- Color3.Lerp = function (start, end, amount) {
- var r = start.r + ((end.r - start.r) * amount);
- var g = start.g + ((end.g - start.g) * amount);
- var b = start.b + ((end.b - start.b) * amount);
- return new Color3(r, g, b);
- };
- Color3.Red = function () { return new Color3(1, 0, 0); };
- Color3.Green = function () { return new Color3(0, 1, 0); };
- Color3.Blue = function () { return new Color3(0, 0, 1); };
- Color3.Black = function () { return new Color3(0, 0, 0); };
- Color3.White = function () { return new Color3(1, 1, 1); };
- Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
- Color3.Magenta = function () { return new Color3(1, 0, 1); };
- Color3.Yellow = function () { return new Color3(1, 1, 0); };
- Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
- return Color3;
- })();
- BABYLON.Color3 = Color3;
- var Color4 = (function () {
- function Color4(r, g, b, a) {
- this.r = r;
- this.g = g;
- this.b = b;
- this.a = a;
- }
- // Operators
- Color4.prototype.addInPlace = function (right) {
- this.r += right.r;
- this.g += right.g;
- this.b += right.b;
- this.a += right.a;
- return this;
- };
- Color4.prototype.asArray = function () {
- var result = [];
- this.toArray(result, 0);
- return result;
- };
- Color4.prototype.toArray = function (array, index) {
- if (index === undefined) {
- index = 0;
- }
- array[index] = this.r;
- array[index + 1] = this.g;
- array[index + 2] = this.b;
- array[index + 3] = this.a;
- return this;
- };
- Color4.prototype.add = function (right) {
- return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
- };
- Color4.prototype.subtract = function (right) {
- return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
- };
- Color4.prototype.subtractToRef = function (right, result) {
- result.r = this.r - right.r;
- result.g = this.g - right.g;
- result.b = this.b - right.b;
- result.a = this.a - right.a;
- return this;
- };
- Color4.prototype.scale = function (scale) {
- return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
- };
- Color4.prototype.scaleToRef = function (scale, result) {
- result.r = this.r * scale;
- result.g = this.g * scale;
- result.b = this.b * scale;
- result.a = this.a * scale;
- return this;
- };
- Color4.prototype.toString = function () {
- return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
- };
- Color4.prototype.clone = function () {
- return new Color4(this.r, this.g, this.b, this.a);
- };
- Color4.prototype.copyFrom = function (source) {
- this.r = source.r;
- this.g = source.g;
- this.b = source.b;
- this.a = source.a;
- return this;
- };
- Color4.prototype.toHexString = function () {
- var intR = (this.r * 255) | 0;
- var intG = (this.g * 255) | 0;
- var intB = (this.b * 255) | 0;
- var intA = (this.a * 255) | 0;
- return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
- };
- // Statics
- Color4.FromHexString = function (hex) {
- if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
- //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
- return new Color4(0, 0, 0, 0);
- }
- var r = parseInt(hex.substring(1, 3), 16);
- var g = parseInt(hex.substring(3, 5), 16);
- var b = parseInt(hex.substring(5, 7), 16);
- var a = parseInt(hex.substring(7, 9), 16);
- return Color4.FromInts(r, g, b, a);
- };
- Color4.Lerp = function (left, right, amount) {
- var result = new Color4(0, 0, 0, 0);
- Color4.LerpToRef(left, right, amount, result);
- return result;
- };
- Color4.LerpToRef = function (left, right, amount, result) {
- result.r = left.r + (right.r - left.r) * amount;
- result.g = left.g + (right.g - left.g) * amount;
- result.b = left.b + (right.b - left.b) * amount;
- result.a = left.a + (right.a - left.a) * amount;
- };
- Color4.FromArray = function (array, offset) {
- if (offset === void 0) { offset = 0; }
- return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
- };
- Color4.FromInts = function (r, g, b, a) {
- return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
- };
- Color4.CheckColors4 = function (colors, count) {
- // Check if color3 was used
- if (colors.length === count * 3) {
- var colors4 = [];
- for (var index = 0; index < colors.length; index += 3) {
- var newIndex = (index / 3) * 4;
- colors4[newIndex] = colors[index];
- colors4[newIndex + 1] = colors[index + 1];
- colors4[newIndex + 2] = colors[index + 2];
- colors4[newIndex + 3] = 1.0;
- }
- return colors4;
- }
- return colors;
- };
- return Color4;
- })();
- BABYLON.Color4 = Color4;
- var Vector2 = (function () {
- function Vector2(x, y) {
- this.x = x;
- this.y = y;
- }
- Vector2.prototype.toString = function () {
- return "{X: " + this.x + " Y:" + this.y + "}";
- };
- // Operators
- Vector2.prototype.toArray = function (array, index) {
- if (index === void 0) { index = 0; }
- array[index] = this.x;
- array[index + 1] = this.y;
- return this;
- };
- Vector2.prototype.asArray = function () {
- var result = [];
- this.toArray(result, 0);
- return result;
- };
- Vector2.prototype.copyFrom = function (source) {
- this.x = source.x;
- this.y = source.y;
- return this;
- };
- Vector2.prototype.copyFromFloats = function (x, y) {
- this.x = x;
- this.y = y;
- return this;
- };
- Vector2.prototype.add = function (otherVector) {
- return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
- };
- Vector2.prototype.addVector3 = function (otherVector) {
- return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
- };
- Vector2.prototype.subtract = function (otherVector) {
- return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
- };
- Vector2.prototype.subtractInPlace = function (otherVector) {
- this.x -= otherVector.x;
- this.y -= otherVector.y;
- return this;
- };
- Vector2.prototype.multiplyInPlace = function (otherVector) {
- this.x *= otherVector.x;
- this.y *= otherVector.y;
- return this;
- };
- Vector2.prototype.multiply = function (otherVector) {
- return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
- };
- Vector2.prototype.multiplyToRef = function (otherVector, result) {
- result.x = this.x * otherVector.x;
- result.y = this.y * otherVector.y;
- return this;
- };
- Vector2.prototype.multiplyByFloats = function (x, y) {
- return new Vector2(this.x * x, this.y * y);
- };
- Vector2.prototype.divide = function (otherVector) {
- return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
- };
- Vector2.prototype.divideToRef = function (otherVector, result) {
- result.x = this.x / otherVector.x;
- result.y = this.y / otherVector.y;
- return this;
- };
- Vector2.prototype.negate = function () {
- return new Vector2(-this.x, -this.y);
- };
- Vector2.prototype.scaleInPlace = function (scale) {
- this.x *= scale;
- this.y *= scale;
- return this;
- };
- Vector2.prototype.scale = function (scale) {
- return new Vector2(this.x * scale, this.y * scale);
- };
- Vector2.prototype.equals = function (otherVector) {
- return otherVector && this.x === otherVector.x && this.y === otherVector.y;
- };
- Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
- if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
- return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
- };
- // Properties
- Vector2.prototype.length = function () {
- return Math.sqrt(this.x * this.x + this.y * this.y);
- };
- Vector2.prototype.lengthSquared = function () {
- return (this.x * this.x + this.y * this.y);
- };
- // Methods
- Vector2.prototype.normalize = function () {
- var len = this.length();
- if (len === 0)
- return this;
- var num = 1.0 / len;
- this.x *= num;
- this.y *= num;
- return this;
- };
- Vector2.prototype.clone = function () {
- return new Vector2(this.x, this.y);
- };
- // Statics
- Vector2.Zero = function () {
- return new Vector2(0, 0);
- };
- Vector2.FromArray = function (array, offset) {
- if (offset === void 0) { offset = 0; }
- return new Vector2(array[offset], array[offset + 1]);
- };
- Vector2.FromArrayToRef = function (array, offset, result) {
- result.x = array[offset];
- result.y = array[offset + 1];
- };
- Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
- var squared = amount * amount;
- var cubed = amount * squared;
- var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
- (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
- ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
- var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
- (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
- ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
- return new Vector2(x, y);
- };
- Vector2.Clamp = function (value, min, max) {
- var x = value.x;
- x = (x > max.x) ? max.x : x;
- x = (x < min.x) ? min.x : x;
- var y = value.y;
- y = (y > max.y) ? max.y : y;
- y = (y < min.y) ? min.y : y;
- return new Vector2(x, y);
- };
- Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
- var squared = amount * amount;
- var cubed = amount * squared;
- var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
- var part2 = (-2.0 * cubed) + (3.0 * squared);
- var part3 = (cubed - (2.0 * squared)) + amount;
- var part4 = cubed - squared;
- var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
- var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
- return new Vector2(x, y);
- };
- Vector2.Lerp = function (start, end, amount) {
- var x = start.x + ((end.x - start.x) * amount);
- var y = start.y + ((end.y - start.y) * amount);
- return new Vector2(x, y);
- };
- Vector2.Dot = function (left, right) {
- return left.x * right.x + left.y * right.y;
- };
- Vector2.Normalize = function (vector) {
- var newVector = vector.clone();
- newVector.normalize();
- return newVector;
- };
- Vector2.Minimize = function (left, right) {
- var x = (left.x < right.x) ? left.x : right.x;
- var y = (left.y < right.y) ? left.y : right.y;
- return new Vector2(x, y);
- };
- Vector2.Maximize = function (left, right) {
- var x = (left.x > right.x) ? left.x : right.x;
- var y = (left.y > right.y) ? left.y : right.y;
- return new Vector2(x, y);
- };
- Vector2.Transform = function (vector, transformation) {
- var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
- var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
- return new Vector2(x, y);
- };
- Vector2.Distance = function (value1, value2) {
- return Math.sqrt(Vector2.DistanceSquared(value1, value2));
- };
- Vector2.DistanceSquared = function (value1, value2) {
- var x = value1.x - value2.x;
- var y = value1.y - value2.y;
- return (x * x) + (y * y);
- };
- return Vector2;
- })();
- BABYLON.Vector2 = Vector2;
- var Vector3 = (function () {
- function Vector3(x, y, z) {
- this.x = x;
- this.y = y;
- this.z = z;
- }
- Vector3.prototype.toString = function () {
- return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
- };
- // Operators
- Vector3.prototype.asArray = function () {
- var result = [];
- this.toArray(result, 0);
- return result;
- };
- Vector3.prototype.toArray = function (array, index) {
- if (index === void 0) { index = 0; }
- array[index] = this.x;
- array[index + 1] = this.y;
- array[index + 2] = this.z;
- return this;
- };
- Vector3.prototype.toQuaternion = function () {
- var result = new Quaternion(0, 0, 0, 1);
- var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
- var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
- var coszMinusx = Math.cos((this.z - this.x) * 0.5);
- var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
- var cosy = Math.cos(this.y * 0.5);
- var siny = Math.sin(this.y * 0.5);
- result.x = coszMinusx * siny;
- result.y = -sinzMinusx * siny;
- result.z = sinxPlusz * cosy;
- result.w = cosxPlusz * cosy;
- return result;
- };
- Vector3.prototype.addInPlace = function (otherVector) {
- this.x += otherVector.x;
- this.y += otherVector.y;
- this.z += otherVector.z;
- return this;
- };
- Vector3.prototype.add = function (otherVector) {
- return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
- };
- Vector3.prototype.addToRef = function (otherVector, result) {
- result.x = this.x + otherVector.x;
- result.y = this.y + otherVector.y;
- result.z = this.z + otherVector.z;
- return this;
- };
- Vector3.prototype.subtractInPlace = function (otherVector) {
- this.x -= otherVector.x;
- this.y -= otherVector.y;
- this.z -= otherVector.z;
- return this;
- };
- Vector3.prototype.subtract = function (otherVector) {
- return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
- };
- Vector3.prototype.subtractToRef = function (otherVector, result) {
- result.x = this.x - otherVector.x;
- result.y = this.y - otherVector.y;
- result.z = this.z - otherVector.z;
- return this;
- };
- Vector3.prototype.subtractFromFloats = function (x, y, z) {
- return new Vector3(this.x - x, this.y - y, this.z - z);
- };
- Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
- result.x = this.x - x;
- result.y = this.y - y;
- result.z = this.z - z;
- return this;
- };
- Vector3.prototype.negate = function () {
- return new Vector3(-this.x, -this.y, -this.z);
- };
- Vector3.prototype.scaleInPlace = function (scale) {
- this.x *= scale;
- this.y *= scale;
- this.z *= scale;
- return this;
- };
- Vector3.prototype.scale = function (scale) {
- return new Vector3(this.x * scale, this.y * scale, this.z * scale);
- };
- Vector3.prototype.scaleToRef = function (scale, result) {
- result.x = this.x * scale;
- result.y = this.y * scale;
- result.z = this.z * scale;
- };
- Vector3.prototype.equals = function (otherVector) {
- return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
- };
- Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
- if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
- return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
- };
- Vector3.prototype.equalsToFloats = function (x, y, z) {
- return this.x === x && this.y === y && this.z === z;
- };
- Vector3.prototype.multiplyInPlace = function (otherVector) {
- this.x *= otherVector.x;
- this.y *= otherVector.y;
- this.z *= otherVector.z;
- return this;
- };
- Vector3.prototype.multiply = function (otherVector) {
- return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
- };
- Vector3.prototype.multiplyToRef = function (otherVector, result) {
- result.x = this.x * otherVector.x;
- result.y = this.y * otherVector.y;
- result.z = this.z * otherVector.z;
- return this;
- };
- Vector3.prototype.multiplyByFloats = function (x, y, z) {
- return new Vector3(this.x * x, this.y * y, this.z * z);
- };
- Vector3.prototype.divide = function (otherVector) {
- return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
- };
- Vector3.prototype.divideToRef = function (otherVector, result) {
- result.x = this.x / otherVector.x;
- result.y = this.y / otherVector.y;
- result.z = this.z / otherVector.z;
- return this;
- };
- Vector3.prototype.MinimizeInPlace = function (other) {
- if (other.x < this.x)
- this.x = other.x;
- if (other.y < this.y)
- this.y = other.y;
- if (other.z < this.z)
- this.z = other.z;
- return this;
- };
- Vector3.prototype.MaximizeInPlace = function (other) {
- if (other.x > this.x)
- this.x = other.x;
- if (other.y > this.y)
- this.y = other.y;
- if (other.z > this.z)
- this.z = other.z;
- return this;
- };
- // Properties
- Vector3.prototype.length = function () {
- return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
- };
- Vector3.prototype.lengthSquared = function () {
- return (this.x * this.x + this.y * this.y + this.z * this.z);
- };
- // Methods
- Vector3.prototype.normalize = function () {
- var len = this.length();
- if (len === 0 || len === 1.0)
- return this;
- var num = 1.0 / len;
- this.x *= num;
- this.y *= num;
- this.z *= num;
- return this;
- };
- Vector3.prototype.clone = function () {
- return new Vector3(this.x, this.y, this.z);
- };
- Vector3.prototype.copyFrom = function (source) {
- this.x = source.x;
- this.y = source.y;
- this.z = source.z;
- return this;
- };
- Vector3.prototype.copyFromFloats = function (x, y, z) {
- this.x = x;
- this.y = y;
- this.z = z;
- return this;
- };
- // Statics
- Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
- var d0 = Vector3.Dot(vector0, axis) - size;
- var d1 = Vector3.Dot(vector1, axis) - size;
- var s = d0 / (d0 - d1);
- return s;
- };
- Vector3.FromArray = function (array, offset) {
- if (!offset) {
- offset = 0;
- }
- return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
- };
- Vector3.FromFloatArray = function (array, offset) {
- if (!offset) {
- offset = 0;
- }
- return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
- };
- Vector3.FromArrayToRef = function (array, offset, result) {
- result.x = array[offset];
- result.y = array[offset + 1];
- result.z = array[offset + 2];
- };
- Vector3.FromFloatArrayToRef = function (array, offset, result) {
- result.x = array[offset];
- result.y = array[offset + 1];
- result.z = array[offset + 2];
- };
- Vector3.FromFloatsToRef = function (x, y, z, result) {
- result.x = x;
- result.y = y;
- result.z = z;
- };
- Vector3.Zero = function () {
- return new Vector3(0, 0, 0);
- };
- Vector3.Up = function () {
- return new Vector3(0, 1.0, 0);
- };
- Vector3.TransformCoordinates = function (vector, transformation) {
- var result = Vector3.Zero();
- Vector3.TransformCoordinatesToRef(vector, transformation, result);
- return result;
- };
- Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
- var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
- var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
- var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
- var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
- result.x = x / w;
- result.y = y / w;
- result.z = z / w;
- };
- Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
- var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
- var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
- var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
- var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
- result.x = rx / rw;
- result.y = ry / rw;
- result.z = rz / rw;
- };
- Vector3.TransformNormal = function (vector, transformation) {
- var result = Vector3.Zero();
- Vector3.TransformNormalToRef(vector, transformation, result);
- return result;
- };
- Vector3.TransformNormalToRef = function (vector, transformation, result) {
- result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
- result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
- result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
- };
- Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
- result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
- result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
- result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
- };
- Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
- var squared = amount * amount;
- var cubed = amount * squared;
- var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
- (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
- ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
- var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
- (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
- ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
- var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
- (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
- ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
- return new Vector3(x, y, z);
- };
- Vector3.Clamp = function (value, min, max) {
- var x = value.x;
- x = (x > max.x) ? max.x : x;
- x = (x < min.x) ? min.x : x;
- var y = value.y;
- y = (y > max.y) ? max.y : y;
- y = (y < min.y) ? min.y : y;
- var z = value.z;
- z = (z > max.z) ? max.z : z;
- z = (z < min.z) ? min.z : z;
- return new Vector3(x, y, z);
- };
- Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
- var squared = amount * amount;
- var cubed = amount * squared;
- var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
- var part2 = (-2.0 * cubed) + (3.0 * squared);
- var part3 = (cubed - (2.0 * squared)) + amount;
- var part4 = cubed - squared;
- var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
- var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
- var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
- return new Vector3(x, y, z);
- };
- Vector3.Lerp = function (start, end, amount) {
- var x = start.x + ((end.x - start.x) * amount);
- var y = start.y + ((end.y - start.y) * amount);
- var z = start.z + ((end.z - start.z) * amount);
- return new Vector3(x, y, z);
- };
- Vector3.Dot = function (left, right) {
- return (left.x * right.x + left.y * right.y + left.z * right.z);
- };
- Vector3.Cross = function (left, right) {
- var result = Vector3.Zero();
- Vector3.CrossToRef(left, right, result);
- return result;
- };
- Vector3.CrossToRef = function (left, right, result) {
- result.x = left.y * right.z - left.z * right.y;
- result.y = left.z * right.x - left.x * right.z;
- result.z = left.x * right.y - left.y * right.x;
- };
- Vector3.Normalize = function (vector) {
- var result = Vector3.Zero();
- Vector3.NormalizeToRef(vector, result);
- return result;
- };
- Vector3.NormalizeToRef = function (vector, result) {
- result.copyFrom(vector);
- result.normalize();
- };
- Vector3.Project = function (vector, world, transform, viewport) {
- var cw = viewport.width;
- var ch = viewport.height;
- var cx = viewport.x;
- var cy = viewport.y;
- var viewportMatrix = Matrix.FromValues(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);
- var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
- return Vector3.TransformCoordinates(vector, finalMatrix);
- };
- Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
- var matrix = world.multiply(transform);
- matrix.invert();
- source.x = source.x / viewportWidth * 2 - 1;
- source.y = -(source.y / viewportHeight * 2 - 1);
- var vector = Vector3.TransformCoordinates(source, matrix);
- var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
- if (MathTools.WithinEpsilon(num, 1.0)) {
- vector = vector.scale(1.0 / num);
- }
- return vector;
- };
- Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
- var matrix = world.multiply(view).multiply(projection);
- matrix.invert();
- var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
- var vector = Vector3.TransformCoordinates(screenSource, matrix);
- var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
- if (MathTools.WithinEpsilon(num, 1.0)) {
- vector = vector.scale(1.0 / num);
- }
- return vector;
- };
- Vector3.Minimize = function (left, right) {
- var min = left.clone();
- min.MinimizeInPlace(right);
- return min;
- };
- Vector3.Maximize = function (left, right) {
- var max = left.clone();
- max.MaximizeInPlace(right);
- return max;
- };
- Vector3.Distance = function (value1, value2) {
- return Math.sqrt(Vector3.DistanceSquared(value1, value2));
- };
- Vector3.DistanceSquared = function (value1, value2) {
- var x = value1.x - value2.x;
- var y = value1.y - value2.y;
- var z = value1.z - value2.z;
- return (x * x) + (y * y) + (z * z);
- };
- Vector3.Center = function (value1, value2) {
- var center = value1.add(value2);
- center.scaleInPlace(0.5);
- return center;
- };
- /**
- * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
- * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
- * to something in order to rotate it from its local system to the given target system.
- */
- Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
- var rotation = Vector3.Zero();
- Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
- return rotation;
- };
- /**
- * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
- */
- Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
- var u = axis1.normalize();
- var w = axis3.normalize();
- // world axis
- var X = Axis.X;
- var Y = Axis.Y;
- // equation unknowns and vars
- var yaw = 0.0;
- var pitch = 0.0;
- var roll = 0.0;
- var x = 0.0;
- var y = 0.0;
- var z = 0.0;
- var t = 0.0;
- var sign = -1.0;
- var nbRevert = 0;
- var cross = Tmp.Vector3[0];
- var dot = 0.0;
- // step 1 : rotation around w
- // Rv3(u) = u1, and u1 belongs to plane xOz
- // Rv3(w) = w1 = w invariant
- var u1 = Tmp.Vector3[1];
- if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
- z = 1.0;
- }
- else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
- x = 1.0;
- }
- else {
- t = w.z / w.x;
- x = -t * Math.sqrt(1 / (1 + t * t));
- z = Math.sqrt(1 / (1 + t * t));
- }
- u1.x = x;
- u1.y = y;
- u1.z = z;
- u1.normalize();
- Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
- cross.normalize();
- if (Vector3.Dot(w, cross) < 0) {
- sign = 1.0;
- }
- dot = Vector3.Dot(u, u1);
- dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
- roll = Math.acos(dot) * sign;
- if (Vector3.Dot(u1, X) < 0) {
- roll = Math.PI + roll;
- u1 = u1.scaleInPlace(-1);
- nbRevert++;
- }
- // step 2 : rotate around u1
- // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
- // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
- var w2 = Tmp.Vector3[2];
- var v2 = Tmp.Vector3[3];
- x = 0.0;
- y = 0.0;
- z = 0.0;
- sign = -1.0;
- if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
- x = 1.0;
- }
- else {
- t = u1.z / u1.x;
- x = -t * Math.sqrt(1 / (1 + t * t));
- z = Math.sqrt(1 / (1 + t * t));
- }
- w2.x = x;
- w2.y = y;
- w2.z = z;
- w2.normalize();
- Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
- v2.normalize();
- Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
- cross.normalize();
- if (Vector3.Dot(u1, cross) < 0) {
- sign = 1.0;
- }
- dot = Vector3.Dot(w, w2);
- dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
- pitch = Math.acos(dot) * sign;
- if (Vector3.Dot(v2, Y) < 0) {
- pitch = Math.PI + pitch;
- nbRevert++;
- }
- // step 3 : rotate around v2
- // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
- sign = -1.0;
- Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
- cross.normalize();
- if (Vector3.Dot(cross, Y) < 0) {
- sign = 1.0;
- }
- dot = Vector3.Dot(u1, X);
- dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
- yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
- if (dot < 0 && nbRevert < 2) {
- yaw = Math.PI + yaw;
- }
- ref.x = pitch;
- ref.y = yaw;
- ref.z = roll;
- };
- return Vector3;
- })();
- BABYLON.Vector3 = Vector3;
- //Vector4 class created for EulerAngle class conversion to Quaternion
- var Vector4 = (function () {
- function Vector4(x, y, z, w) {
- this.x = x;
- this.y = y;
- this.z = z;
- this.w = w;
- }
- Vector4.prototype.toString = function () {
- return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
- };
- // Operators
- Vector4.prototype.asArray = function () {
- var result = [];
- this.toArray(result, 0);
- return result;
- };
- Vector4.prototype.toArray = function (array, index) {
- if (index === undefined) {
- index = 0;
- }
- array[index] = this.x;
- array[index + 1] = this.y;
- array[index + 2] = this.z;
- array[index + 3] = this.w;
- return this;
- };
- Vector4.prototype.addInPlace = function (otherVector) {
- this.x += otherVector.x;
- this.y += otherVector.y;
- this.z += otherVector.z;
- this.w += otherVector.w;
- return this;
- };
- Vector4.prototype.add = function (otherVector) {
- return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
- };
- Vector4.prototype.addToRef = function (otherVector, result) {
- result.x = this.x + otherVector.x;
- result.y = this.y + otherVector.y;
- result.z = this.z + otherVector.z;
- result.w = this.w + otherVector.w;
- return this;
- };
- Vector4.prototype.subtractInPlace = function (otherVector) {
- this.x -= otherVector.x;
- this.y -= otherVector.y;
- this.z -= otherVector.z;
- this.w -= otherVector.w;
- return this;
- };
- Vector4.prototype.subtract = function (otherVector) {
- return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
- };
- Vector4.prototype.subtractToRef = function (otherVector, result) {
- result.x = this.x - otherVector.x;
- result.y = this.y - otherVector.y;
- result.z = this.z - otherVector.z;
- result.w = this.w - otherVector.w;
- return this;
- };
- Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
- return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
- };
- Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
- result.x = this.x - x;
- result.y = this.y - y;
- result.z = this.z - z;
- result.w = this.w - w;
- return this;
- };
- Vector4.prototype.negate = function () {
- return new Vector4(-this.x, -this.y, -this.z, -this.w);
- };
- Vector4.prototype.scaleInPlace = function (scale) {
- this.x *= scale;
- this.y *= scale;
- this.z *= scale;
- this.w *= scale;
- return this;
- };
- Vector4.prototype.scale = function (scale) {
- return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
- };
- Vector4.prototype.scaleToRef = function (scale, result) {
- result.x = this.x * scale;
- result.y = this.y * scale;
- result.z = this.z * scale;
- result.w = this.w * scale;
- };
- Vector4.prototype.equals = function (otherVector) {
- return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
- };
- Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
- if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
- return otherVector
- && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
- && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
- && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
- && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
- };
- Vector4.prototype.equalsToFloats = function (x, y, z, w) {
- return this.x === x && this.y === y && this.z === z && this.w === w;
- };
- Vector4.prototype.multiplyInPlace = function (otherVector) {
- this.x *= otherVector.x;
- this.y *= otherVector.y;
- this.z *= otherVector.z;
- this.w *= otherVector.w;
- return this;
- };
- Vector4.prototype.multiply = function (otherVector) {
- return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
- };
- Vector4.prototype.multiplyToRef = function (otherVector, result) {
- result.x = this.x * otherVector.x;
- result.y = this.y * otherVector.y;
- result.z = this.z * otherVector.z;
- result.w = this.w * otherVector.w;
- return this;
- };
- Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
- return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
- };
- Vector4.prototype.divide = function (otherVector) {
- return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
- };
- Vector4.prototype.divideToRef = function (otherVector, result) {
- result.x = this.x / otherVector.x;
- result.y = this.y / otherVector.y;
- result.z = this.z / otherVector.z;
- result.w = this.w / otherVector.w;
- return this;
- };
- Vector4.prototype.MinimizeInPlace = function (other) {
- if (other.x < this.x)
- this.x = other.x;
- if (other.y < this.y)
- this.y = other.y;
- if (other.z < this.z)
- this.z = other.z;
- if (other.w < this.w)
- this.w = other.w;
- return this;
- };
- Vector4.prototype.MaximizeInPlace = function (other) {
- if (other.x > this.x)
- this.x = other.x;
- if (other.y > this.y)
- this.y = other.y;
- if (other.z > this.z)
- this.z = other.z;
- if (other.w > this.w)
- this.w = other.w;
- return this;
- };
- // Properties
- Vector4.prototype.length = function () {
- return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
- };
- Vector4.prototype.lengthSquared = function () {
- return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
- };
- // Methods
- Vector4.prototype.normalize = function () {
- var len = this.length();
- if (len === 0)
- return this;
- var num = 1.0 / len;
- this.x *= num;
- this.y *= num;
- this.z *= num;
- this.w *= num;
- return this;
- };
- Vector4.prototype.toVector3 = function () {
- return new Vector3(this.x, this.y, this.z);
- };
- Vector4.prototype.clone = function () {
- return new Vector4(this.x, this.y, this.z, this.w);
- };
- Vector4.prototype.copyFrom = function (source) {
- this.x = source.x;
- this.y = source.y;
- this.z = source.z;
- this.w = source.w;
- return this;
- };
- Vector4.prototype.copyFromFloats = function (x, y, z, w) {
- this.x = x;
- this.y = y;
- this.z = z;
- this.w = w;
- return this;
- };
- // Statics
- Vector4.FromArray = function (array, offset) {
- if (!offset) {
- offset = 0;
- }
- return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
- };
- Vector4.FromArrayToRef = function (array, offset, result) {
- result.x = array[offset];
- result.y = array[offset + 1];
- result.z = array[offset + 2];
- result.w = array[offset + 3];
- };
- Vector4.FromFloatArrayToRef = function (array, offset, result) {
- result.x = array[offset];
- result.y = array[offset + 1];
- result.z = array[offset + 2];
- result.w = array[offset + 3];
- };
- Vector4.FromFloatsToRef = function (x, y, z, w, result) {
- result.x = x;
- result.y = y;
- result.z = z;
- result.w = w;
- };
- Vector4.Zero = function () {
- return new Vector4(0, 0, 0, 0);
- };
- Vector4.Normalize = function (vector) {
- var result = Vector4.Zero();
- Vector4.NormalizeToRef(vector, result);
- return result;
- };
- Vector4.NormalizeToRef = function (vector, result) {
- result.copyFrom(vector);
- result.normalize();
- };
- Vector4.Minimize = function (left, right) {
- var min = left.clone();
- min.MinimizeInPlace(right);
- return min;
- };
- Vector4.Maximize = function (left, right) {
- var max = left.clone();
- max.MaximizeInPlace(right);
- return max;
- };
- Vector4.Distance = function (value1, value2) {
- return Math.sqrt(Vector4.DistanceSquared(value1, value2));
- };
- Vector4.DistanceSquared = function (value1, value2) {
- var x = value1.x - value2.x;
- var y = value1.y - value2.y;
- var z = value1.z - value2.z;
- var w = value1.w - value2.w;
- return (x * x) + (y * y) + (z * z) + (w * w);
- };
- Vector4.Center = function (value1, value2) {
- var center = value1.add(value2);
- center.scaleInPlace(0.5);
- return center;
- };
- return Vector4;
- })();
- BABYLON.Vector4 = Vector4;
- var Quaternion = (function () {
- function Quaternion(x, y, z, w) {
- if (x === void 0) { x = 0; }
- if (y === void 0) { y = 0; }
- if (z === void 0) { z = 0; }
- if (w === void 0) { w = 1; }
- this.x = x;
- this.y = y;
- this.z = z;
- this.w = w;
- }
- Quaternion.prototype.toString = function () {
- return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
- };
- Quaternion.prototype.asArray = function () {
- return [this.x, this.y, this.z, this.w];
- };
- Quaternion.prototype.equals = function (otherQuaternion) {
- return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
- };
- Quaternion.prototype.clone = function () {
- return new Quaternion(this.x, this.y, this.z, this.w);
- };
- Quaternion.prototype.copyFrom = function (other) {
- this.x = other.x;
- this.y = other.y;
- this.z = other.z;
- this.w = other.w;
- return this;
- };
- Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
- this.x = x;
- this.y = y;
- this.z = z;
- this.w = w;
- return this;
- };
- Quaternion.prototype.add = function (other) {
- return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
- };
- Quaternion.prototype.subtract = function (other) {
- return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
- };
- Quaternion.prototype.scale = function (value) {
- return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
- };
- Quaternion.prototype.multiply = function (q1) {
- var result = new Quaternion(0, 0, 0, 1.0);
- this.multiplyToRef(q1, result);
- return result;
- };
- Quaternion.prototype.multiplyToRef = function (q1, result) {
- var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
- var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
- var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
- var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
- result.copyFromFloats(x, y, z, w);
- return this;
- };
- Quaternion.prototype.multiplyInPlace = function (q1) {
- this.multiplyToRef(q1, this);
- return this;
- };
- Quaternion.prototype.conjugateToRef = function (ref) {
- ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
- return this;
- };
- Quaternion.prototype.conjugateInPlace = function () {
- this.x *= -1;
- this.y *= -1;
- this.z *= -1;
- return this;
- };
- Quaternion.prototype.conjugate = function () {
- var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
- return result;
- };
- Quaternion.prototype.length = function () {
- return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
- };
- Quaternion.prototype.normalize = function () {
- var length = 1.0 / this.length();
- this.x *= length;
- this.y *= length;
- this.z *= length;
- this.w *= length;
- return this;
- };
- Quaternion.prototype.toEulerAngles = function (order) {
- if (order === void 0) { order = "YZX"; }
- var result = Vector3.Zero();
- this.toEulerAnglesToRef(result, order);
- return result;
- };
- Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
- if (order === void 0) { order = "YZX"; }
- var heading, attitude, bank;
- var x = this.x, y = this.y, z = this.z, w = this.w;
- switch (order) {
- case "YZX":
- var test = x * y + z * w;
- if (test > 0.499) {
- heading = 2 * Math.atan2(x, w);
- attitude = Math.PI / 2;
- bank = 0;
- }
- if (test < -0.499) {
- heading = -2 * Math.atan2(x, w);
- attitude = -Math.PI / 2;
- bank = 0;
- }
- if (isNaN(heading)) {
- var sqx = x * x;
- var sqy = y * y;
- var sqz = z * z;
- heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
- attitude = Math.asin(2 * test); // attitude
- bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
- }
- break;
- default:
- throw new Error("Euler order " + order + " not supported yet.");
- }
- result.y = heading;
- result.z = attitude;
- result.x = bank;
- return this;
- };
- ;
- Quaternion.prototype.toRotationMatrix = function (result) {
- var xx = this.x * this.x;
- var yy = this.y * this.y;
- var zz = this.z * this.z;
- var xy = this.x * this.y;
- var zw = this.z * this.w;
- var zx = this.z * this.x;
- var yw = this.y * this.w;
- var yz = this.y * this.z;
- var xw = this.x * this.w;
- result.m[0] = 1.0 - (2.0 * (yy + zz));
- result.m[1] = 2.0 * (xy + zw);
- result.m[2] = 2.0 * (zx - yw);
- result.m[3] = 0;
- result.m[4] = 2.0 * (xy - zw);
- result.m[5] = 1.0 - (2.0 * (zz + xx));
- result.m[6] = 2.0 * (yz + xw);
- result.m[7] = 0;
- result.m[8] = 2.0 * (zx + yw);
- result.m[9] = 2.0 * (yz - xw);
- result.m[10] = 1.0 - (2.0 * (yy + xx));
- result.m[11] = 0;
- result.m[12] = 0;
- result.m[13] = 0;
- result.m[14] = 0;
- result.m[15] = 1.0;
- return this;
- };
- Quaternion.prototype.fromRotationMatrix = function (matrix) {
- Quaternion.FromRotationMatrixToRef(matrix, this);
- return this;
- };
- // Statics
- Quaternion.FromRotationMatrix = function (matrix) {
- var result = new Quaternion();
- Quaternion.FromRotationMatrixToRef(matrix, result);
- return result;
- };
- Quaternion.FromRotationMatrixToRef = function (matrix, result) {
- var data = matrix.m;
- var m11 = data[0], m12 = data[4], m13 = data[8];
- var m21 = data[1], m22 = data[5], m23 = data[9];
- var m31 = data[2], m32 = data[6], m33 = data[10];
- var trace = m11 + m22 + m33;
- var s;
- if (trace > 0) {
- s = 0.5 / Math.sqrt(trace + 1.0);
- result.w = 0.25 / s;
- result.x = (m32 - m23) * s;
- result.y = (m13 - m31) * s;
- result.z = (m21 - m12) * s;
- }
- else if (m11 > m22 && m11 > m33) {
- s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
- result.w = (m32 - m23) / s;
- result.x = 0.25 * s;
- result.y = (m12 + m21) / s;
- result.z = (m13 + m31) / s;
- }
- else if (m22 > m33) {
- s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
- result.w = (m13 - m31) / s;
- result.x = (m12 + m21) / s;
- result.y = 0.25 * s;
- result.z = (m23 + m32) / s;
- }
- else {
- s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
- result.w = (m21 - m12) / s;
- result.x = (m13 + m31) / s;
- result.y = (m23 + m32) / s;
- result.z = 0.25 * s;
- }
- };
- Quaternion.Inverse = function (q) {
- return new Quaternion(-q.x, -q.y, -q.z, q.w);
- };
- Quaternion.Identity = function () {
- return new Quaternion(0, 0, 0, 1);
- };
- Quaternion.RotationAxis = function (axis, angle) {
- var result = new Quaternion();
- var sin = Math.sin(angle / 2);
- axis.normalize();
- result.w = Math.cos(angle / 2);
- result.x = axis.x * sin;
- result.y = axis.y * sin;
- result.z = axis.z * sin;
- return result;
- };
- Quaternion.FromArray = function (array, offset) {
- if (!offset) {
- offset = 0;
- }
- return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
- };
- Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
- var result = new Quaternion();
- Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
- return result;
- };
- Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
- // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
- var halfRoll = roll * 0.5;
- var halfPitch = pitch * 0.5;
- var halfYaw = yaw * 0.5;
- var sinRoll = Math.sin(halfRoll);
- var cosRoll = Math.cos(halfRoll);
- var sinPitch = Math.sin(halfPitch);
- var cosPitch = Math.cos(halfPitch);
- var sinYaw = Math.sin(halfYaw);
- var cosYaw = Math.cos(halfYaw);
- result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
- result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
- result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
- result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
- };
- Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
- var result = new Quaternion();
- Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
- return result;
- };
- Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
- // Produces a quaternion from Euler angles in the z-x-z orientation
- var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
- var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
- var halfBeta = beta * 0.5;
- result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
- result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
- result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
- result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
- };
- Quaternion.Slerp = function (left, right, amount) {
- var num2;
- var num3;
- var num = amount;
- var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
- var flag = false;
- if (num4 < 0) {
- flag = true;
- num4 = -num4;
- }
- if (num4 > 0.999999) {
- num3 = 1 - num;
- num2 = flag ? -num : num;
- }
- else {
- var num5 = Math.acos(num4);
- var num6 = (1.0 / Math.sin(num5));
- num3 = (Math.sin((1.0 - num) * num5)) * num6;
- num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
- }
- 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));
- };
- return Quaternion;
- })();
- BABYLON.Quaternion = Quaternion;
- var Matrix = (function () {
- function Matrix() {
- this.m = new Float32Array(16);
- }
- // Properties
- Matrix.prototype.isIdentity = function () {
- if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
- return false;
- if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
- this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
- this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
- this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
- return false;
- return true;
- };
- Matrix.prototype.determinant = function () {
- var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
- var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
- var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
- var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
- var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
- var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
- return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
- (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
- (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
- };
- // Methods
- Matrix.prototype.toArray = function () {
- return this.m;
- };
- Matrix.prototype.asArray = function () {
- return this.toArray();
- };
- Matrix.prototype.invert = function () {
- this.invertToRef(this);
- return this;
- };
- Matrix.prototype.reset = function () {
- for (var index = 0; index < 16; index++) {
- this.m[index] = 0;
- }
- return this;
- };
- Matrix.prototype.add = function (other) {
- var result = new Matrix();
- this.addToRef(other, result);
- return result;
- };
- Matrix.prototype.addToRef = function (other, result) {
- for (var index = 0; index < 16; index++) {
- result.m[index] = this.m[index] + other.m[index];
- }
- return this;
- };
- Matrix.prototype.addToSelf = function (other) {
- for (var index = 0; index < 16; index++) {
- this.m[index] += other.m[index];
- }
- return this;
- };
- Matrix.prototype.invertToRef = function (other) {
- var l1 = this.m[0];
- var l2 = this.m[1];
- var l3 = this.m[2];
- var l4 = this.m[3];
- var l5 = this.m[4];
- var l6 = this.m[5];
- var l7 = this.m[6];
- var l8 = this.m[7];
- var l9 = this.m[8];
- var l10 = this.m[9];
- var l11 = this.m[10];
- var l12 = this.m[11];
- var l13 = this.m[12];
- var l14 = this.m[13];
- var l15 = this.m[14];
- var l16 = this.m[15];
- var l17 = (l11 * l16) - (l12 * l15);
- var l18 = (l10 * l16) - (l12 * l14);
- var l19 = (l10 * l15) - (l11 * l14);
- var l20 = (l9 * l16) - (l12 * l13);
- var l21 = (l9 * l15) - (l11 * l13);
- var l22 = (l9 * l14) - (l10 * l13);
- var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
- var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
- var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
- var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
- var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
- var l28 = (l7 * l16) - (l8 * l15);
- var l29 = (l6 * l16) - (l8 * l14);
- var l30 = (l6 * l15) - (l7 * l14);
- var l31 = (l5 * l16) - (l8 * l13);
- var l32 = (l5 * l15) - (l7 * l13);
- var l33 = (l5 * l14) - (l6 * l13);
- var l34 = (l7 * l12) - (l8 * l11);
- var l35 = (l6 * l12) - (l8 * l10);
- var l36 = (l6 * l11) - (l7 * l10);
- var l37 = (l5 * l12) - (l8 * l9);
- var l38 = (l5 * l11) - (l7 * l9);
- var l39 = (l5 * l10) - (l6 * l9);
- other.m[0] = l23 * l27;
- other.m[4] = l24 * l27;
- other.m[8] = l25 * l27;
- other.m[12] = l26 * l27;
- other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
- other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
- other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
- other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
- other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
- other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
- other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
- other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
- other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
- other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
- other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
- other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
- return this;
- };
- Matrix.prototype.setTranslation = function (vector3) {
- this.m[12] = vector3.x;
- this.m[13] = vector3.y;
- this.m[14] = vector3.z;
- return this;
- };
- Matrix.prototype.getTranslation = function () {
- return new Vector3(this.m[12], this.m[13], this.m[14]);
- };
- Matrix.prototype.multiply = function (other) {
- var result = new Matrix();
- this.multiplyToRef(other, result);
- return result;
- };
- Matrix.prototype.copyFrom = function (other) {
- for (var index = 0; index < 16; index++) {
- this.m[index] = other.m[index];
- }
- return this;
- };
- Matrix.prototype.copyToArray = function (array, offset) {
- if (offset === void 0) { offset = 0; }
- for (var index = 0; index < 16; index++) {
- array[offset + index] = this.m[index];
- }
- return this;
- };
- Matrix.prototype.multiplyToRef = function (other, result) {
- this.multiplyToArray(other, result.m, 0);
- return this;
- };
- Matrix.prototype.multiplyToArray = function (other, result, offset) {
- var tm0 = this.m[0];
- var tm1 = this.m[1];
- var tm2 = this.m[2];
- var tm3 = this.m[3];
- var tm4 = this.m[4];
- var tm5 = this.m[5];
- var tm6 = this.m[6];
- var tm7 = this.m[7];
- var tm8 = this.m[8];
- var tm9 = this.m[9];
- var tm10 = this.m[10];
- var tm11 = this.m[11];
- var tm12 = this.m[12];
- var tm13 = this.m[13];
- var tm14 = this.m[14];
- var tm15 = this.m[15];
- var om0 = other.m[0];
- var om1 = other.m[1];
- var om2 = other.m[2];
- var om3 = other.m[3];
- var om4 = other.m[4];
- var om5 = other.m[5];
- var om6 = other.m[6];
- var om7 = other.m[7];
- var om8 = other.m[8];
- var om9 = other.m[9];
- var om10 = other.m[10];
- var om11 = other.m[11];
- var om12 = other.m[12];
- var om13 = other.m[13];
- var om14 = other.m[14];
- var om15 = other.m[15];
- result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
- result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
- result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
- result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
- result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
- result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
- result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
- result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
- result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
- result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
- result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
- result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
- result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
- result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
- result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
- result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
- return this;
- };
- Matrix.prototype.equals = function (value) {
- return value &&
- (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
- this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
- this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
- this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
- };
- Matrix.prototype.clone = function () {
- 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]);
- };
- Matrix.prototype.decompose = function (scale, rotation, translation) {
- translation.x = this.m[12];
- translation.y = this.m[13];
- translation.z = this.m[14];
- var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
- var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
- var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
- scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
- scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
- scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
- if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
- rotation.x = 0;
- rotation.y = 0;
- rotation.z = 0;
- rotation.w = 1;
- return false;
- }
- 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);
- Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
- return true;
- };
- // Statics
- Matrix.FromArray = function (array, offset) {
- var result = new Matrix();
- if (!offset) {
- offset = 0;
- }
- Matrix.FromArrayToRef(array, offset, result);
- return result;
- };
- Matrix.FromArrayToRef = function (array, offset, result) {
- for (var index = 0; index < 16; index++) {
- result.m[index] = array[index + offset];
- }
- };
- Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
- for (var index = 0; index < 16; index++) {
- result.m[index] = array[index + offset] * scale;
- }
- };
- Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
- result.m[0] = initialM11;
- result.m[1] = initialM12;
- result.m[2] = initialM13;
- result.m[3] = initialM14;
- result.m[4] = initialM21;
- result.m[5] = initialM22;
- result.m[6] = initialM23;
- result.m[7] = initialM24;
- result.m[8] = initialM31;
- result.m[9] = initialM32;
- result.m[10] = initialM33;
- result.m[11] = initialM34;
- result.m[12] = initialM41;
- result.m[13] = initialM42;
- result.m[14] = initialM43;
- result.m[15] = initialM44;
- };
- Matrix.prototype.getRow = function (index) {
- if (index < 0 || index > 3) {
- return null;
- }
- var i = index * 4;
- return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
- };
- Matrix.prototype.setRow = function (index, row) {
- if (index < 0 || index > 3) {
- return this;
- }
- var i = index * 4;
- this.m[i + 0] = row.x;
- this.m[i + 1] = row.y;
- this.m[i + 2] = row.z;
- this.m[i + 3] = row.w;
- return this;
- };
- Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
- var result = new Matrix();
- result.m[0] = initialM11;
- result.m[1] = initialM12;
- result.m[2] = initialM13;
- result.m[3] = initialM14;
- result.m[4] = initialM21;
- result.m[5] = initialM22;
- result.m[6] = initialM23;
- result.m[7] = initialM24;
- result.m[8] = initialM31;
- result.m[9] = initialM32;
- result.m[10] = initialM33;
- result.m[11] = initialM34;
- result.m[12] = initialM41;
- result.m[13] = initialM42;
- result.m[14] = initialM43;
- result.m[15] = initialM44;
- return result;
- };
- Matrix.Compose = function (scale, rotation, translation) {
- var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
- var rotationMatrix = Matrix.Identity();
- rotation.toRotationMatrix(rotationMatrix);
- result = result.multiply(rotationMatrix);
- result.setTranslation(translation);
- return result;
- };
- Matrix.Identity = function () {
- return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
- };
- Matrix.IdentityToRef = function (result) {
- Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
- };
- Matrix.Zero = function () {
- return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
- };
- Matrix.RotationX = function (angle) {
- var result = new Matrix();
- Matrix.RotationXToRef(angle, result);
- return result;
- };
- Matrix.Invert = function (source) {
- var result = new Matrix();
- source.invertToRef(result);
- return result;
- };
- Matrix.RotationXToRef = function (angle, result) {
- var s = Math.sin(angle);
- var c = Math.cos(angle);
- result.m[0] = 1.0;
- result.m[15] = 1.0;
- result.m[5] = c;
- result.m[10] = c;
- result.m[9] = -s;
- result.m[6] = s;
- result.m[1] = 0;
- result.m[2] = 0;
- result.m[3] = 0;
- result.m[4] = 0;
- result.m[7] = 0;
- result.m[8] = 0;
- result.m[11] = 0;
- result.m[12] = 0;
- result.m[13] = 0;
- result.m[14] = 0;
- };
- Matrix.RotationY = function (angle) {
- var result = new Matrix();
- Matrix.RotationYToRef(angle, result);
- return result;
- };
- Matrix.RotationYToRef = function (angle, result) {
- var s = Math.sin(angle);
- var c = Math.cos(angle);
- result.m[5] = 1.0;
- result.m[15] = 1.0;
- result.m[0] = c;
- result.m[2] = -s;
- result.m[8] = s;
- result.m[10] = c;
- result.m[1] = 0;
- result.m[3] = 0;
- result.m[4] = 0;
- result.m[6] = 0;
- result.m[7] = 0;
- result.m[9] = 0;
- result.m[11] = 0;
- result.m[12] = 0;
- result.m[13] = 0;
- result.m[14] = 0;
- };
- Matrix.RotationZ = function (angle) {
- var result = new Matrix();
- Matrix.RotationZToRef(angle, result);
- return result;
- };
- Matrix.RotationZToRef = function (angle, result) {
- var s = Math.sin(angle);
- var c = Math.cos(angle);
- result.m[10] = 1.0;
- result.m[15] = 1.0;
- result.m[0] = c;
- result.m[1] = s;
- result.m[4] = -s;
- result.m[5] = c;
- result.m[2] = 0;
- result.m[3] = 0;
- result.m[6] = 0;
- result.m[7] = 0;
- result.m[8] = 0;
- result.m[9] = 0;
- result.m[11] = 0;
- result.m[12] = 0;
- result.m[13] = 0;
- result.m[14] = 0;
- };
- Matrix.RotationAxis = function (axis, angle) {
- var result = Matrix.Zero();
- Matrix.RotationAxisToRef(axis, angle, result);
- return result;
- };
- Matrix.RotationAxisToRef = function (axis, angle, result) {
- var s = Math.sin(-angle);
- var c = Math.cos(-angle);
- var c1 = 1 - c;
- axis.normalize();
- result.m[0] = (axis.x * axis.x) * c1 + c;
- result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
- result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
- result.m[3] = 0.0;
- result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
- result.m[5] = (axis.y * axis.y) * c1 + c;
- result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
- result.m[7] = 0.0;
- result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
- result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
- result.m[10] = (axis.z * axis.z) * c1 + c;
- result.m[11] = 0.0;
- result.m[15] = 1.0;
- };
- Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
- var result = new Matrix();
- Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
- return result;
- };
- Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
- Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
- this._tempQuaternion.toRotationMatrix(result);
- };
- Matrix.Scaling = function (x, y, z) {
- var result = Matrix.Zero();
- Matrix.ScalingToRef(x, y, z, result);
- return result;
- };
- Matrix.ScalingToRef = function (x, y, z, result) {
- result.m[0] = x;
- result.m[1] = 0;
- result.m[2] = 0;
- result.m[3] = 0;
- result.m[4] = 0;
- result.m[5] = y;
- result.m[6] = 0;
- result.m[7] = 0;
- result.m[8] = 0;
- result.m[9] = 0;
- result.m[10] = z;
- result.m[11] = 0;
- result.m[12] = 0;
- result.m[13] = 0;
- result.m[14] = 0;
- result.m[15] = 1.0;
- };
- Matrix.Translation = function (x, y, z) {
- var result = Matrix.Identity();
- Matrix.TranslationToRef(x, y, z, result);
- return result;
- };
- Matrix.TranslationToRef = function (x, y, z, result) {
- Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
- };
- Matrix.Lerp = function (startValue, endValue, gradient) {
- var startScale = new Vector3(0, 0, 0);
- var startRotation = new Quaternion();
- var startTranslation = new Vector3(0, 0, 0);
- startValue.decompose(startScale, startRotation, startTranslation);
- var endScale = new Vector3(0, 0, 0);
- var endRotation = new Quaternion();
- var endTranslation = new Vector3(0, 0, 0);
- endValue.decompose(endScale, endRotation, endTranslation);
- var resultScale = Vector3.Lerp(startScale, endScale, gradient);
- var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
- var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
- return Matrix.Compose(resultScale, resultRotation, resultTranslation);
- };
- Matrix.LookAtLH = function (eye, target, up) {
- var result = Matrix.Zero();
- Matrix.LookAtLHToRef(eye, target, up, result);
- return result;
- };
- Matrix.LookAtLHToRef = function (eye, target, up, result) {
- // Z axis
- target.subtractToRef(eye, this._zAxis);
- this._zAxis.normalize();
- // X axis
- Vector3.CrossToRef(up, this._zAxis, this._xAxis);
- if (this._xAxis.lengthSquared() === 0) {
- this._xAxis.x = 1.0;
- }
- else {
- this._xAxis.normalize();
- }
- // Y axis
- Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
- this._yAxis.normalize();
- // Eye angles
- var ex = -Vector3.Dot(this._xAxis, eye);
- var ey = -Vector3.Dot(this._yAxis, eye);
- var ez = -Vector3.Dot(this._zAxis, eye);
- 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);
- };
- Matrix.OrthoLH = function (width, height, znear, zfar) {
- var matrix = Matrix.Zero();
- Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
- return matrix;
- };
- Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
- var hw = 2.0 / width;
- var hh = 2.0 / height;
- var id = 1.0 / (zfar - znear);
- var nid = znear / (znear - zfar);
- Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
- };
- Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
- var matrix = Matrix.Zero();
- Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
- return matrix;
- };
- Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
- result.m[0] = 2.0 / (right - left);
- result.m[1] = result.m[2] = result.m[3] = 0;
- result.m[5] = 2.0 / (top - bottom);
- result.m[4] = result.m[6] = result.m[7] = 0;
- result.m[10] = -1.0 / (znear - zfar);
- result.m[8] = result.m[9] = result.m[11] = 0;
- result.m[12] = (left + right) / (left - right);
- result.m[13] = (top + bottom) / (bottom - top);
- result.m[14] = znear / (znear - zfar);
- result.m[15] = 1.0;
- };
- Matrix.PerspectiveLH = function (width, height, znear, zfar) {
- var matrix = Matrix.Zero();
- matrix.m[0] = (2.0 * znear) / width;
- matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
- matrix.m[5] = (2.0 * znear) / height;
- matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
- matrix.m[10] = -zfar / (znear - zfar);
- matrix.m[8] = matrix.m[9] = 0.0;
- matrix.m[11] = 1.0;
- matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
- matrix.m[14] = (znear * zfar) / (znear - zfar);
- return matrix;
- };
- Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
- var matrix = Matrix.Zero();
- Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
- return matrix;
- };
- Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
- if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
- var tan = 1.0 / (Math.tan(fov * 0.5));
- if (isVerticalFovFixed) {
- result.m[0] = tan / aspect;
- }
- else {
- result.m[0] = tan;
- }
- result.m[1] = result.m[2] = result.m[3] = 0.0;
- if (isVerticalFovFixed) {
- result.m[5] = tan;
- }
- else {
- result.m[5] = tan * aspect;
- }
- result.m[4] = result.m[6] = result.m[7] = 0.0;
- result.m[8] = result.m[9] = 0.0;
- result.m[10] = -zfar / (znear - zfar);
- result.m[11] = 1.0;
- result.m[12] = result.m[13] = result.m[15] = 0.0;
- result.m[14] = (znear * zfar) / (znear - zfar);
- };
- Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
- var cw = viewport.width;
- var ch = viewport.height;
- var cx = viewport.x;
- var cy = viewport.y;
- 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);
- return world.multiply(view).multiply(projection).multiply(viewportMatrix);
- };
- Matrix.GetAsMatrix2x2 = function (matrix) {
- return new Float32Array([
- matrix.m[0], matrix.m[1],
- matrix.m[4], matrix.m[5]
- ]);
- };
- Matrix.GetAsMatrix3x3 = function (matrix) {
- return new Float32Array([
- matrix.m[0], matrix.m[1], matrix.m[2],
- matrix.m[4], matrix.m[5], matrix.m[6],
- matrix.m[8], matrix.m[9], matrix.m[10]
- ]);
- };
- Matrix.Transpose = function (matrix) {
- var result = new Matrix();
- result.m[0] = matrix.m[0];
- result.m[1] = matrix.m[4];
- result.m[2] = matrix.m[8];
- result.m[3] = matrix.m[12];
- result.m[4] = matrix.m[1];
- result.m[5] = matrix.m[5];
- result.m[6] = matrix.m[9];
- result.m[7] = matrix.m[13];
- result.m[8] = matrix.m[2];
- result.m[9] = matrix.m[6];
- result.m[10] = matrix.m[10];
- result.m[11] = matrix.m[14];
- result.m[12] = matrix.m[3];
- result.m[13] = matrix.m[7];
- result.m[14] = matrix.m[11];
- result.m[15] = matrix.m[15];
- return result;
- };
- Matrix.Reflection = function (plane) {
- var matrix = new Matrix();
- Matrix.ReflectionToRef(plane, matrix);
- return matrix;
- };
- Matrix.ReflectionToRef = function (plane, result) {
- plane.normalize();
- var x = plane.normal.x;
- var y = plane.normal.y;
- var z = plane.normal.z;
- var temp = -2 * x;
- var temp2 = -2 * y;
- var temp3 = -2 * z;
- result.m[0] = (temp * x) + 1;
- result.m[1] = temp2 * x;
- result.m[2] = temp3 * x;
- result.m[3] = 0.0;
- result.m[4] = temp * y;
- result.m[5] = (temp2 * y) + 1;
- result.m[6] = temp3 * y;
- result.m[7] = 0.0;
- result.m[8] = temp * z;
- result.m[9] = temp2 * z;
- result.m[10] = (temp3 * z) + 1;
- result.m[11] = 0.0;
- result.m[12] = temp * plane.d;
- result.m[13] = temp2 * plane.d;
- result.m[14] = temp3 * plane.d;
- result.m[15] = 1.0;
- };
- Matrix._tempQuaternion = new Quaternion();
- Matrix._xAxis = Vector3.Zero();
- Matrix._yAxis = Vector3.Zero();
- Matrix._zAxis = Vector3.Zero();
- return Matrix;
- })();
- BABYLON.Matrix = Matrix;
- var Plane = (function () {
- function Plane(a, b, c, d) {
- this.normal = new Vector3(a, b, c);
- this.d = d;
- }
- Plane.prototype.asArray = function () {
- return [this.normal.x, this.normal.y, this.normal.z, this.d];
- };
- // Methods
- Plane.prototype.clone = function () {
- return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
- };
- Plane.prototype.normalize = function () {
- var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
- var magnitude = 0;
- if (norm !== 0) {
- magnitude = 1.0 / norm;
- }
- this.normal.x *= magnitude;
- this.normal.y *= magnitude;
- this.normal.z *= magnitude;
- this.d *= magnitude;
- return this;
- };
- Plane.prototype.transform = function (transformation) {
- var transposedMatrix = Matrix.Transpose(transformation);
- var x = this.normal.x;
- var y = this.normal.y;
- var z = this.normal.z;
- var d = this.d;
- var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
- var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
- var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
- var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
- return new Plane(normalX, normalY, normalZ, finalD);
- };
- Plane.prototype.dotCoordinate = function (point) {
- return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
- };
- Plane.prototype.copyFromPoints = function (point1, point2, point3) {
- var x1 = point2.x - point1.x;
- var y1 = point2.y - point1.y;
- var z1 = point2.z - point1.z;
- var x2 = point3.x - point1.x;
- var y2 = point3.y - point1.y;
- var z2 = point3.z - point1.z;
- var yz = (y1 * z2) - (z1 * y2);
- var xz = (z1 * x2) - (x1 * z2);
- var xy = (x1 * y2) - (y1 * x2);
- var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
- var invPyth;
- if (pyth !== 0) {
- invPyth = 1.0 / pyth;
- }
- else {
- invPyth = 0;
- }
- this.normal.x = yz * invPyth;
- this.normal.y = xz * invPyth;
- this.normal.z = xy * invPyth;
- this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
- return this;
- };
- Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
- var dot = Vector3.Dot(this.normal, direction);
- return (dot <= epsilon);
- };
- Plane.prototype.signedDistanceTo = function (point) {
- return Vector3.Dot(point, this.normal) + this.d;
- };
- // Statics
- Plane.FromArray = function (array) {
- return new Plane(array[0], array[1], array[2], array[3]);
- };
- Plane.FromPoints = function (point1, point2, point3) {
- var result = new Plane(0, 0, 0, 0);
- result.copyFromPoints(point1, point2, point3);
- return result;
- };
- Plane.FromPositionAndNormal = function (origin, normal) {
- var result = new Plane(0, 0, 0, 0);
- normal.normalize();
- result.normal = normal;
- result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
- return result;
- };
- Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
- var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
- return Vector3.Dot(point, normal) + d;
- };
- return Plane;
- })();
- BABYLON.Plane = Plane;
- var Viewport = (function () {
- function Viewport(x, y, width, height) {
- this.x = x;
- this.y = y;
- this.width = width;
- this.height = height;
- }
- Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
- return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
- };
- return Viewport;
- })();
- BABYLON.Viewport = Viewport;
- var Frustum = (function () {
- function Frustum() {
- }
- Frustum.GetPlanes = function (transform) {
- var frustumPlanes = [];
- for (var index = 0; index < 6; index++) {
- frustumPlanes.push(new Plane(0, 0, 0, 0));
- }
- Frustum.GetPlanesToRef(transform, frustumPlanes);
- return frustumPlanes;
- };
- Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
- // Near
- frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
- frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
- frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
- frustumPlanes[0].d = transform.m[15] + transform.m[14];
- frustumPlanes[0].normalize();
- // Far
- frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
- frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
- frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
- frustumPlanes[1].d = transform.m[15] - transform.m[14];
- frustumPlanes[1].normalize();
- // Left
- frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
- frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
- frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
- frustumPlanes[2].d = transform.m[15] + transform.m[12];
- frustumPlanes[2].normalize();
- // Right
- frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
- frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
- frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
- frustumPlanes[3].d = transform.m[15] - transform.m[12];
- frustumPlanes[3].normalize();
- // Top
- frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
- frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
- frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
- frustumPlanes[4].d = transform.m[15] - transform.m[13];
- frustumPlanes[4].normalize();
- // Bottom
- frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
- frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
- frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
- frustumPlanes[5].d = transform.m[15] + transform.m[13];
- frustumPlanes[5].normalize();
- };
- return Frustum;
- })();
- BABYLON.Frustum = Frustum;
- (function (Space) {
- Space[Space["LOCAL"] = 0] = "LOCAL";
- Space[Space["WORLD"] = 1] = "WORLD";
- })(BABYLON.Space || (BABYLON.Space = {}));
- var Space = BABYLON.Space;
- var Axis = (function () {
- function Axis() {
- }
- Axis.X = new Vector3(1, 0, 0);
- Axis.Y = new Vector3(0, 1, 0);
- Axis.Z = new Vector3(0, 0, 1);
- return Axis;
- })();
- BABYLON.Axis = Axis;
- ;
- var BezierCurve = (function () {
- function BezierCurve() {
- }
- BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
- // Extract X (which is equal to time here)
- var f0 = 1 - 3 * x2 + 3 * x1;
- var f1 = 3 * x2 - 6 * x1;
- var f2 = 3 * x1;
- var refinedT = t;
- for (var i = 0; i < 5; i++) {
- var refinedT2 = refinedT * refinedT;
- var refinedT3 = refinedT2 * refinedT;
- var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
- var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
- refinedT -= (x - t) * slope;
- refinedT = Math.min(1, Math.max(0, refinedT));
- }
- // Resolve cubic bezier for the given x
- return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
- 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
- Math.pow(refinedT, 3);
- };
- return BezierCurve;
- })();
- BABYLON.BezierCurve = BezierCurve;
- (function (Orientation) {
- Orientation[Orientation["CW"] = 0] = "CW";
- Orientation[Orientation["CCW"] = 1] = "CCW";
- })(BABYLON.Orientation || (BABYLON.Orientation = {}));
- var Orientation = BABYLON.Orientation;
- var Angle = (function () {
- function Angle(radians) {
- var _this = this;
- this.degrees = function () { return _this._radians * 180 / Math.PI; };
- this.radians = function () { return _this._radians; };
- this._radians = radians;
- if (this._radians < 0)
- this._radians += (2 * Math.PI);
- }
- Angle.BetweenTwoPoints = function (a, b) {
- var delta = b.subtract(a);
- var theta = Math.atan2(delta.y, delta.x);
- return new Angle(theta);
- };
- Angle.FromRadians = function (radians) {
- return new Angle(radians);
- };
- Angle.FromDegrees = function (degrees) {
- return new Angle(degrees * Math.PI / 180);
- };
- return Angle;
- })();
- BABYLON.Angle = Angle;
- var Arc2 = (function () {
- function Arc2(startPoint, midPoint, endPoint) {
- this.startPoint = startPoint;
- this.midPoint = midPoint;
- this.endPoint = endPoint;
- var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
- var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
- var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
- var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
- 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);
- this.radius = this.centerPoint.subtract(this.startPoint).length();
- this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
- var a1 = this.startAngle.degrees();
- var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
- var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
- // angles correction
- if (a2 - a1 > +180.0)
- a2 -= 360.0;
- if (a2 - a1 < -180.0)
- a2 += 360.0;
- if (a3 - a2 > +180.0)
- a3 -= 360.0;
- if (a3 - a2 < -180.0)
- a3 += 360.0;
- this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
- this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
- }
- return Arc2;
- })();
- BABYLON.Arc2 = Arc2;
- var Path2 = (function () {
- function Path2(x, y) {
- this._points = new Array();
- this._length = 0;
- this.closed = false;
- this._points.push(new Vector2(x, y));
- }
- Path2.prototype.addLineTo = function (x, y) {
- if (closed) {
- //Tools.Error("cannot add lines to closed paths");
- return this;
- }
- var newPoint = new Vector2(x, y);
- var previousPoint = this._points[this._points.length - 1];
- this._points.push(newPoint);
- this._length += newPoint.subtract(previousPoint).length();
- return this;
- };
- Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
- if (numberOfSegments === void 0) { numberOfSegments = 36; }
- if (closed) {
- //Tools.Error("cannot add arcs to closed paths");
- return this;
- }
- var startPoint = this._points[this._points.length - 1];
- var midPoint = new Vector2(midX, midY);
- var endPoint = new Vector2(endX, endY);
- var arc = new Arc2(startPoint, midPoint, endPoint);
- var increment = arc.angle.radians() / numberOfSegments;
- if (arc.orientation === Orientation.CW)
- increment *= -1;
- var currentAngle = arc.startAngle.radians() + increment;
- for (var i = 0; i < numberOfSegments; i++) {
- var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
- var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
- this.addLineTo(x, y);
- currentAngle += increment;
- }
- return this;
- };
- Path2.prototype.close = function () {
- this.closed = true;
- return this;
- };
- Path2.prototype.length = function () {
- var result = this._length;
- if (!this.closed) {
- var lastPoint = this._points[this._points.length - 1];
- var firstPoint = this._points[0];
- result += (firstPoint.subtract(lastPoint).length());
- }
- return result;
- };
- Path2.prototype.getPoints = function () {
- return this._points;
- };
- Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
- if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
- //Tools.Error("normalized length position should be between 0 and 1.");
- return Vector2.Zero();
- }
- var lengthPosition = normalizedLengthPosition * this.length();
- var previousOffset = 0;
- for (var i = 0; i < this._points.length; i++) {
- var j = (i + 1) % this._points.length;
- var a = this._points[i];
- var b = this._points[j];
- var bToA = b.subtract(a);
- var nextOffset = (bToA.length() + previousOffset);
- if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
- var dir = bToA.normalize();
- var localOffset = lengthPosition - previousOffset;
- return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
- }
- previousOffset = nextOffset;
- }
- //Tools.Error("internal error");
- return Vector2.Zero();
- };
- Path2.StartingAt = function (x, y) {
- return new Path2(x, y);
- };
- return Path2;
- })();
- BABYLON.Path2 = Path2;
- var Path3D = (function () {
- /**
- * new Path3D(path, normal, raw)
- * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
- * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
- * path : an array of Vector3, the curve axis of the Path3D
- * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
- * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
- */
- function Path3D(path, firstNormal, raw) {
- this.path = path;
- this._curve = new Array();
- this._distances = new Array();
- this._tangents = new Array();
- this._normals = new Array();
- this._binormals = new Array();
- for (var p = 0; p < path.length; p++) {
- this._curve[p] = path[p].clone(); // hard copy
- }
- this._raw = raw || false;
- this._compute(firstNormal);
- }
- /**
- * Returns the Path3D array of successive Vector3 designing its curve.
- */
- Path3D.prototype.getCurve = function () {
- return this._curve;
- };
- /**
- * Returns an array populated with tangent vectors on each Path3D curve point.
- */
- Path3D.prototype.getTangents = function () {
- return this._tangents;
- };
- /**
- * Returns an array populated with normal vectors on each Path3D curve point.
- */
- Path3D.prototype.getNormals = function () {
- return this._normals;
- };
- /**
- * Returns an array populated with binormal vectors on each Path3D curve point.
- */
- Path3D.prototype.getBinormals = function () {
- return this._binormals;
- };
- /**
- * Returns an array populated with distances (float) of the i-th point from the first curve point.
- */
- Path3D.prototype.getDistances = function () {
- return this._distances;
- };
- /**
- * Forces the Path3D tangent, normal, binormal and distance recomputation.
- * Returns the same object updated.
- */
- Path3D.prototype.update = function (path, firstNormal) {
- for (var p = 0; p < path.length; p++) {
- this._curve[p].x = path[p].x;
- this._curve[p].y = path[p].y;
- this._curve[p].z = path[p].z;
- }
- this._compute(firstNormal);
- return this;
- };
- // private function compute() : computes tangents, normals and binormals
- Path3D.prototype._compute = function (firstNormal) {
- var l = this._curve.length;
- // first and last tangents
- this._tangents[0] = this._getFirstNonNullVector(0);
- if (!this._raw) {
- this._tangents[0].normalize();
- }
- this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
- if (!this._raw) {
- this._tangents[l - 1].normalize();
- }
- // normals and binormals at first point : arbitrary vector with _normalVector()
- var tg0 = this._tangents[0];
- var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
- this._normals[0] = pp0;
- if (!this._raw) {
- this._normals[0].normalize();
- }
- this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
- if (!this._raw) {
- this._binormals[0].normalize();
- }
- this._distances[0] = 0;
- // normals and binormals : next points
- var prev; // previous vector (segment)
- var cur; // current vector (segment)
- var curTang; // current tangent
- // previous normal
- var prevBinor; // previous binormal
- for (var i = 1; i < l; i++) {
- // tangents
- prev = this._getLastNonNullVector(i);
- if (i < l - 1) {
- cur = this._getFirstNonNullVector(i);
- this._tangents[i] = prev.add(cur);
- this._tangents[i].normalize();
- }
- this._distances[i] = this._distances[i - 1] + prev.length();
- // normals and binormals
- // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
- curTang = this._tangents[i];
- prevBinor = this._binormals[i - 1];
- this._normals[i] = Vector3.Cross(prevBinor, curTang);
- if (!this._raw) {
- this._normals[i].normalize();
- }
- this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
- if (!this._raw) {
- this._binormals[i].normalize();
- }
- }
- };
- // private function getFirstNonNullVector(index)
- // returns the first non null vector from index : curve[index + N].subtract(curve[index])
- Path3D.prototype._getFirstNonNullVector = function (index) {
- var i = 1;
- var nNVector = this._curve[index + i].subtract(this._curve[index]);
- while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
- i++;
- nNVector = this._curve[index + i].subtract(this._curve[index]);
- }
- return nNVector;
- };
- // private function getLastNonNullVector(index)
- // returns the last non null vector from index : curve[index].subtract(curve[index - N])
- Path3D.prototype._getLastNonNullVector = function (index) {
- var i = 1;
- var nLVector = this._curve[index].subtract(this._curve[index - i]);
- while (nLVector.length() === 0 && index > i + 1) {
- i++;
- nLVector = this._curve[index].subtract(this._curve[index - i]);
- }
- return nLVector;
- };
- // private function normalVector(v0, vt, va) :
- // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
- // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
- Path3D.prototype._normalVector = function (v0, vt, va) {
- var normal0;
- if (va === undefined || va === null) {
- var point;
- if (!MathTools.WithinEpsilon(vt.y, 1, BABYLON.Epsilon)) {
- point = new Vector3(0, -1, 0);
- }
- else if (!MathTools.WithinEpsilon(vt.x, 1, BABYLON.Epsilon)) {
- point = new Vector3(1, 0, 0);
- }
- else if (!MathTools.WithinEpsilon(vt.z, 1, BABYLON.Epsilon)) {
- point = new Vector3(0, 0, 1);
- }
- normal0 = Vector3.Cross(vt, point);
- }
- else {
- normal0 = Vector3.Cross(vt, va);
- Vector3.CrossToRef(normal0, vt, normal0);
- }
- normal0.normalize();
- return normal0;
- };
- return Path3D;
- })();
- BABYLON.Path3D = Path3D;
- var Curve3 = (function () {
- /**
- * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
- * A Curve3 is designed from a series of successive Vector3.
- * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
- */
- function Curve3(points) {
- this._length = 0;
- this._points = points;
- this._length = this._computeLength(points);
- }
- /**
- * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
- * @param v0 (Vector3) the origin point of the Quadratic Bezier
- * @param v1 (Vector3) the control point
- * @param v2 (Vector3) the end point of the Quadratic Bezier
- * @param nbPoints (integer) the wanted number of points in the curve
- */
- Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
- nbPoints = nbPoints > 2 ? nbPoints : 3;
- var bez = new Array();
- var equation = function (t, val0, val1, val2) {
- var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
- return res;
- };
- for (var i = 0; i <= nbPoints; i++) {
- 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)));
- }
- return new Curve3(bez);
- };
- /**
- * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
- * @param v0 (Vector3) the origin point of the Cubic Bezier
- * @param v1 (Vector3) the first control point
- * @param v2 (Vector3) the second control point
- * @param v3 (Vector3) the end point of the Cubic Bezier
- * @param nbPoints (integer) the wanted number of points in the curve
- */
- Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
- nbPoints = nbPoints > 3 ? nbPoints : 4;
- var bez = new Array();
- var equation = function (t, val0, val1, val2, val3) {
- var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
- return res;
- };
- for (var i = 0; i <= nbPoints; i++) {
- 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)));
- }
- return new Curve3(bez);
- };
- /**
- * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
- * @param p1 (Vector3) the origin point of the Hermite Spline
- * @param t1 (Vector3) the tangent vector at the origin point
- * @param p2 (Vector3) the end point of the Hermite Spline
- * @param t2 (Vector3) the tangent vector at the end point
- * @param nbPoints (integer) the wanted number of points in the curve
- */
- Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
- var hermite = new Array();
- var step = 1 / nbPoints;
- for (var i = 0; i <= nbPoints; i++) {
- hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
- }
- return new Curve3(hermite);
- };
- /**
- * Returns the Curve3 stored array of successive Vector3
- */
- Curve3.prototype.getPoints = function () {
- return this._points;
- };
- /**
- * Returns the computed length (float) of the curve.
- */
- Curve3.prototype.length = function () {
- return this._length;
- };
- /**
- * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
- * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
- * curveA and curveB keep unchanged.
- */
- Curve3.prototype.continue = function (curve) {
- var lastPoint = this._points[this._points.length - 1];
- var continuedPoints = this._points.slice();
- var curvePoints = curve.getPoints();
- for (var i = 1; i < curvePoints.length; i++) {
- continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
- }
- var continuedCurve = new Curve3(continuedPoints);
- return continuedCurve;
- };
- Curve3.prototype._computeLength = function (path) {
- var l = 0;
- for (var i = 1; i < path.length; i++) {
- l += (path[i].subtract(path[i - 1])).length();
- }
- return l;
- };
- return Curve3;
- })();
- BABYLON.Curve3 = Curve3;
- // SphericalHarmonics
- var SphericalHarmonics = (function () {
- function SphericalHarmonics() {
- this.L00 = Vector3.Zero();
- this.L1_1 = Vector3.Zero();
- this.L10 = Vector3.Zero();
- this.L11 = Vector3.Zero();
- this.L2_2 = Vector3.Zero();
- this.L2_1 = Vector3.Zero();
- this.L20 = Vector3.Zero();
- this.L21 = Vector3.Zero();
- this.L22 = Vector3.Zero();
- }
- SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
- var colorVector = new Vector3(color.r, color.g, color.b);
- var c = colorVector.scale(deltaSolidAngle);
- this.L00 = this.L00.add(c.scale(0.282095));
- this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
- this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
- this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
- this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
- this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
- this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
- this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
- this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
- };
- SphericalHarmonics.prototype.scale = function (scale) {
- this.L00 = this.L00.scale(scale);
- this.L1_1 = this.L1_1.scale(scale);
- this.L10 = this.L10.scale(scale);
- this.L11 = this.L11.scale(scale);
- this.L2_2 = this.L2_2.scale(scale);
- this.L2_1 = this.L2_1.scale(scale);
- this.L20 = this.L20.scale(scale);
- this.L21 = this.L21.scale(scale);
- this.L22 = this.L22.scale(scale);
- };
- return SphericalHarmonics;
- })();
- BABYLON.SphericalHarmonics = SphericalHarmonics;
- // SphericalPolynomial
- var SphericalPolynomial = (function () {
- function SphericalPolynomial() {
- this.x = Vector3.Zero();
- this.y = Vector3.Zero();
- this.z = Vector3.Zero();
- this.xx = Vector3.Zero();
- this.yy = Vector3.Zero();
- this.zz = Vector3.Zero();
- this.xy = Vector3.Zero();
- this.yz = Vector3.Zero();
- this.zx = Vector3.Zero();
- }
- SphericalPolynomial.prototype.addAmbient = function (color) {
- var colorVector = new Vector3(color.r, color.g, color.b);
- this.xx = this.xx.add(colorVector);
- this.yy = this.yy.add(colorVector);
- this.zz = this.zz.add(colorVector);
- };
- SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
- var result = new SphericalPolynomial();
- result.x = harmonics.L11.scale(1.02333);
- result.y = harmonics.L1_1.scale(1.02333);
- result.z = harmonics.L10.scale(1.02333);
- result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
- result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
- result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
- result.yz = harmonics.L2_1.scale(0.858086);
- result.zx = harmonics.L21.scale(0.858086);
- result.xy = harmonics.L2_2.scale(0.858086);
- return result;
- };
- return SphericalPolynomial;
- })();
- BABYLON.SphericalPolynomial = SphericalPolynomial;
- // Vertex formats
- var PositionNormalVertex = (function () {
- function PositionNormalVertex(position, normal) {
- if (position === void 0) { position = Vector3.Zero(); }
- if (normal === void 0) { normal = Vector3.Up(); }
- this.position = position;
- this.normal = normal;
- }
- PositionNormalVertex.prototype.clone = function () {
- return new PositionNormalVertex(this.position.clone(), this.normal.clone());
- };
- return PositionNormalVertex;
- })();
- BABYLON.PositionNormalVertex = PositionNormalVertex;
- var PositionNormalTextureVertex = (function () {
- function PositionNormalTextureVertex(position, normal, uv) {
- if (position === void 0) { position = Vector3.Zero(); }
- if (normal === void 0) { normal = Vector3.Up(); }
- if (uv === void 0) { uv = Vector2.Zero(); }
- this.position = position;
- this.normal = normal;
- this.uv = uv;
- }
- PositionNormalTextureVertex.prototype.clone = function () {
- return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
- };
- return PositionNormalTextureVertex;
- })();
- BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
- // Temporary pre-allocated objects for engine internal use
- // usage in any internal function :
- // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
- // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
- var Tmp = (function () {
- function Tmp() {
- }
- Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
- Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
- Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
- Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
- Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
- Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
- Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
- Matrix.Zero(), Matrix.Zero(),
- Matrix.Zero(), Matrix.Zero(),
- Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
- return Tmp;
- })();
- BABYLON.Tmp = Tmp;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- function generateSerializableMember(type, sourceName) {
- return function (target, propertyKey) {
- if (!target.__serializableMembers) {
- target.__serializableMembers = {};
- }
- target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
- };
- }
- function serialize(sourceName) {
- return generateSerializableMember(0, sourceName); // value member
- }
- BABYLON.serialize = serialize;
- function serializeAsTexture(sourceName) {
- return generateSerializableMember(1, sourceName); // texture member
- }
- BABYLON.serializeAsTexture = serializeAsTexture;
- function serializeAsColor3(sourceName) {
- return generateSerializableMember(2, sourceName); // color3 member
- }
- BABYLON.serializeAsColor3 = serializeAsColor3;
- function serializeAsFresnelParameters(sourceName) {
- return generateSerializableMember(3, sourceName); // fresnel parameters member
- }
- BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
- function serializeAsVector2(sourceName) {
- return generateSerializableMember(4, sourceName); // vector2 member
- }
- BABYLON.serializeAsVector2 = serializeAsVector2;
- function serializeAsVector3(sourceName) {
- return generateSerializableMember(5, sourceName); // vector3 member
- }
- BABYLON.serializeAsVector3 = serializeAsVector3;
- function serializeAsMeshReference(sourceName) {
- return generateSerializableMember(6, sourceName); // mesh reference member
- }
- BABYLON.serializeAsMeshReference = serializeAsMeshReference;
- var SerializationHelper = (function () {
- function SerializationHelper() {
- }
- SerializationHelper.Serialize = function (entity, serializationObject) {
- if (!serializationObject) {
- serializationObject = {};
- }
- // Tags
- serializationObject.tags = BABYLON.Tags.GetTags(entity);
- // Properties
- for (var property in entity.__serializableMembers) {
- var propertyDescriptor = entity.__serializableMembers[property];
- var targetPropertyName = propertyDescriptor.sourceName || property;
- var propertyType = propertyDescriptor.type;
- var sourceProperty = entity[property];
- if (sourceProperty !== undefined && sourceProperty !== null) {
- switch (propertyType) {
- case 0:
- serializationObject[targetPropertyName] = sourceProperty;
- break;
- case 1:
- serializationObject[targetPropertyName] = sourceProperty.serialize();
- break;
- case 2:
- serializationObject[targetPropertyName] = sourceProperty.asArray();
- break;
- case 3:
- serializationObject[targetPropertyName] = sourceProperty.serialize();
- break;
- case 4:
- serializationObject[targetPropertyName] = sourceProperty.asArray();
- break;
- case 5:
- serializationObject[targetPropertyName] = sourceProperty.asArray();
- break;
- case 6:
- serializationObject[targetPropertyName] = sourceProperty.id;
- break;
- }
- }
- }
- return serializationObject;
- };
- SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
- var destination = creationFunction();
- // Tags
- BABYLON.Tags.AddTagsTo(destination, source.tags);
- // Properties
- for (var property in destination.__serializableMembers) {
- var propertyDescriptor = destination.__serializableMembers[property];
- var sourceProperty = source[propertyDescriptor.sourceName || property];
- var propertyType = propertyDescriptor.type;
- if (sourceProperty !== undefined && sourceProperty !== null) {
- switch (propertyType) {
- case 0:
- destination[property] = sourceProperty;
- break;
- case 1:
- destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
- break;
- case 2:
- destination[property] = BABYLON.Color3.FromArray(sourceProperty);
- break;
- case 3:
- destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
- break;
- case 4:
- destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
- break;
- case 5:
- destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
- break;
- case 6:
- destination[property] = scene.getLastMeshByID(sourceProperty);
- break;
- }
- }
- }
- return destination;
- };
- SerializationHelper.Clone = function (creationFunction, source) {
- var destination = creationFunction();
- // Tags
- BABYLON.Tags.AddTagsTo(destination, source.tags);
- // Properties
- for (var property in destination.__serializableMembers) {
- var propertyDescriptor = destination.__serializableMembers[property];
- var sourceProperty = source[property];
- var propertyType = propertyDescriptor.type;
- if (sourceProperty !== undefined && sourceProperty !== null) {
- switch (propertyType) {
- case 0: // Value
- case 6:
- destination[property] = sourceProperty;
- break;
- case 1: // Texture
- case 2: // Color3
- case 3: // FresnelParameters
- case 4: // Vector2
- case 5:
- destination[property] = sourceProperty.clone();
- break;
- }
- }
- }
- return destination;
- };
- return SerializationHelper;
- })();
- BABYLON.SerializationHelper = SerializationHelper;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- /**
- * A class serves as a medium between the observable and its observers
- */
- var EventState = (function () {
- /**
- * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
- */
- function EventState(skipNextObservers) {
- if (skipNextObservers === void 0) { skipNextObservers = false; }
- this.skipNextObservers = skipNextObservers;
- }
- return EventState;
- })();
- BABYLON.EventState = EventState;
- var Observer = (function () {
- function Observer(callback, mask) {
- this.callback = callback;
- this.mask = mask;
- }
- return Observer;
- })();
- BABYLON.Observer = Observer;
- var Observable = (function () {
- function Observable() {
- this._observers = new Array();
- }
- /**
- * Create a new Observer with the specified callback
- * @param callback the callback that will be executed for that Observer
- * @param mash the mask used to filter observers
- * @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.
- */
- Observable.prototype.add = function (callback, mask, insertFirst) {
- if (mask === void 0) { mask = -1; }
- if (insertFirst === void 0) { insertFirst = false; }
- if (!callback) {
- return null;
- }
- var observer = new Observer(callback, mask);
- if (insertFirst) {
- this._observers.unshift(observer);
- }
- else {
- this._observers.push(observer);
- }
- return observer;
- };
- /**
- * Remove an Observer from the Observable object
- * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
- */
- Observable.prototype.remove = function (observer) {
- var index = this._observers.indexOf(observer);
- if (index !== -1) {
- this._observers.splice(index, 1);
- return true;
- }
- return false;
- };
- /**
- * Remove a callback from the Observable object
- * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
- */
- Observable.prototype.removeCallback = function (callback) {
- for (var index = 0; index < this._observers.length; index++) {
- if (this._observers[index].callback === callback) {
- this._observers.splice(index, 1);
- return true;
- }
- }
- return false;
- };
- /**
- * Notify all Observers by calling their respective callback with the given data
- * @param eventData
- * @param mask
- */
- Observable.prototype.notifyObservers = function (eventData, mask) {
- if (mask === void 0) { mask = -1; }
- var state = new EventState();
- for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
- var obs = _a[_i];
- if (obs.mask & mask) {
- obs.callback(eventData, state);
- }
- if (state.skipNextObservers) {
- break;
- }
- }
- };
- /**
- * return true is the Observable has at least one Observer registered
- */
- Observable.prototype.hasObservers = function () {
- return this._observers.length > 0;
- };
- /**
- * Clear the list of observers
- */
- Observable.prototype.clear = function () {
- this._observers = new Array();
- };
- /**
- * Clone the current observable
- */
- Observable.prototype.clone = function () {
- var result = new Observable();
- result._observers = this._observers.slice(0);
- return result;
- };
- return Observable;
- })();
- BABYLON.Observable = Observable;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Database = (function () {
- function Database(urlToScene, callbackManifestChecked) {
- // Handling various flavors of prefixed version of IndexedDB
- this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
- this.callbackManifestChecked = callbackManifestChecked;
- this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
- this.db = null;
- this.enableSceneOffline = false;
- this.enableTexturesOffline = false;
- this.manifestVersionFound = 0;
- this.mustUpdateRessources = false;
- this.hasReachedQuota = false;
- if (!Database.IDBStorageEnabled) {
- this.callbackManifestChecked(true);
- }
- else {
- this.checkManifestFile();
- }
- }
- Database.prototype.checkManifestFile = function () {
- var _this = this;
- function noManifestFile() {
- that.enableSceneOffline = false;
- that.enableTexturesOffline = false;
- that.callbackManifestChecked(false);
- }
- var that = this;
- var timeStampUsed = false;
- var manifestURL = this.currentSceneUrl + ".manifest";
- var xhr = new XMLHttpRequest();
- if (navigator.onLine) {
- // Adding a timestamp to by-pass browsers' cache
- timeStampUsed = true;
- manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
- }
- xhr.open("GET", manifestURL, true);
- xhr.addEventListener("load", function () {
- if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
- try {
- var manifestFile = JSON.parse(xhr.response);
- _this.enableSceneOffline = manifestFile.enableSceneOffline;
- _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
- if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
- _this.manifestVersionFound = manifestFile.version;
- }
- if (_this.callbackManifestChecked) {
- _this.callbackManifestChecked(true);
- }
- }
- catch (ex) {
- noManifestFile();
- }
- }
- else {
- noManifestFile();
- }
- }, false);
- xhr.addEventListener("error", function (event) {
- if (timeStampUsed) {
- timeStampUsed = false;
- // Let's retry without the timeStamp
- // It could fail when coupled with HTML5 Offline API
- var retryManifestURL = _this.currentSceneUrl + ".manifest";
- xhr.open("GET", retryManifestURL, true);
- xhr.send();
- }
- else {
- noManifestFile();
- }
- }, false);
- try {
- xhr.send();
- }
- catch (ex) {
- BABYLON.Tools.Error("Error on XHR send request.");
- that.callbackManifestChecked(false);
- }
- };
- Database.prototype.openAsync = function (successCallback, errorCallback) {
- var _this = this;
- function handleError() {
- that.isSupported = false;
- if (errorCallback)
- errorCallback();
- }
- var that = this;
- if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
- // Your browser doesn't support IndexedDB
- this.isSupported = false;
- if (errorCallback)
- errorCallback();
- }
- else {
- // If the DB hasn't been opened or created yet
- if (!this.db) {
- this.hasReachedQuota = false;
- this.isSupported = true;
- var request = this.idbFactory.open("babylonjs", 1);
- // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
- request.onerror = function (event) {
- handleError();
- };
- // executes when a version change transaction cannot complete due to other active transactions
- request.onblocked = function (event) {
- BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
- handleError();
- };
- // DB has been opened successfully
- request.onsuccess = function (event) {
- _this.db = request.result;
- successCallback();
- };
- // Initialization of the DB. Creating Scenes & Textures stores
- request.onupgradeneeded = function (event) {
- _this.db = (event.target).result;
- try {
- var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
- var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
- var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
- }
- catch (ex) {
- BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
- handleError();
- }
- };
- }
- else {
- if (successCallback)
- successCallback();
- }
- }
- };
- Database.prototype.loadImageFromDB = function (url, image) {
- var _this = this;
- var completeURL = Database.ReturnFullUrlLocation(url);
- var saveAndLoadImage = function () {
- if (!_this.hasReachedQuota && _this.db !== null) {
- // the texture is not yet in the DB, let's try to save it
- _this._saveImageIntoDBAsync(completeURL, image);
- }
- else {
- image.src = url;
- }
- };
- if (!this.mustUpdateRessources) {
- this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
- }
- else {
- saveAndLoadImage();
- }
- };
- Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
- if (this.isSupported && this.db !== null) {
- var texture;
- var transaction = this.db.transaction(["textures"]);
- transaction.onabort = function (event) {
- image.src = url;
- };
- transaction.oncomplete = function (event) {
- var blobTextureURL;
- if (texture) {
- var URL = window.URL || window.webkitURL;
- blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
- image.onerror = function () {
- BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
- image.src = url;
- };
- image.src = blobTextureURL;
- }
- else {
- notInDBCallback();
- }
- };
- var getRequest = transaction.objectStore("textures").get(url);
- getRequest.onsuccess = function (event) {
- texture = (event.target).result;
- };
- getRequest.onerror = function (event) {
- BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
- image.src = url;
- };
- }
- else {
- BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
- image.src = url;
- }
- };
- Database.prototype._saveImageIntoDBAsync = function (url, image) {
- var _this = this;
- if (this.isSupported) {
- // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
- var generateBlobUrl = function () {
- var blobTextureURL;
- if (blob) {
- var URL = window.URL || window.webkitURL;
- try {
- blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
- }
- // Chrome is raising a type error if we're setting the oneTimeOnly parameter
- catch (ex) {
- blobTextureURL = URL.createObjectURL(blob);
- }
- }
- image.src = blobTextureURL;
- };
- if (Database.IsUASupportingBlobStorage) {
- var xhr = new XMLHttpRequest(), blob;
- xhr.open("GET", url, true);
- xhr.responseType = "blob";
- xhr.addEventListener("load", function () {
- if (xhr.status === 200) {
- // Blob as response (XHR2)
- blob = xhr.response;
- var transaction = _this.db.transaction(["textures"], "readwrite");
- // the transaction could abort because of a QuotaExceededError error
- transaction.onabort = function (event) {
- try {
- //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
- if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
- this.hasReachedQuota = true;
- }
- }
- catch (ex) { }
- generateBlobUrl();
- };
- transaction.oncomplete = function (event) {
- generateBlobUrl();
- };
- var newTexture = { textureUrl: url, data: blob };
- try {
- // Put the blob into the dabase
- var addRequest = transaction.objectStore("textures").put(newTexture);
- addRequest.onsuccess = function (event) {
- };
- addRequest.onerror = function (event) {
- generateBlobUrl();
- };
- }
- catch (ex) {
- // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
- if (ex.code === 25) {
- Database.IsUASupportingBlobStorage = false;
- }
- image.src = url;
- }
- }
- else {
- image.src = url;
- }
- }, false);
- xhr.addEventListener("error", function (event) {
- BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
- image.src = url;
- }, false);
- xhr.send();
- }
- else {
- image.src = url;
- }
- }
- else {
- BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
- image.src = url;
- }
- };
- Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
- var _this = this;
- var updateVersion = function (event) {
- // the version is not yet in the DB or we need to update it
- _this._saveVersionIntoDBAsync(url, versionLoaded);
- };
- this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
- };
- Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
- var _this = this;
- if (this.isSupported) {
- var version;
- try {
- var transaction = this.db.transaction(["versions"]);
- transaction.oncomplete = function (event) {
- if (version) {
- // If the version in the JSON file is > than the version in DB
- if (_this.manifestVersionFound > version.data) {
- _this.mustUpdateRessources = true;
- updateInDBCallback();
- }
- else {
- callback(version.data);
- }
- }
- else {
- _this.mustUpdateRessources = true;
- updateInDBCallback();
- }
- };
- transaction.onabort = function (event) {
- callback(-1);
- };
- var getRequest = transaction.objectStore("versions").get(url);
- getRequest.onsuccess = function (event) {
- version = (event.target).result;
- };
- getRequest.onerror = function (event) {
- BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
- callback(-1);
- };
- }
- catch (ex) {
- BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
- callback(-1);
- }
- }
- else {
- BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
- callback(-1);
- }
- };
- Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
- var _this = this;
- if (this.isSupported && !this.hasReachedQuota) {
- try {
- // Open a transaction to the database
- var transaction = this.db.transaction(["versions"], "readwrite");
- // the transaction could abort because of a QuotaExceededError error
- transaction.onabort = function (event) {
- try {
- if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
- _this.hasReachedQuota = true;
- }
- }
- catch (ex) { }
- callback(-1);
- };
- transaction.oncomplete = function (event) {
- callback(_this.manifestVersionFound);
- };
- var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
- // Put the scene into the database
- var addRequest = transaction.objectStore("versions").put(newVersion);
- addRequest.onsuccess = function (event) {
- };
- addRequest.onerror = function (event) {
- BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
- };
- }
- catch (ex) {
- BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
- callback(-1);
- }
- }
- else {
- callback(-1);
- }
- };
- Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
- var _this = this;
- var completeUrl = Database.ReturnFullUrlLocation(url);
- var saveAndLoadFile = function (event) {
- // the scene is not yet in the DB, let's try to save it
- _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
- };
- this._checkVersionFromDB(completeUrl, function (version) {
- if (version !== -1) {
- if (!_this.mustUpdateRessources) {
- _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
- }
- else {
- _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
- }
- }
- else {
- errorCallback();
- }
- });
- };
- Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
- if (this.isSupported) {
- var targetStore;
- if (url.indexOf(".babylon") !== -1) {
- targetStore = "scenes";
- }
- else {
- targetStore = "textures";
- }
- var file;
- var transaction = this.db.transaction([targetStore]);
- transaction.oncomplete = function (event) {
- if (file) {
- callback(file.data);
- }
- else {
- notInDBCallback();
- }
- };
- transaction.onabort = function (event) {
- notInDBCallback();
- };
- var getRequest = transaction.objectStore(targetStore).get(url);
- getRequest.onsuccess = function (event) {
- file = (event.target).result;
- };
- getRequest.onerror = function (event) {
- BABYLON.Tools.Error("Error loading file " + url + " from DB.");
- notInDBCallback();
- };
- }
- else {
- BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
- callback();
- }
- };
- Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
- var _this = this;
- if (this.isSupported) {
- var targetStore;
- if (url.indexOf(".babylon") !== -1) {
- targetStore = "scenes";
- }
- else {
- targetStore = "textures";
- }
- // Create XHR
- var xhr = new XMLHttpRequest(), fileData;
- xhr.open("GET", url, true);
- if (useArrayBuffer) {
- xhr.responseType = "arraybuffer";
- }
- xhr.onprogress = progressCallback;
- xhr.addEventListener("load", function () {
- if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
- // Blob as response (XHR2)
- //fileData = xhr.responseText;
- fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
- if (!_this.hasReachedQuota) {
- // Open a transaction to the database
- var transaction = _this.db.transaction([targetStore], "readwrite");
- // the transaction could abort because of a QuotaExceededError error
- transaction.onabort = function (event) {
- try {
- //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
- if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
- this.hasReachedQuota = true;
- }
- }
- catch (ex) { }
- callback(fileData);
- };
- transaction.oncomplete = function (event) {
- callback(fileData);
- };
- var newFile;
- if (targetStore === "scenes") {
- newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
- }
- else {
- newFile = { textureUrl: url, data: fileData };
- }
- try {
- // Put the scene into the database
- var addRequest = transaction.objectStore(targetStore).put(newFile);
- addRequest.onsuccess = function (event) {
- };
- addRequest.onerror = function (event) {
- BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
- };
- }
- catch (ex) {
- callback(fileData);
- }
- }
- else {
- callback(fileData);
- }
- }
- else {
- callback();
- }
- }, false);
- xhr.addEventListener("error", function (event) {
- BABYLON.Tools.Error("error on XHR request.");
- callback();
- }, false);
- xhr.send();
- }
- else {
- BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
- callback();
- }
- };
- Database.IsUASupportingBlobStorage = true;
- Database.IDBStorageEnabled = true;
- Database.parseURL = function (url) {
- var a = document.createElement('a');
- a.href = url;
- var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
- var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
- var absLocation = url.substring(0, url.indexOf(fileName, 0));
- return absLocation;
- };
- Database.ReturnFullUrlLocation = function (url) {
- if (url.indexOf("http:/") === -1) {
- return (Database.parseURL(window.location.href) + url);
- }
- else {
- return url;
- }
- };
- return Database;
- })();
- BABYLON.Database = Database;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Internals;
- (function (Internals) {
- /*
- * Based on jsTGALoader - Javascript loader for TGA file
- * By Vincent Thibault
- * @blog http://blog.robrowser.com/javascript-tga-loader.html
- */
- var TGATools = (function () {
- function TGATools() {
- }
- TGATools.GetTGAHeader = function (data) {
- var offset = 0;
- var header = {
- id_length: data[offset++],
- colormap_type: data[offset++],
- image_type: data[offset++],
- colormap_index: data[offset++] | data[offset++] << 8,
- colormap_length: data[offset++] | data[offset++] << 8,
- colormap_size: data[offset++],
- origin: [
- data[offset++] | data[offset++] << 8,
- data[offset++] | data[offset++] << 8
- ],
- width: data[offset++] | data[offset++] << 8,
- height: data[offset++] | data[offset++] << 8,
- pixel_size: data[offset++],
- flags: data[offset++]
- };
- return header;
- };
- TGATools.UploadContent = function (gl, data) {
- // Not enough data to contain header ?
- if (data.length < 19) {
- BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
- return;
- }
- // Read Header
- var offset = 18;
- var header = TGATools.GetTGAHeader(data);
- // Assume it's a valid Targa file.
- if (header.id_length + offset > data.length) {
- BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
- return;
- }
- // Skip not needed data
- offset += header.id_length;
- var use_rle = false;
- var use_pal = false;
- var use_rgb = false;
- var use_grey = false;
- // Get some informations.
- switch (header.image_type) {
- case TGATools._TYPE_RLE_INDEXED:
- use_rle = true;
- case TGATools._TYPE_INDEXED:
- use_pal = true;
- break;
- case TGATools._TYPE_RLE_RGB:
- use_rle = true;
- case TGATools._TYPE_RGB:
- use_rgb = true;
- break;
- case TGATools._TYPE_RLE_GREY:
- use_rle = true;
- case TGATools._TYPE_GREY:
- use_grey = true;
- break;
- }
- var pixel_data;
- var numAlphaBits = header.flags & 0xf;
- var pixel_size = header.pixel_size >> 3;
- var pixel_total = header.width * header.height * pixel_size;
- // Read palettes
- var palettes;
- if (use_pal) {
- palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
- }
- // Read LRE
- if (use_rle) {
- pixel_data = new Uint8Array(pixel_total);
- var c, count, i;
- var localOffset = 0;
- var pixels = new Uint8Array(pixel_size);
- while (offset < pixel_total && localOffset < pixel_total) {
- c = data[offset++];
- count = (c & 0x7f) + 1;
- // RLE pixels
- if (c & 0x80) {
- // Bind pixel tmp array
- for (i = 0; i < pixel_size; ++i) {
- pixels[i] = data[offset++];
- }
- // Copy pixel array
- for (i = 0; i < count; ++i) {
- pixel_data.set(pixels, localOffset + i * pixel_size);
- }
- localOffset += pixel_size * count;
- }
- else {
- count *= pixel_size;
- for (i = 0; i < count; ++i) {
- pixel_data[localOffset + i] = data[offset++];
- }
- localOffset += count;
- }
- }
- }
- else {
- pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
- }
- // Load to texture
- var x_start, y_start, x_step, y_step, y_end, x_end;
- switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
- default:
- case TGATools._ORIGIN_UL:
- x_start = 0;
- x_step = 1;
- x_end = header.width;
- y_start = 0;
- y_step = 1;
- y_end = header.height;
- break;
- case TGATools._ORIGIN_BL:
- x_start = 0;
- x_step = 1;
- x_end = header.width;
- y_start = header.height - 1;
- y_step = -1;
- y_end = -1;
- break;
- case TGATools._ORIGIN_UR:
- x_start = header.width - 1;
- x_step = -1;
- x_end = -1;
- y_start = 0;
- y_step = 1;
- y_end = header.height;
- break;
- case TGATools._ORIGIN_BR:
- x_start = header.width - 1;
- x_step = -1;
- x_end = -1;
- y_start = header.height - 1;
- y_step = -1;
- y_end = -1;
- break;
- }
- // Load the specify method
- var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
- var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
- };
- TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
- var image = pixel_data, colormap = palettes;
- var width = header.width, height = header.height;
- var color, i = 0, x, y;
- var imageData = new Uint8Array(width * height * 4);
- for (y = y_start; y !== y_end; y += y_step) {
- for (x = x_start; x !== x_end; x += x_step, i++) {
- color = image[i];
- imageData[(x + width * y) * 4 + 3] = 255;
- imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
- imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
- imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
- }
- }
- return imageData;
- };
- TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
- var image = pixel_data;
- var width = header.width, height = header.height;
- var color, i = 0, x, y;
- var imageData = new Uint8Array(width * height * 4);
- for (y = y_start; y !== y_end; y += y_step) {
- for (x = x_start; x !== x_end; x += x_step, i += 2) {
- color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
- imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
- imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
- imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
- imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
- }
- }
- return imageData;
- };
- TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
- var image = pixel_data;
- var width = header.width, height = header.height;
- var i = 0, x, y;
- var imageData = new Uint8Array(width * height * 4);
- for (y = y_start; y !== y_end; y += y_step) {
- for (x = x_start; x !== x_end; x += x_step, i += 3) {
- imageData[(x + width * y) * 4 + 3] = 255;
- imageData[(x + width * y) * 4 + 2] = image[i + 0];
- imageData[(x + width * y) * 4 + 1] = image[i + 1];
- imageData[(x + width * y) * 4 + 0] = image[i + 2];
- }
- }
- return imageData;
- };
- TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
- var image = pixel_data;
- var width = header.width, height = header.height;
- var i = 0, x, y;
- var imageData = new Uint8Array(width * height * 4);
- for (y = y_start; y !== y_end; y += y_step) {
- for (x = x_start; x !== x_end; x += x_step, i += 4) {
- imageData[(x + width * y) * 4 + 2] = image[i + 0];
- imageData[(x + width * y) * 4 + 1] = image[i + 1];
- imageData[(x + width * y) * 4 + 0] = image[i + 2];
- imageData[(x + width * y) * 4 + 3] = image[i + 3];
- }
- }
- return imageData;
- };
- TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
- var image = pixel_data;
- var width = header.width, height = header.height;
- var color, i = 0, x, y;
- var imageData = new Uint8Array(width * height * 4);
- for (y = y_start; y !== y_end; y += y_step) {
- for (x = x_start; x !== x_end; x += x_step, i++) {
- color = image[i];
- imageData[(x + width * y) * 4 + 0] = color;
- imageData[(x + width * y) * 4 + 1] = color;
- imageData[(x + width * y) * 4 + 2] = color;
- imageData[(x + width * y) * 4 + 3] = 255;
- }
- }
- return imageData;
- };
- TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
- var image = pixel_data;
- var width = header.width, height = header.height;
- var i = 0, x, y;
- var imageData = new Uint8Array(width * height * 4);
- for (y = y_start; y !== y_end; y += y_step) {
- for (x = x_start; x !== x_end; x += x_step, i += 2) {
- imageData[(x + width * y) * 4 + 0] = image[i + 0];
- imageData[(x + width * y) * 4 + 1] = image[i + 0];
- imageData[(x + width * y) * 4 + 2] = image[i + 0];
- imageData[(x + width * y) * 4 + 3] = image[i + 1];
- }
- }
- return imageData;
- };
- TGATools._TYPE_NO_DATA = 0;
- TGATools._TYPE_INDEXED = 1;
- TGATools._TYPE_RGB = 2;
- TGATools._TYPE_GREY = 3;
- TGATools._TYPE_RLE_INDEXED = 9;
- TGATools._TYPE_RLE_RGB = 10;
- TGATools._TYPE_RLE_GREY = 11;
- TGATools._ORIGIN_MASK = 0x30;
- TGATools._ORIGIN_SHIFT = 0x04;
- TGATools._ORIGIN_BL = 0x00;
- TGATools._ORIGIN_BR = 0x01;
- TGATools._ORIGIN_UL = 0x02;
- TGATools._ORIGIN_UR = 0x03;
- return TGATools;
- })();
- Internals.TGATools = TGATools;
- })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var SmartArray = (function () {
- function SmartArray(capacity) {
- this.length = 0;
- this._duplicateId = 0;
- this.data = new Array(capacity);
- this._id = SmartArray._GlobalId++;
- }
- SmartArray.prototype.push = function (value) {
- this.data[this.length++] = value;
- if (this.length > this.data.length) {
- this.data.length *= 2;
- }
- if (!value.__smartArrayFlags) {
- value.__smartArrayFlags = {};
- }
- value.__smartArrayFlags[this._id] = this._duplicateId;
- };
- SmartArray.prototype.pushNoDuplicate = function (value) {
- if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
- return;
- }
- this.push(value);
- };
- SmartArray.prototype.sort = function (compareFn) {
- this.data.sort(compareFn);
- };
- SmartArray.prototype.reset = function () {
- this.length = 0;
- this._duplicateId++;
- };
- SmartArray.prototype.concat = function (array) {
- if (array.length === 0) {
- return;
- }
- if (this.length + array.length > this.data.length) {
- this.data.length = (this.length + array.length) * 2;
- }
- for (var index = 0; index < array.length; index++) {
- this.data[this.length++] = (array.data || array)[index];
- }
- };
- SmartArray.prototype.concatWithNoDuplicate = function (array) {
- if (array.length === 0) {
- return;
- }
- if (this.length + array.length > this.data.length) {
- this.data.length = (this.length + array.length) * 2;
- }
- for (var index = 0; index < array.length; index++) {
- var item = (array.data || array)[index];
- this.pushNoDuplicate(item);
- }
- };
- SmartArray.prototype.indexOf = function (value) {
- var position = this.data.indexOf(value);
- if (position >= this.length) {
- return -1;
- }
- return position;
- };
- // Statics
- SmartArray._GlobalId = 0;
- return SmartArray;
- })();
- BABYLON.SmartArray = SmartArray;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- /**
- * This class implement a typical dictionary using a string as key and the generic type T as value.
- * The underlying implemetation relies on an associative array to ensure the best performances.
- * The value can be anything including 'null' but except 'undefined'
- */
- var StringDictionary = (function () {
- function StringDictionary() {
- this._count = 0;
- this._data = {};
- }
- /**
- * Get a value based from its key
- * @param key the given key to get the matching value from
- * @return the value if found, otherwise undefined is returned
- */
- StringDictionary.prototype.get = function (key) {
- var val = this._data[key];
- if (val !== undefined) {
- return val;
- }
- return undefined;
- };
- /**
- * Get a value from its key or add it if it doesn't exist.
- * This method will ensure you that a given key/data will be present in the dictionary.
- * @param key the given key to get the matchin value from
- * @param factory the factory that will create the value if the key is not present in the dictionary.
- * The factory will only be invoked if there's no data for the given key.
- * @return the value corresponding to the key.
- */
- StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
- var val = this.get(key);
- if (val !== undefined) {
- return val;
- }
- val = factory(key);
- if (val) {
- this.add(key, val);
- }
- return val;
- };
- /**
- * Get a value from its key if present in the dictionary otherwise add it
- * @param key the key to get the value from
- * @param val if there's no such key/value pair in the dictionary add it with this value
- * @return the value corresponding to the key
- */
- StringDictionary.prototype.getOrAdd = function (key, val) {
- var val = this.get(key);
- if (val !== undefined) {
- return val;
- }
- this.add(key, val);
- return val;
- };
- /**
- * Check if there's a given key in the dictionary
- * @param key the key to check for
- * @return true if the key is present, false otherwise
- */
- StringDictionary.prototype.contains = function (key) {
- return this._data[key] !== undefined;
- };
- /**
- * Add a new key and its corresponding value
- * @param key the key to add
- * @param value the value corresponding to the key
- * @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
- */
- StringDictionary.prototype.add = function (key, value) {
- if (this._data[key] !== undefined) {
- return false;
- }
- this._data[key] = value;
- ++this._count;
- return true;
- };
- /**
- * Remove a key/value from the dictionary.
- * @param key the key to remove
- * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
- */
- StringDictionary.prototype.remove = function (key) {
- if (this.contains(key)) {
- delete this._data[key];
- --this._count;
- return true;
- }
- return false;
- };
- /**
- * Clear the whole content of the dictionary
- */
- StringDictionary.prototype.clear = function () {
- this._data = {};
- this._count = 0;
- };
- Object.defineProperty(StringDictionary.prototype, "count", {
- get: function () {
- return this._count;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Execute a callback on each key/val of the dictionary.
- * Note that you can remove any element in this dictionary in the callback implementation
- * @param callback the callback to execute on a given key/value pair
- */
- StringDictionary.prototype.forEach = function (callback) {
- for (var cur in this._data) {
- var val = this._data[cur];
- callback(cur, val);
- }
- };
- /**
- * Execute a callback on every occurence of the dictionary until it returns a valid TRes object.
- * If the callback returns null or undefined the method will iterate to the next key/value pair
- * Note that you can remove any element in this dictionary in the callback implementation
- * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
- */
- StringDictionary.prototype.first = function (callback) {
- for (var cur in this._data) {
- var val = this._data[cur];
- var res = callback(cur, val);
- if (res) {
- return res;
- }
- }
- return null;
- };
- return StringDictionary;
- })();
- BABYLON.StringDictionary = StringDictionary;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- // Screenshots
- var screenshotCanvas;
- var cloneValue = function (source, destinationObject) {
- if (!source)
- return null;
- if (source instanceof BABYLON.Mesh) {
- return null;
- }
- if (source instanceof BABYLON.SubMesh) {
- return source.clone(destinationObject);
- }
- else if (source.clone) {
- return source.clone();
- }
- return null;
- };
- var Tools = (function () {
- function Tools() {
- }
- Tools.Instantiate = function (className) {
- var arr = className.split(".");
- var fn = (window || this);
- for (var i = 0, len = arr.length; i < len; i++) {
- fn = fn[arr[i]];
- }
- if (typeof fn !== "function") {
- return null;
- }
- return fn;
- };
- Tools.SetImmediate = function (action) {
- if (window.setImmediate) {
- window.setImmediate(action);
- }
- else {
- setTimeout(action, 1);
- }
- };
- Tools.IsExponentOfTwo = function (value) {
- var count = 1;
- do {
- count *= 2;
- } while (count < value);
- return count === value;
- };
- Tools.GetExponentOfTwo = function (value, max) {
- var count = 1;
- do {
- count *= 2;
- } while (count < value);
- if (count > max)
- count = max;
- return count;
- };
- Tools.GetFilename = function (path) {
- var index = path.lastIndexOf("/");
- if (index < 0)
- return path;
- return path.substring(index + 1);
- };
- Tools.GetDOMTextContent = function (element) {
- var result = "";
- var child = element.firstChild;
- while (child) {
- if (child.nodeType === 3) {
- result += child.textContent;
- }
- child = child.nextSibling;
- }
- return result;
- };
- Tools.ToDegrees = function (angle) {
- return angle * 180 / Math.PI;
- };
- Tools.ToRadians = function (angle) {
- return angle * Math.PI / 180;
- };
- Tools.EncodeArrayBufferTobase64 = function (buffer) {
- var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
- var output = "";
- var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
- var i = 0;
- var bytes = new Uint8Array(buffer);
- while (i < bytes.length) {
- chr1 = bytes[i++];
- chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
- chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
- enc1 = chr1 >> 2;
- enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
- enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
- enc4 = chr3 & 63;
- if (isNaN(chr2)) {
- enc3 = enc4 = 64;
- }
- else if (isNaN(chr3)) {
- enc4 = 64;
- }
- output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
- keyStr.charAt(enc3) + keyStr.charAt(enc4);
- }
- return "data:image/png;base64," + output;
- };
- Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
- if (bias === void 0) { bias = null; }
- var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
- var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
- for (var index = indexStart; index < indexStart + indexCount; index++) {
- var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
- minimum = BABYLON.Vector3.Minimize(current, minimum);
- maximum = BABYLON.Vector3.Maximize(current, maximum);
- }
- if (bias) {
- minimum.x -= minimum.x * bias.x + bias.y;
- minimum.y -= minimum.y * bias.x + bias.y;
- minimum.z -= minimum.z * bias.x + bias.y;
- maximum.x += maximum.x * bias.x + bias.y;
- maximum.y += maximum.y * bias.x + bias.y;
- maximum.z += maximum.z * bias.x + bias.y;
- }
- return {
- minimum: minimum,
- maximum: maximum
- };
- };
- Tools.ExtractMinAndMax = function (positions, start, count, bias) {
- if (bias === void 0) { bias = null; }
- var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
- var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
- for (var index = start; index < start + count; index++) {
- var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
- minimum = BABYLON.Vector3.Minimize(current, minimum);
- maximum = BABYLON.Vector3.Maximize(current, maximum);
- }
- if (bias) {
- minimum.x -= minimum.x * bias.x + bias.y;
- minimum.y -= minimum.y * bias.x + bias.y;
- minimum.z -= minimum.z * bias.x + bias.y;
- maximum.x += maximum.x * bias.x + bias.y;
- maximum.y += maximum.y * bias.x + bias.y;
- maximum.z += maximum.z * bias.x + bias.y;
- }
- return {
- minimum: minimum,
- maximum: maximum
- };
- };
- Tools.MakeArray = function (obj, allowsNullUndefined) {
- if (allowsNullUndefined !== true && (obj === undefined || obj == null))
- return undefined;
- return Array.isArray(obj) ? obj : [obj];
- };
- // Misc.
- Tools.GetPointerPrefix = function () {
- var eventPrefix = "pointer";
- // Check if pointer events are supported
- if (!window.PointerEvent && !navigator.pointerEnabled) {
- eventPrefix = "mouse";
- }
- return eventPrefix;
- };
- Tools.QueueNewFrame = function (func) {
- if (window.requestAnimationFrame)
- window.requestAnimationFrame(func);
- else if (window.msRequestAnimationFrame)
- window.msRequestAnimationFrame(func);
- else if (window.webkitRequestAnimationFrame)
- window.webkitRequestAnimationFrame(func);
- else if (window.mozRequestAnimationFrame)
- window.mozRequestAnimationFrame(func);
- else if (window.oRequestAnimationFrame)
- window.oRequestAnimationFrame(func);
- else {
- window.setTimeout(func, 16);
- }
- };
- Tools.RequestFullscreen = function (element) {
- if (element.requestFullscreen)
- element.requestFullscreen();
- else if (element.msRequestFullscreen)
- element.msRequestFullscreen();
- else if (element.webkitRequestFullscreen)
- element.webkitRequestFullscreen();
- else if (element.mozRequestFullScreen)
- element.mozRequestFullScreen();
- };
- Tools.ExitFullscreen = function () {
- if (document.exitFullscreen) {
- document.exitFullscreen();
- }
- else if (document.mozCancelFullScreen) {
- document.mozCancelFullScreen();
- }
- else if (document.webkitCancelFullScreen) {
- document.webkitCancelFullScreen();
- }
- else if (document.msCancelFullScreen) {
- document.msCancelFullScreen();
- }
- };
- // External files
- Tools.CleanUrl = function (url) {
- url = url.replace(/#/mg, "%23");
- return url;
- };
- Tools.LoadImage = function (url, onload, onerror, database) {
- if (url instanceof ArrayBuffer) {
- url = Tools.EncodeArrayBufferTobase64(url);
- }
- url = Tools.CleanUrl(url);
- var img = new Image();
- if (url.substr(0, 5) !== "data:") {
- if (Tools.CorsBehavior) {
- switch (typeof (Tools.CorsBehavior)) {
- case "function":
- var result = Tools.CorsBehavior(url);
- if (result) {
- img.crossOrigin = result;
- }
- break;
- case "string":
- default:
- img.crossOrigin = Tools.CorsBehavior;
- break;
- }
- }
- }
- img.onload = function () {
- onload(img);
- };
- img.onerror = function (err) {
- Tools.Error("Error while trying to load texture: " + url);
- if (Tools.UseFallbackTexture) {
- 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";
- onload(img);
- }
- else {
- onerror();
- }
- };
- var noIndexedDB = function () {
- img.src = url;
- };
- var loadFromIndexedDB = function () {
- database.loadImageFromDB(url, img);
- };
- //ANY database to do!
- if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
- database.openAsync(loadFromIndexedDB, noIndexedDB);
- }
- else {
- if (url.indexOf("file:") === -1) {
- noIndexedDB();
- }
- else {
- try {
- var textureName = url.substring(5).toLowerCase();
- var blobURL;
- try {
- blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
- }
- catch (ex) {
- // Chrome doesn't support oneTimeOnly parameter
- blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
- }
- img.src = blobURL;
- }
- catch (e) {
- img.src = null;
- }
- }
- }
- return img;
- };
- //ANY
- Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
- url = Tools.CleanUrl(url);
- var noIndexedDB = function () {
- var request = new XMLHttpRequest();
- var loadUrl = Tools.BaseUrl + url;
- request.open('GET', loadUrl, true);
- if (useArrayBuffer) {
- request.responseType = "arraybuffer";
- }
- request.onprogress = progressCallBack;
- request.onreadystatechange = function () {
- if (request.readyState === 4) {
- if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
- callback(!useArrayBuffer ? request.responseText : request.response);
- }
- else {
- if (onError) {
- onError();
- }
- else {
- throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
- }
- }
- }
- };
- request.send(null);
- };
- var loadFromIndexedDB = function () {
- database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
- };
- if (url.indexOf("file:") !== -1) {
- var fileName = url.substring(5).toLowerCase();
- Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
- }
- else {
- // Caching all files
- if (database && database.enableSceneOffline) {
- database.openAsync(loadFromIndexedDB, noIndexedDB);
- }
- else {
- noIndexedDB();
- }
- }
- };
- Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
- var reader = new FileReader();
- reader.onload = function (e) {
- //target doesn't have result from ts 1.3
- callback(e.target['result']);
- };
- reader.onprogress = progressCallback;
- reader.readAsDataURL(fileToLoad);
- };
- Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
- var reader = new FileReader();
- reader.onerror = function (e) {
- Tools.Log("Error while reading file: " + fileToLoad.name);
- callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
- };
- reader.onload = function (e) {
- //target doesn't have result from ts 1.3
- callback(e.target['result']);
- };
- reader.onprogress = progressCallBack;
- if (!useArrayBuffer) {
- // Asynchronous read
- reader.readAsText(fileToLoad);
- }
- else {
- reader.readAsArrayBuffer(fileToLoad);
- }
- };
- //returns a downloadable url to a file content.
- Tools.FileAsURL = function (content) {
- var fileBlob = new Blob([content]);
- var url = window.URL || window.webkitURL;
- var link = url.createObjectURL(fileBlob);
- return link;
- };
- // Misc.
- Tools.Format = function (value, decimals) {
- if (decimals === void 0) { decimals = 2; }
- return value.toFixed(decimals);
- };
- Tools.CheckExtends = function (v, min, max) {
- if (v.x < min.x)
- min.x = v.x;
- if (v.y < min.y)
- min.y = v.y;
- if (v.z < min.z)
- min.z = v.z;
- if (v.x > max.x)
- max.x = v.x;
- if (v.y > max.y)
- max.y = v.y;
- if (v.z > max.z)
- max.z = v.z;
- };
- Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
- for (var prop in source) {
- if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
- continue;
- }
- if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
- continue;
- }
- var sourceValue = source[prop];
- var typeOfSourceValue = typeof sourceValue;
- if (typeOfSourceValue === "function") {
- continue;
- }
- if (typeOfSourceValue === "object") {
- if (sourceValue instanceof Array) {
- destination[prop] = [];
- if (sourceValue.length > 0) {
- if (typeof sourceValue[0] == "object") {
- for (var index = 0; index < sourceValue.length; index++) {
- var clonedValue = cloneValue(sourceValue[index], destination);
- if (destination[prop].indexOf(clonedValue) === -1) {
- destination[prop].push(clonedValue);
- }
- }
- }
- else {
- destination[prop] = sourceValue.slice(0);
- }
- }
- }
- else {
- destination[prop] = cloneValue(sourceValue, destination);
- }
- }
- else {
- destination[prop] = sourceValue;
- }
- }
- };
- Tools.IsEmpty = function (obj) {
- for (var i in obj) {
- return false;
- }
- return true;
- };
- Tools.RegisterTopRootEvents = function (events) {
- for (var index = 0; index < events.length; index++) {
- var event = events[index];
- window.addEventListener(event.name, event.handler, false);
- try {
- if (window.parent) {
- window.parent.addEventListener(event.name, event.handler, false);
- }
- }
- catch (e) {
- }
- }
- };
- Tools.UnregisterTopRootEvents = function (events) {
- for (var index = 0; index < events.length; index++) {
- var event = events[index];
- window.removeEventListener(event.name, event.handler);
- try {
- if (window.parent) {
- window.parent.removeEventListener(event.name, event.handler);
- }
- }
- catch (e) {
- }
- }
- };
- Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
- // Read the contents of the framebuffer
- var numberOfChannelsByLine = width * 4;
- var halfHeight = height / 2;
- //Reading datas from WebGL
- var data = engine.readPixels(0, 0, width, height);
- //To flip image on Y axis.
- for (var i = 0; i < halfHeight; i++) {
- for (var j = 0; j < numberOfChannelsByLine; j++) {
- var currentCell = j + i * numberOfChannelsByLine;
- var targetLine = height - i - 1;
- var targetCell = j + targetLine * numberOfChannelsByLine;
- var temp = data[currentCell];
- data[currentCell] = data[targetCell];
- data[targetCell] = temp;
- }
- }
- // Create a 2D canvas to store the result
- if (!screenshotCanvas) {
- screenshotCanvas = document.createElement('canvas');
- }
- screenshotCanvas.width = width;
- screenshotCanvas.height = height;
- var context = screenshotCanvas.getContext('2d');
- // Copy the pixels to a 2D canvas
- var imageData = context.createImageData(width, height);
- //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
- var castData = imageData.data;
- castData.set(data);
- context.putImageData(imageData, 0, 0);
- var base64Image = screenshotCanvas.toDataURL();
- if (successCallback) {
- successCallback(base64Image);
- }
- else {
- //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
- if (("download" in document.createElement("a"))) {
- var a = window.document.createElement("a");
- a.href = base64Image;
- var date = new Date();
- var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
- a.setAttribute("download", "screenshot_" + stringDate + ".png");
- window.document.body.appendChild(a);
- a.addEventListener("click", function () {
- a.parentElement.removeChild(a);
- });
- a.click();
- }
- else {
- var newWindow = window.open("");
- var img = newWindow.document.createElement("img");
- img.src = base64Image;
- newWindow.document.body.appendChild(img);
- }
- }
- };
- Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
- var width;
- var height;
- //If a precision value is specified
- if (size.precision) {
- width = Math.round(engine.getRenderWidth() * size.precision);
- height = Math.round(width / engine.getAspectRatio(camera));
- size = { width: width, height: height };
- }
- else if (size.width && size.height) {
- width = size.width;
- height = size.height;
- }
- else if (size.width && !size.height) {
- width = size.width;
- height = Math.round(width / engine.getAspectRatio(camera));
- size = { width: width, height: height };
- }
- else if (size.height && !size.width) {
- height = size.height;
- width = Math.round(height * engine.getAspectRatio(camera));
- size = { width: width, height: height };
- }
- else if (!isNaN(size)) {
- height = size;
- width = size;
- }
- else {
- Tools.Error("Invalid 'size' parameter !");
- return;
- }
- var scene = camera.getScene();
- var previousCamera = null;
- if (scene.activeCamera !== camera) {
- previousCamera = scene.activeCamera;
- scene.activeCamera = camera;
- }
- //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
- var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
- texture.renderList = scene.meshes;
- texture.onAfterRender = function () {
- Tools.DumpFramebuffer(width, height, engine, successCallback);
- };
- scene.incrementRenderId();
- texture.render(true);
- texture.dispose();
- if (previousCamera) {
- scene.activeCamera = previousCamera;
- }
- camera.getProjectionMatrix(true); // Force cache refresh;
- };
- // XHR response validator for local file scenario
- Tools.ValidateXHRData = function (xhr, dataType) {
- // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
- if (dataType === void 0) { dataType = 7; }
- try {
- if (dataType & 1) {
- if (xhr.responseText && xhr.responseText.length > 0) {
- return true;
- }
- else if (dataType === 1) {
- return false;
- }
- }
- if (dataType & 2) {
- // Check header width and height since there is no "TGA" magic number
- var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
- if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
- return true;
- }
- else if (dataType === 2) {
- return false;
- }
- }
- if (dataType & 4) {
- // Check for the "DDS" magic number
- var ddsHeader = new Uint8Array(xhr.response, 0, 3);
- if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
- return true;
- }
- else {
- return false;
- }
- }
- }
- catch (e) {
- }
- return false;
- };
- Tools.getClassName = function (obj) {
- var funcNameRegex = /function (.{1,})\(/;
- var results = (funcNameRegex).exec((obj).constructor.toString());
- return (results && results.length > 1) ? results[1] : "";
- };
- Object.defineProperty(Tools, "NoneLogLevel", {
- get: function () {
- return Tools._NoneLogLevel;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Tools, "MessageLogLevel", {
- get: function () {
- return Tools._MessageLogLevel;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Tools, "WarningLogLevel", {
- get: function () {
- return Tools._WarningLogLevel;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Tools, "ErrorLogLevel", {
- get: function () {
- return Tools._ErrorLogLevel;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Tools, "AllLogLevel", {
- get: function () {
- return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
- },
- enumerable: true,
- configurable: true
- });
- Tools._AddLogEntry = function (entry) {
- Tools._LogCache = entry + Tools._LogCache;
- if (Tools.OnNewCacheEntry) {
- Tools.OnNewCacheEntry(entry);
- }
- };
- Tools._FormatMessage = function (message) {
- var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
- var date = new Date();
- return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
- };
- Tools._LogDisabled = function (message) {
- // nothing to do
- };
- Tools._LogEnabled = function (message) {
- var formattedMessage = Tools._FormatMessage(message);
- console.log("BJS - " + formattedMessage);
- var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
- Tools._AddLogEntry(entry);
- };
- Tools._WarnDisabled = function (message) {
- // nothing to do
- };
- Tools._WarnEnabled = function (message) {
- var formattedMessage = Tools._FormatMessage(message);
- console.warn("BJS - " + formattedMessage);
- var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
- Tools._AddLogEntry(entry);
- };
- Tools._ErrorDisabled = function (message) {
- // nothing to do
- };
- Tools._ErrorEnabled = function (message) {
- Tools.errorsCount++;
- var formattedMessage = Tools._FormatMessage(message);
- console.error("BJS - " + formattedMessage);
- var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
- Tools._AddLogEntry(entry);
- };
- Object.defineProperty(Tools, "LogCache", {
- get: function () {
- return Tools._LogCache;
- },
- enumerable: true,
- configurable: true
- });
- Tools.ClearLogCache = function () {
- Tools._LogCache = "";
- Tools.errorsCount = 0;
- };
- Object.defineProperty(Tools, "LogLevels", {
- set: function (level) {
- if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
- Tools.Log = Tools._LogEnabled;
- }
- else {
- Tools.Log = Tools._LogDisabled;
- }
- if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
- Tools.Warn = Tools._WarnEnabled;
- }
- else {
- Tools.Warn = Tools._WarnDisabled;
- }
- if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
- Tools.Error = Tools._ErrorEnabled;
- }
- else {
- Tools.Error = Tools._ErrorDisabled;
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
- get: function () {
- return Tools._PerformanceNoneLogLevel;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
- get: function () {
- return Tools._PerformanceUserMarkLogLevel;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
- get: function () {
- return Tools._PerformanceConsoleLogLevel;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Tools, "PerformanceLogLevel", {
- set: function (level) {
- if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
- Tools.StartPerformanceCounter = Tools._StartUserMark;
- Tools.EndPerformanceCounter = Tools._EndUserMark;
- return;
- }
- if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
- Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
- Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
- return;
- }
- Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
- Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
- },
- enumerable: true,
- configurable: true
- });
- Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
- };
- Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
- };
- Tools._StartUserMark = function (counterName, condition) {
- if (condition === void 0) { condition = true; }
- if (!condition || !Tools._performance.mark) {
- return;
- }
- Tools._performance.mark(counterName + "-Begin");
- };
- Tools._EndUserMark = function (counterName, condition) {
- if (condition === void 0) { condition = true; }
- if (!condition || !Tools._performance.mark) {
- return;
- }
- Tools._performance.mark(counterName + "-End");
- Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
- };
- Tools._StartPerformanceConsole = function (counterName, condition) {
- if (condition === void 0) { condition = true; }
- if (!condition) {
- return;
- }
- Tools._StartUserMark(counterName, condition);
- if (console.time) {
- console.time(counterName);
- }
- };
- Tools._EndPerformanceConsole = function (counterName, condition) {
- if (condition === void 0) { condition = true; }
- if (!condition) {
- return;
- }
- Tools._EndUserMark(counterName, condition);
- if (console.time) {
- console.timeEnd(counterName);
- }
- };
- Object.defineProperty(Tools, "Now", {
- get: function () {
- if (window.performance && window.performance.now) {
- return window.performance.now();
- }
- return new Date().getTime();
- },
- enumerable: true,
- configurable: true
- });
- Tools.BaseUrl = "";
- Tools.CorsBehavior = "anonymous";
- Tools.UseFallbackTexture = true;
- // Logs
- Tools._NoneLogLevel = 0;
- Tools._MessageLogLevel = 1;
- Tools._WarningLogLevel = 2;
- Tools._ErrorLogLevel = 4;
- Tools._LogCache = "";
- Tools.errorsCount = 0;
- Tools.Log = Tools._LogEnabled;
- Tools.Warn = Tools._WarnEnabled;
- Tools.Error = Tools._ErrorEnabled;
- // Performances
- Tools._PerformanceNoneLogLevel = 0;
- Tools._PerformanceUserMarkLogLevel = 1;
- Tools._PerformanceConsoleLogLevel = 2;
- Tools._performance = window.performance;
- Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
- Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
- return Tools;
- })();
- BABYLON.Tools = Tools;
- /**
- * An implementation of a loop for asynchronous functions.
- */
- var AsyncLoop = (function () {
- /**
- * Constroctor.
- * @param iterations the number of iterations.
- * @param _fn the function to run each iteration
- * @param _successCallback the callback that will be called upon succesful execution
- * @param offset starting offset.
- */
- function AsyncLoop(iterations, _fn, _successCallback, offset) {
- if (offset === void 0) { offset = 0; }
- this.iterations = iterations;
- this._fn = _fn;
- this._successCallback = _successCallback;
- this.index = offset - 1;
- this._done = false;
- }
- /**
- * Execute the next iteration. Must be called after the last iteration was finished.
- */
- AsyncLoop.prototype.executeNext = function () {
- if (!this._done) {
- if (this.index + 1 < this.iterations) {
- ++this.index;
- this._fn(this);
- }
- else {
- this.breakLoop();
- }
- }
- };
- /**
- * Break the loop and run the success callback.
- */
- AsyncLoop.prototype.breakLoop = function () {
- this._done = true;
- this._successCallback();
- };
- /**
- * Helper function
- */
- AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
- if (offset === void 0) { offset = 0; }
- var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
- loop.executeNext();
- return loop;
- };
- /**
- * A for-loop that will run a given number of iterations synchronous and the rest async.
- * @param iterations total number of iterations
- * @param syncedIterations number of synchronous iterations in each async iteration.
- * @param fn the function to call each iteration.
- * @param callback a success call back that will be called when iterating stops.
- * @param breakFunction a break condition (optional)
- * @param timeout timeout settings for the setTimeout function. default - 0.
- * @constructor
- */
- AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
- if (timeout === void 0) { timeout = 0; }
- AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
- if (breakFunction && breakFunction())
- loop.breakLoop();
- else {
- setTimeout(function () {
- for (var i = 0; i < syncedIterations; ++i) {
- var iteration = (loop.index * syncedIterations) + i;
- if (iteration >= iterations)
- break;
- fn(iteration);
- if (breakFunction && breakFunction()) {
- loop.breakLoop();
- break;
- }
- }
- loop.executeNext();
- }, timeout);
- }
- }, callback);
- };
- return AsyncLoop;
- })();
- BABYLON.AsyncLoop = AsyncLoop;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Internals;
- (function (Internals) {
- var _AlphaState = (function () {
- function _AlphaState() {
- this._isAlphaBlendDirty = false;
- this._isBlendFunctionParametersDirty = false;
- this._alphaBlend = false;
- this._blendFunctionParameters = new Array(4);
- }
- Object.defineProperty(_AlphaState.prototype, "isDirty", {
- get: function () {
- return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
- get: function () {
- return this._alphaBlend;
- },
- set: function (value) {
- if (this._alphaBlend === value) {
- return;
- }
- this._alphaBlend = value;
- this._isAlphaBlendDirty = true;
- },
- enumerable: true,
- configurable: true
- });
- _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
- if (this._blendFunctionParameters[0] === value0 &&
- this._blendFunctionParameters[1] === value1 &&
- this._blendFunctionParameters[2] === value2 &&
- this._blendFunctionParameters[3] === value3) {
- return;
- }
- this._blendFunctionParameters[0] = value0;
- this._blendFunctionParameters[1] = value1;
- this._blendFunctionParameters[2] = value2;
- this._blendFunctionParameters[3] = value3;
- this._isBlendFunctionParametersDirty = true;
- };
- _AlphaState.prototype.reset = function () {
- this._alphaBlend = false;
- this._blendFunctionParameters[0] = null;
- this._blendFunctionParameters[1] = null;
- this._blendFunctionParameters[2] = null;
- this._blendFunctionParameters[3] = null;
- this._isAlphaBlendDirty = true;
- this._isBlendFunctionParametersDirty = false;
- };
- _AlphaState.prototype.apply = function (gl) {
- if (!this.isDirty) {
- return;
- }
- // Alpha blend
- if (this._isAlphaBlendDirty) {
- if (this._alphaBlend) {
- gl.enable(gl.BLEND);
- }
- else {
- gl.disable(gl.BLEND);
- }
- this._isAlphaBlendDirty = false;
- }
- // Alpha function
- if (this._isBlendFunctionParametersDirty) {
- gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
- this._isBlendFunctionParametersDirty = false;
- }
- };
- return _AlphaState;
- })();
- Internals._AlphaState = _AlphaState;
- })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Internals;
- (function (Internals) {
- var _DepthCullingState = (function () {
- function _DepthCullingState() {
- this._isDepthTestDirty = false;
- this._isDepthMaskDirty = false;
- this._isDepthFuncDirty = false;
- this._isCullFaceDirty = false;
- this._isCullDirty = false;
- this._isZOffsetDirty = false;
- }
- Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
- get: function () {
- return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
- get: function () {
- return this._zOffset;
- },
- set: function (value) {
- if (this._zOffset === value) {
- return;
- }
- this._zOffset = value;
- this._isZOffsetDirty = true;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
- get: function () {
- return this._cullFace;
- },
- set: function (value) {
- if (this._cullFace === value) {
- return;
- }
- this._cullFace = value;
- this._isCullFaceDirty = true;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(_DepthCullingState.prototype, "cull", {
- get: function () {
- return this._cull;
- },
- set: function (value) {
- if (this._cull === value) {
- return;
- }
- this._cull = value;
- this._isCullDirty = true;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
- get: function () {
- return this._depthFunc;
- },
- set: function (value) {
- if (this._depthFunc === value) {
- return;
- }
- this._depthFunc = value;
- this._isDepthFuncDirty = true;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
- get: function () {
- return this._depthMask;
- },
- set: function (value) {
- if (this._depthMask === value) {
- return;
- }
- this._depthMask = value;
- this._isDepthMaskDirty = true;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
- get: function () {
- return this._depthTest;
- },
- set: function (value) {
- if (this._depthTest === value) {
- return;
- }
- this._depthTest = value;
- this._isDepthTestDirty = true;
- },
- enumerable: true,
- configurable: true
- });
- _DepthCullingState.prototype.reset = function () {
- this._depthMask = true;
- this._depthTest = true;
- this._depthFunc = null;
- this._cull = null;
- this._cullFace = null;
- this._zOffset = 0;
- this._isDepthTestDirty = true;
- this._isDepthMaskDirty = true;
- this._isDepthFuncDirty = false;
- this._isCullFaceDirty = false;
- this._isCullDirty = false;
- this._isZOffsetDirty = false;
- };
- _DepthCullingState.prototype.apply = function (gl) {
- if (!this.isDirty) {
- return;
- }
- // Cull
- if (this._isCullDirty) {
- if (this.cull) {
- gl.enable(gl.CULL_FACE);
- }
- else {
- gl.disable(gl.CULL_FACE);
- }
- this._isCullDirty = false;
- }
- // Cull face
- if (this._isCullFaceDirty) {
- gl.cullFace(this.cullFace);
- this._isCullFaceDirty = false;
- }
- // Depth mask
- if (this._isDepthMaskDirty) {
- gl.depthMask(this.depthMask);
- this._isDepthMaskDirty = false;
- }
- // Depth test
- if (this._isDepthTestDirty) {
- if (this.depthTest) {
- gl.enable(gl.DEPTH_TEST);
- }
- else {
- gl.disable(gl.DEPTH_TEST);
- }
- this._isDepthTestDirty = false;
- }
- // Depth func
- if (this._isDepthFuncDirty) {
- gl.depthFunc(this.depthFunc);
- this._isDepthFuncDirty = false;
- }
- // zOffset
- if (this._isZOffsetDirty) {
- if (this.zOffset) {
- gl.enable(gl.POLYGON_OFFSET_FILL);
- gl.polygonOffset(this.zOffset, 0);
- }
- else {
- gl.disable(gl.POLYGON_OFFSET_FILL);
- }
- this._isZOffsetDirty = false;
- }
- };
- return _DepthCullingState;
- })();
- Internals._DepthCullingState = _DepthCullingState;
- })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var compileShader = function (gl, source, type, defines) {
- var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
- gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
- gl.compileShader(shader);
- if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
- throw new Error(gl.getShaderInfoLog(shader));
- }
- return shader;
- };
- var getWebGLTextureType = function (gl, type) {
- var textureType = gl.UNSIGNED_BYTE;
- if (type === Engine.TEXTURETYPE_FLOAT)
- textureType = gl.FLOAT;
- return textureType;
- };
- var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
- var magFilter = gl.NEAREST;
- var minFilter = gl.NEAREST;
- if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
- magFilter = gl.LINEAR;
- if (generateMipMaps) {
- minFilter = gl.LINEAR_MIPMAP_NEAREST;
- }
- else {
- minFilter = gl.LINEAR;
- }
- }
- else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
- magFilter = gl.LINEAR;
- if (generateMipMaps) {
- minFilter = gl.LINEAR_MIPMAP_LINEAR;
- }
- else {
- minFilter = gl.LINEAR;
- }
- }
- else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
- magFilter = gl.NEAREST;
- if (generateMipMaps) {
- minFilter = gl.NEAREST_MIPMAP_LINEAR;
- }
- else {
- minFilter = gl.NEAREST;
- }
- }
- return {
- min: minFilter,
- mag: magFilter
- };
- };
- var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
- var engine = scene.getEngine();
- var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
- var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
- texture._baseWidth = width;
- texture._baseHeight = height;
- texture._width = potWidth;
- texture._height = potHeight;
- texture.isReady = true;
- processFunction(potWidth, potHeight);
- var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
- if (!noMipmap && !isCompressed) {
- gl.generateMipmap(gl.TEXTURE_2D);
- }
- gl.bindTexture(gl.TEXTURE_2D, null);
- engine.resetTextureCache();
- scene._removePendingData(texture);
- if (onLoad) {
- onLoad();
- }
- };
- var partialLoad = function (url, index, loadedImages, scene, onfinish) {
- var img;
- var onload = function () {
- loadedImages[index] = img;
- loadedImages._internalCount++;
- scene._removePendingData(img);
- if (loadedImages._internalCount === 6) {
- onfinish(loadedImages);
- }
- };
- var onerror = function () {
- scene._removePendingData(img);
- };
- img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
- scene._addPendingData(img);
- };
- var cascadeLoad = function (rootUrl, scene, onfinish, files) {
- var loadedImages = [];
- loadedImages._internalCount = 0;
- for (var index = 0; index < 6; index++) {
- partialLoad(files[index], index, loadedImages, scene, onfinish);
- }
- };
- var EngineCapabilities = (function () {
- function EngineCapabilities() {
- }
- return EngineCapabilities;
- })();
- BABYLON.EngineCapabilities = EngineCapabilities;
- /**
- * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
- */
- var Engine = (function () {
- /**
- * @constructor
- * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
- * @param {boolean} [antialias] - enable antialias
- * @param options - further options to be sent to the getContext function
- */
- function Engine(canvas, antialias, options, adaptToDeviceRatio) {
- var _this = this;
- if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
- // Public members
- this.isFullscreen = false;
- this.isPointerLock = false;
- this.cullBackFaces = true;
- this.renderEvenInBackground = true;
- // To enable/disable IDB support and avoid XHR on .manifest
- this.enableOfflineSupport = true;
- this.scenes = new Array();
- this._windowIsBackground = false;
- this._webGLVersion = "1.0";
- this._drawCalls = 0;
- this._renderingQueueLaunched = false;
- this._activeRenderLoops = [];
- // FPS
- this.fpsRange = 60;
- this.previousFramesDuration = [];
- this.fps = 60;
- this.deltaTime = 0;
- // States
- this._depthCullingState = new BABYLON.Internals._DepthCullingState();
- this._alphaState = new BABYLON.Internals._AlphaState();
- this._alphaMode = Engine.ALPHA_DISABLE;
- // Cache
- this._loadedTexturesCache = new Array();
- this._maxTextureChannels = 16;
- this._activeTexturesCache = new Array(this._maxTextureChannels);
- this._compiledEffects = {};
- this._uintIndicesCurrentlySet = false;
- this._renderingCanvas = canvas;
- options = options || {};
- options.antialias = antialias;
- if (options.preserveDrawingBuffer === undefined) {
- options.preserveDrawingBuffer = false;
- }
- // GL
- //try {
- // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
- // if (this._gl) {
- // this._webGLVersion = "2.0";
- // }
- //} catch (e) {
- // // Do nothing
- //}
- if (!this._gl) {
- try {
- this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
- }
- catch (e) {
- throw new Error("WebGL not supported");
- }
- }
- if (!this._gl) {
- throw new Error("WebGL not supported");
- }
- this._onBlur = function () {
- _this._windowIsBackground = true;
- };
- this._onFocus = function () {
- _this._windowIsBackground = false;
- };
- window.addEventListener("blur", this._onBlur);
- window.addEventListener("focus", this._onFocus);
- // Viewport
- var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
- this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
- this.resize();
- // Caps
- this._caps = new EngineCapabilities();
- this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
- this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
- this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
- this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
- // Infos
- this._glVersion = this._gl.getParameter(this._gl.VERSION);
- var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
- if (rendererInfo != null) {
- this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
- this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
- }
- if (!this._glVendor) {
- this._glVendor = "Unknown vendor";
- }
- if (!this._glRenderer) {
- this._glRenderer = "Unknown renderer";
- }
- // Extensions
- this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
- this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
- this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
- 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');
- this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
- this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
- this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
- this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
- this._caps.highPrecisionShaderSupported = true;
- this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
- this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
- this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
- if (this._gl.getShaderPrecisionFormat) {
- var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
- this._caps.highPrecisionShaderSupported = highp.precision !== 0;
- }
- // Depth buffer
- this.setDepthBuffer(true);
- this.setDepthFunctionToLessOrEqual();
- this.setDepthWrite(true);
- // Fullscreen
- this._onFullscreenChange = function () {
- if (document.fullscreen !== undefined) {
- _this.isFullscreen = document.fullscreen;
- }
- else if (document.mozFullScreen !== undefined) {
- _this.isFullscreen = document.mozFullScreen;
- }
- else if (document.webkitIsFullScreen !== undefined) {
- _this.isFullscreen = document.webkitIsFullScreen;
- }
- else if (document.msIsFullScreen !== undefined) {
- _this.isFullscreen = document.msIsFullScreen;
- }
- // Pointer lock
- if (_this.isFullscreen && _this._pointerLockRequested) {
- canvas.requestPointerLock = canvas.requestPointerLock ||
- canvas.msRequestPointerLock ||
- canvas.mozRequestPointerLock ||
- canvas.webkitRequestPointerLock;
- if (canvas.requestPointerLock) {
- canvas.requestPointerLock();
- }
- }
- };
- document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
- document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
- document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
- document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
- // Pointer lock
- this._onPointerLockChange = function () {
- _this.isPointerLock = (document.mozPointerLockElement === canvas ||
- document.webkitPointerLockElement === canvas ||
- document.msPointerLockElement === canvas ||
- document.pointerLockElement === canvas);
- };
- document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
- document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
- document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
- document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
- if (BABYLON.AudioEngine && !Engine.audioEngine) {
- Engine.audioEngine = new BABYLON.AudioEngine();
- }
- //default loading screen
- this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
- BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
- }
- Object.defineProperty(Engine, "ALPHA_DISABLE", {
- get: function () {
- return Engine._ALPHA_DISABLE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "ALPHA_ONEONE", {
- get: function () {
- return Engine._ALPHA_ONEONE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "ALPHA_ADD", {
- get: function () {
- return Engine._ALPHA_ADD;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "ALPHA_COMBINE", {
- get: function () {
- return Engine._ALPHA_COMBINE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
- get: function () {
- return Engine._ALPHA_SUBTRACT;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
- get: function () {
- return Engine._ALPHA_MULTIPLY;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
- get: function () {
- return Engine._ALPHA_MAXIMIZED;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
- get: function () {
- return Engine._DELAYLOADSTATE_NONE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
- get: function () {
- return Engine._DELAYLOADSTATE_LOADED;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
- get: function () {
- return Engine._DELAYLOADSTATE_LOADING;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
- get: function () {
- return Engine._DELAYLOADSTATE_NOTLOADED;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
- get: function () {
- return Engine._TEXTUREFORMAT_ALPHA;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
- get: function () {
- return Engine._TEXTUREFORMAT_LUMINANCE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
- get: function () {
- return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
- get: function () {
- return Engine._TEXTUREFORMAT_RGB;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
- get: function () {
- return Engine._TEXTUREFORMAT_RGBA;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
- get: function () {
- return Engine._TEXTURETYPE_UNSIGNED_INT;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
- get: function () {
- return Engine._TEXTURETYPE_FLOAT;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "Version", {
- get: function () {
- return "2.4.0-alpha";
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine.prototype, "webGLVersion", {
- get: function () {
- return this._webGLVersion;
- },
- enumerable: true,
- configurable: true
- });
- Engine.prototype._prepareWorkingCanvas = function () {
- if (this._workingCanvas) {
- return;
- }
- this._workingCanvas = document.createElement("canvas");
- this._workingContext = this._workingCanvas.getContext("2d");
- };
- Engine.prototype.resetTextureCache = function () {
- for (var index = 0; index < this._maxTextureChannels; index++) {
- this._activeTexturesCache[index] = null;
- }
- };
- Engine.prototype.getGlInfo = function () {
- return {
- vendor: this._glVendor,
- renderer: this._glRenderer,
- version: this._glVersion
- };
- };
- Engine.prototype.getAspectRatio = function (camera, useScreen) {
- if (useScreen === void 0) { useScreen = false; }
- var viewport = camera.viewport;
- return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
- };
- Engine.prototype.getRenderWidth = function (useScreen) {
- if (useScreen === void 0) { useScreen = false; }
- if (!useScreen && this._currentRenderTarget) {
- return this._currentRenderTarget._width;
- }
- return this._renderingCanvas.width;
- };
- Engine.prototype.getRenderHeight = function (useScreen) {
- if (useScreen === void 0) { useScreen = false; }
- if (!useScreen && this._currentRenderTarget) {
- return this._currentRenderTarget._height;
- }
- return this._renderingCanvas.height;
- };
- Engine.prototype.getRenderingCanvas = function () {
- return this._renderingCanvas;
- };
- Engine.prototype.getRenderingCanvasClientRect = function () {
- return this._renderingCanvas.getBoundingClientRect();
- };
- Engine.prototype.setHardwareScalingLevel = function (level) {
- this._hardwareScalingLevel = level;
- this.resize();
- };
- Engine.prototype.getHardwareScalingLevel = function () {
- return this._hardwareScalingLevel;
- };
- Engine.prototype.getLoadedTexturesCache = function () {
- return this._loadedTexturesCache;
- };
- Engine.prototype.getCaps = function () {
- return this._caps;
- };
- Object.defineProperty(Engine.prototype, "drawCalls", {
- get: function () {
- return this._drawCalls;
- },
- enumerable: true,
- configurable: true
- });
- // Methods
- Engine.prototype.resetDrawCalls = function () {
- this._drawCalls = 0;
- };
- Engine.prototype.setDepthFunctionToGreater = function () {
- this._depthCullingState.depthFunc = this._gl.GREATER;
- };
- Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
- this._depthCullingState.depthFunc = this._gl.GEQUAL;
- };
- Engine.prototype.setDepthFunctionToLess = function () {
- this._depthCullingState.depthFunc = this._gl.LESS;
- };
- Engine.prototype.setDepthFunctionToLessOrEqual = function () {
- this._depthCullingState.depthFunc = this._gl.LEQUAL;
- };
- /**
- * stop executing a render loop function and remove it from the execution array
- * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
- */
- Engine.prototype.stopRenderLoop = function (renderFunction) {
- if (!renderFunction) {
- this._activeRenderLoops = [];
- return;
- }
- var index = this._activeRenderLoops.indexOf(renderFunction);
- if (index >= 0) {
- this._activeRenderLoops.splice(index, 1);
- }
- };
- Engine.prototype._renderLoop = function () {
- var shouldRender = true;
- if (!this.renderEvenInBackground && this._windowIsBackground) {
- shouldRender = false;
- }
- if (shouldRender) {
- // Start new frame
- this.beginFrame();
- for (var index = 0; index < this._activeRenderLoops.length; index++) {
- var renderFunction = this._activeRenderLoops[index];
- renderFunction();
- }
- // Present
- this.endFrame();
- }
- if (this._activeRenderLoops.length > 0) {
- // Register new frame
- BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
- }
- else {
- this._renderingQueueLaunched = false;
- }
- };
- /**
- * Register and execute a render loop. The engine can have more than one render function.
- * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
- * @example
- * engine.runRenderLoop(function () {
- * scene.render()
- * })
- */
- Engine.prototype.runRenderLoop = function (renderFunction) {
- if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
- return;
- }
- this._activeRenderLoops.push(renderFunction);
- if (!this._renderingQueueLaunched) {
- this._renderingQueueLaunched = true;
- this._bindedRenderFunction = this._renderLoop.bind(this);
- BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
- }
- };
- /**
- * Toggle full screen mode.
- * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
- */
- Engine.prototype.switchFullscreen = function (requestPointerLock) {
- if (this.isFullscreen) {
- BABYLON.Tools.ExitFullscreen();
- }
- else {
- this._pointerLockRequested = requestPointerLock;
- BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
- }
- };
- Engine.prototype.clear = function (color, backBuffer, depthStencil) {
- this.applyStates();
- if (backBuffer) {
- this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
- }
- if (depthStencil && this._depthCullingState.depthMask) {
- this._gl.clearDepth(1.0);
- }
- var mode = 0;
- if (backBuffer) {
- mode |= this._gl.COLOR_BUFFER_BIT;
- }
- if (depthStencil && this._depthCullingState.depthMask) {
- mode |= this._gl.DEPTH_BUFFER_BIT;
- }
- this._gl.clear(mode);
- };
- /**
- * Set the WebGL's viewport
- * @param {BABYLON.Viewport} viewport - the viewport element to be used.
- * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
- * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
- */
- Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
- var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
- var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
- var x = viewport.x || 0;
- var y = viewport.y || 0;
- this._cachedViewport = viewport;
- this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
- };
- Engine.prototype.setDirectViewport = function (x, y, width, height) {
- this._cachedViewport = null;
- this._gl.viewport(x, y, width, height);
- };
- Engine.prototype.beginFrame = function () {
- this._measureFps();
- };
- Engine.prototype.endFrame = function () {
- //this.flushFramebuffer();
- };
- /**
- * resize the view according to the canvas' size.
- * @example
- * window.addEventListener("resize", function () {
- * engine.resize();
- * });
- */
- Engine.prototype.resize = function () {
- var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
- var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
- this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
- for (var index = 0; index < this.scenes.length; index++) {
- var scene = this.scenes[index];
- if (scene.debugLayer.isVisible()) {
- scene.debugLayer._syncPositions();
- }
- }
- };
- /**
- * force a specific size of the canvas
- * @param {number} width - the new canvas' width
- * @param {number} height - the new canvas' height
- */
- Engine.prototype.setSize = function (width, height) {
- this._renderingCanvas.width = width;
- this._renderingCanvas.height = height;
- for (var index = 0; index < this.scenes.length; index++) {
- var scene = this.scenes[index];
- for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
- var cam = scene.cameras[camIndex];
- cam._currentRenderId = 0;
- }
- }
- };
- Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
- this._currentRenderTarget = texture;
- var gl = this._gl;
- gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
- if (texture.isCube) {
- gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
- }
- else {
- gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
- }
- this._gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
- this.wipeCaches();
- };
- Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
- if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
- this._currentRenderTarget = null;
- if (texture.generateMipMaps && !disableGenerateMipMaps) {
- var gl = this._gl;
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.generateMipmap(gl.TEXTURE_2D);
- gl.bindTexture(gl.TEXTURE_2D, null);
- }
- this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
- };
- Engine.prototype.generateMipMapsForCubemap = function (texture) {
- if (texture.generateMipMaps) {
- var gl = this._gl;
- gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
- gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
- gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
- }
- };
- Engine.prototype.flushFramebuffer = function () {
- this._gl.flush();
- };
- Engine.prototype.restoreDefaultFramebuffer = function () {
- this._currentRenderTarget = null;
- this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
- this.setViewport(this._cachedViewport);
- this.wipeCaches();
- };
- // VBOs
- Engine.prototype._resetVertexBufferBinding = function () {
- this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
- this._cachedVertexBuffers = null;
- };
- Engine.prototype.createVertexBuffer = function (vertices) {
- var vbo = this._gl.createBuffer();
- this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
- if (vertices instanceof Float32Array) {
- this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
- }
- else {
- this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
- }
- this._resetVertexBufferBinding();
- vbo.references = 1;
- return vbo;
- };
- Engine.prototype.createDynamicVertexBuffer = function (capacity) {
- var vbo = this._gl.createBuffer();
- this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
- this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
- this._resetVertexBufferBinding();
- vbo.references = 1;
- return vbo;
- };
- Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
- this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
- if (offset === undefined) {
- offset = 0;
- }
- if (vertices instanceof Float32Array) {
- this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
- }
- else {
- this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
- }
- this._resetVertexBufferBinding();
- };
- Engine.prototype._resetIndexBufferBinding = function () {
- this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
- this._cachedIndexBuffer = null;
- };
- Engine.prototype.createIndexBuffer = function (indices) {
- var vbo = this._gl.createBuffer();
- this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
- // Check for 32 bits indices
- var arrayBuffer;
- var need32Bits = false;
- if (this._caps.uintIndices) {
- for (var index = 0; index < indices.length; index++) {
- if (indices[index] > 65535) {
- need32Bits = true;
- break;
- }
- }
- arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
- }
- else {
- arrayBuffer = new Uint16Array(indices);
- }
- this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
- this._resetIndexBufferBinding();
- vbo.references = 1;
- vbo.is32Bits = need32Bits;
- return vbo;
- };
- Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
- if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
- this._cachedVertexBuffers = vertexBuffer;
- this._cachedEffectForVertexBuffers = effect;
- this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
- var offset = 0;
- for (var index = 0; index < vertexDeclaration.length; index++) {
- var order = effect.getAttributeLocation(index);
- if (order >= 0) {
- this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
- }
- offset += vertexDeclaration[index] * 4;
- }
- }
- if (this._cachedIndexBuffer !== indexBuffer) {
- this._cachedIndexBuffer = indexBuffer;
- this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
- this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
- }
- };
- Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
- if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
- this._cachedVertexBuffers = vertexBuffers;
- this._cachedEffectForVertexBuffers = effect;
- var attributes = effect.getAttributesNames();
- for (var index = 0; index < attributes.length; index++) {
- var order = effect.getAttributeLocation(index);
- if (order >= 0) {
- var vertexBuffer = vertexBuffers[attributes[index]];
- if (!vertexBuffer) {
- continue;
- }
- var stride = vertexBuffer.getStrideSize();
- this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
- this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
- }
- }
- }
- if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
- this._cachedIndexBuffer = indexBuffer;
- this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
- this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
- }
- };
- Engine.prototype._releaseBuffer = function (buffer) {
- buffer.references--;
- if (buffer.references === 0) {
- this._gl.deleteBuffer(buffer);
- return true;
- }
- return false;
- };
- Engine.prototype.createInstancesBuffer = function (capacity) {
- var buffer = this._gl.createBuffer();
- buffer.capacity = capacity;
- this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
- this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
- return buffer;
- };
- Engine.prototype.deleteInstancesBuffer = function (buffer) {
- this._gl.deleteBuffer(buffer);
- };
- Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
- this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
- this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
- for (var index = 0; index < 4; index++) {
- var offsetLocation = offsetLocations[index];
- this._gl.enableVertexAttribArray(offsetLocation);
- this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
- this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
- }
- };
- Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
- this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
- for (var index = 0; index < 4; index++) {
- var offsetLocation = offsetLocations[index];
- this._gl.disableVertexAttribArray(offsetLocation);
- this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
- }
- };
- Engine.prototype.applyStates = function () {
- this._depthCullingState.apply(this._gl);
- this._alphaState.apply(this._gl);
- };
- Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
- // Apply states
- this.applyStates();
- this._drawCalls++;
- // Render
- var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
- var mult = this._uintIndicesCurrentlySet ? 4 : 2;
- if (instancesCount) {
- this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
- return;
- }
- this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
- };
- Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
- // Apply states
- this.applyStates();
- this._drawCalls++;
- if (instancesCount) {
- this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
- return;
- }
- this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
- };
- Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
- // Apply states
- this.applyStates();
- this._drawCalls++;
- if (instancesCount) {
- this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
- return;
- }
- this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
- };
- // Shaders
- Engine.prototype._releaseEffect = function (effect) {
- if (this._compiledEffects[effect._key]) {
- delete this._compiledEffects[effect._key];
- if (effect.getProgram()) {
- this._gl.deleteProgram(effect.getProgram());
- }
- }
- };
- Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
- var vertex = baseName.vertexElement || baseName.vertex || baseName;
- var fragment = baseName.fragmentElement || baseName.fragment || baseName;
- var name = vertex + "+" + fragment + "@" + defines;
- if (this._compiledEffects[name]) {
- return this._compiledEffects[name];
- }
- var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
- effect._key = name;
- this._compiledEffects[name] = effect;
- return effect;
- };
- Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
- if (uniformsNames === void 0) { uniformsNames = []; }
- if (samplers === void 0) { samplers = []; }
- if (defines === void 0) { defines = ""; }
- return this.createEffect({
- vertex: "particles",
- fragmentElement: fragmentName
- }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
- };
- Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
- var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
- var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
- var shaderProgram = this._gl.createProgram();
- this._gl.attachShader(shaderProgram, vertexShader);
- this._gl.attachShader(shaderProgram, fragmentShader);
- this._gl.linkProgram(shaderProgram);
- var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
- if (!linked) {
- var error = this._gl.getProgramInfoLog(shaderProgram);
- if (error) {
- throw new Error(error);
- }
- }
- this._gl.deleteShader(vertexShader);
- this._gl.deleteShader(fragmentShader);
- return shaderProgram;
- };
- Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
- var results = [];
- for (var index = 0; index < uniformsNames.length; index++) {
- results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
- }
- return results;
- };
- Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
- var results = [];
- for (var index = 0; index < attributesNames.length; index++) {
- try {
- results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
- }
- catch (e) {
- results.push(-1);
- }
- }
- return results;
- };
- Engine.prototype.enableEffect = function (effect) {
- if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
- if (effect && effect.onBind) {
- effect.onBind(effect);
- }
- return;
- }
- this._vertexAttribArrays = this._vertexAttribArrays || [];
- // Use program
- this._gl.useProgram(effect.getProgram());
- for (var i in this._vertexAttribArrays) {
- //make sure this is a number)
- var iAsNumber = +i;
- if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
- continue;
- }
- this._vertexAttribArrays[iAsNumber] = false;
- this._gl.disableVertexAttribArray(iAsNumber);
- }
- var attributesCount = effect.getAttributesCount();
- for (var index = 0; index < attributesCount; index++) {
- // Attributes
- var order = effect.getAttributeLocation(index);
- if (order >= 0) {
- this._vertexAttribArrays[order] = true;
- this._gl.enableVertexAttribArray(order);
- }
- }
- this._currentEffect = effect;
- if (effect.onBind) {
- effect.onBind(effect);
- }
- };
- Engine.prototype.setArray = function (uniform, array) {
- if (!uniform)
- return;
- this._gl.uniform1fv(uniform, array);
- };
- Engine.prototype.setArray2 = function (uniform, array) {
- if (!uniform || array.length % 2 !== 0)
- return;
- this._gl.uniform2fv(uniform, array);
- };
- Engine.prototype.setArray3 = function (uniform, array) {
- if (!uniform || array.length % 3 !== 0)
- return;
- this._gl.uniform3fv(uniform, array);
- };
- Engine.prototype.setArray4 = function (uniform, array) {
- if (!uniform || array.length % 4 !== 0)
- return;
- this._gl.uniform4fv(uniform, array);
- };
- Engine.prototype.setMatrices = function (uniform, matrices) {
- if (!uniform)
- return;
- this._gl.uniformMatrix4fv(uniform, false, matrices);
- };
- Engine.prototype.setMatrix = function (uniform, matrix) {
- if (!uniform)
- return;
- this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
- };
- Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
- if (!uniform)
- return;
- this._gl.uniformMatrix3fv(uniform, false, matrix);
- };
- Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
- if (!uniform)
- return;
- this._gl.uniformMatrix2fv(uniform, false, matrix);
- };
- Engine.prototype.setFloat = function (uniform, value) {
- if (!uniform)
- return;
- this._gl.uniform1f(uniform, value);
- };
- Engine.prototype.setFloat2 = function (uniform, x, y) {
- if (!uniform)
- return;
- this._gl.uniform2f(uniform, x, y);
- };
- Engine.prototype.setFloat3 = function (uniform, x, y, z) {
- if (!uniform)
- return;
- this._gl.uniform3f(uniform, x, y, z);
- };
- Engine.prototype.setBool = function (uniform, bool) {
- if (!uniform)
- return;
- this._gl.uniform1i(uniform, bool);
- };
- Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
- if (!uniform)
- return;
- this._gl.uniform4f(uniform, x, y, z, w);
- };
- Engine.prototype.setColor3 = function (uniform, color3) {
- if (!uniform)
- return;
- this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
- };
- Engine.prototype.setColor4 = function (uniform, color3, alpha) {
- if (!uniform)
- return;
- this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
- };
- // States
- Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
- if (zOffset === void 0) { zOffset = 0; }
- if (reverseSide === void 0) { reverseSide = false; }
- // Culling
- var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
- var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
- var cullFace = this.cullBackFaces ? showSide : hideSide;
- if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
- if (culling) {
- this._depthCullingState.cullFace = cullFace;
- this._depthCullingState.cull = true;
- }
- else {
- this._depthCullingState.cull = false;
- }
- }
- // Z offset
- this._depthCullingState.zOffset = zOffset;
- };
- Engine.prototype.setDepthBuffer = function (enable) {
- this._depthCullingState.depthTest = enable;
- };
- Engine.prototype.getDepthWrite = function () {
- return this._depthCullingState.depthMask;
- };
- Engine.prototype.setDepthWrite = function (enable) {
- this._depthCullingState.depthMask = enable;
- };
- Engine.prototype.setColorWrite = function (enable) {
- this._gl.colorMask(enable, enable, enable, enable);
- };
- Engine.prototype.setAlphaMode = function (mode) {
- if (this._alphaMode === mode) {
- return;
- }
- switch (mode) {
- case Engine.ALPHA_DISABLE:
- this.setDepthWrite(true);
- this._alphaState.alphaBlend = false;
- break;
- case Engine.ALPHA_COMBINE:
- this.setDepthWrite(false);
- this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
- this._alphaState.alphaBlend = true;
- break;
- case Engine.ALPHA_ONEONE:
- this.setDepthWrite(false);
- this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
- this._alphaState.alphaBlend = true;
- break;
- case Engine.ALPHA_ADD:
- this.setDepthWrite(false);
- this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
- this._alphaState.alphaBlend = true;
- break;
- case Engine.ALPHA_SUBTRACT:
- this.setDepthWrite(false);
- this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
- this._alphaState.alphaBlend = true;
- break;
- case Engine.ALPHA_MULTIPLY:
- this.setDepthWrite(false);
- this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
- this._alphaState.alphaBlend = true;
- break;
- case Engine.ALPHA_MAXIMIZED:
- this.setDepthWrite(false);
- this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
- this._alphaState.alphaBlend = true;
- break;
- }
- this._alphaMode = mode;
- };
- Engine.prototype.getAlphaMode = function () {
- return this._alphaMode;
- };
- Engine.prototype.setAlphaTesting = function (enable) {
- this._alphaTest = enable;
- };
- Engine.prototype.getAlphaTesting = function () {
- return this._alphaTest;
- };
- // Textures
- Engine.prototype.wipeCaches = function () {
- this.resetTextureCache();
- this._currentEffect = null;
- this._depthCullingState.reset();
- this._alphaState.reset();
- this._cachedVertexBuffers = null;
- this._cachedIndexBuffer = null;
- this._cachedEffectForVertexBuffers = null;
- };
- Engine.prototype.setSamplingMode = function (texture, samplingMode) {
- var gl = this._gl;
- gl.bindTexture(gl.TEXTURE_2D, texture);
- var magFilter = gl.NEAREST;
- var minFilter = gl.NEAREST;
- if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
- magFilter = gl.LINEAR;
- minFilter = gl.LINEAR;
- }
- else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
- magFilter = gl.LINEAR;
- minFilter = gl.LINEAR_MIPMAP_LINEAR;
- }
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
- gl.bindTexture(gl.TEXTURE_2D, null);
- texture.samplingMode = samplingMode;
- };
- Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
- var _this = this;
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
- if (onLoad === void 0) { onLoad = null; }
- if (onError === void 0) { onError = null; }
- if (buffer === void 0) { buffer = null; }
- var texture = this._gl.createTexture();
- var extension;
- var fromData = false;
- if (url.substr(0, 5) === "data:") {
- fromData = true;
- }
- if (!fromData)
- extension = url.substr(url.length - 4, 4).toLowerCase();
- else {
- var oldUrl = url;
- fromData = oldUrl.split(':');
- url = oldUrl;
- extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
- }
- var isDDS = this.getCaps().s3tc && (extension === ".dds");
- var isTGA = (extension === ".tga");
- scene._addPendingData(texture);
- texture.url = url;
- texture.noMipmap = noMipmap;
- texture.references = 1;
- texture.samplingMode = samplingMode;
- this._loadedTexturesCache.push(texture);
- var onerror = function () {
- scene._removePendingData(texture);
- if (onError) {
- onError();
- }
- };
- var callback;
- if (isTGA) {
- callback = function (arrayBuffer) {
- var data = new Uint8Array(arrayBuffer);
- var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
- prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
- BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
- }, onLoad, samplingMode);
- };
- if (!(fromData instanceof Array))
- BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
- callback(arrayBuffer);
- }, onerror, scene.database, true);
- else
- callback(buffer);
- }
- else if (isDDS) {
- callback = function (data) {
- var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
- var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
- prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
- BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
- }, onLoad, samplingMode);
- };
- if (!(fromData instanceof Array))
- BABYLON.Tools.LoadFile(url, function (data) {
- callback(data);
- }, onerror, scene.database, true);
- else
- callback(buffer);
- }
- else {
- var onload = function (img) {
- prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
- var isPot = (img.width === potWidth && img.height === potHeight);
- if (!isPot) {
- _this._prepareWorkingCanvas();
- _this._workingCanvas.width = potWidth;
- _this._workingCanvas.height = potHeight;
- if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
- _this._workingContext.imageSmoothingEnabled = false;
- _this._workingContext.mozImageSmoothingEnabled = false;
- _this._workingContext.oImageSmoothingEnabled = false;
- _this._workingContext.webkitImageSmoothingEnabled = false;
- _this._workingContext.msImageSmoothingEnabled = false;
- }
- _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
- if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
- _this._workingContext.imageSmoothingEnabled = true;
- _this._workingContext.mozImageSmoothingEnabled = true;
- _this._workingContext.oImageSmoothingEnabled = true;
- _this._workingContext.webkitImageSmoothingEnabled = true;
- _this._workingContext.msImageSmoothingEnabled = true;
- }
- }
- _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
- }, onLoad, samplingMode);
- };
- if (!(fromData instanceof Array))
- BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
- else
- BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
- }
- return texture;
- };
- Engine.prototype._getInternalFormat = function (format) {
- var internalFormat = this._gl.RGBA;
- switch (format) {
- case Engine.TEXTUREFORMAT_ALPHA:
- internalFormat = this._gl.ALPHA;
- break;
- case Engine.TEXTUREFORMAT_LUMINANCE:
- internalFormat = this._gl.LUMINANCE;
- break;
- case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
- internalFormat = this._gl.LUMINANCE_ALPHA;
- break;
- case Engine.TEXTUREFORMAT_RGB:
- internalFormat = this._gl.RGB;
- break;
- case Engine.TEXTUREFORMAT_RGBA:
- internalFormat = this._gl.RGBA;
- break;
- }
- return internalFormat;
- };
- Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
- if (compression === void 0) { compression = null; }
- var internalFormat = this._getInternalFormat(format);
- this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
- this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
- if (compression) {
- this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
- }
- else {
- this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
- }
- if (texture.generateMipMaps) {
- this._gl.generateMipmap(this._gl.TEXTURE_2D);
- }
- this._gl.bindTexture(this._gl.TEXTURE_2D, null);
- this.resetTextureCache();
- texture.isReady = true;
- };
- Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
- if (compression === void 0) { compression = null; }
- var texture = this._gl.createTexture();
- texture._baseWidth = width;
- texture._baseHeight = height;
- texture._width = width;
- texture._height = height;
- texture.references = 1;
- this.updateRawTexture(texture, data, format, invertY, compression);
- this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
- // Filters
- var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
- this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
- this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
- this._gl.bindTexture(this._gl.TEXTURE_2D, null);
- texture.samplingMode = samplingMode;
- this._loadedTexturesCache.push(texture);
- return texture;
- };
- Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
- if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
- var texture = this._gl.createTexture();
- texture._baseWidth = width;
- texture._baseHeight = height;
- if (forceExponantOfTwo) {
- width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
- height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
- }
- this.resetTextureCache();
- texture._width = width;
- texture._height = height;
- texture.isReady = false;
- texture.generateMipMaps = generateMipMaps;
- texture.references = 1;
- texture.samplingMode = samplingMode;
- this.updateTextureSamplingMode(samplingMode, texture);
- this._loadedTexturesCache.push(texture);
- return texture;
- };
- Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
- var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
- if (texture.isCube) {
- this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
- this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
- this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
- this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
- }
- else {
- this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
- this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
- this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
- this._gl.bindTexture(this._gl.TEXTURE_2D, null);
- }
- };
- Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
- this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
- this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
- this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
- if (texture.generateMipMaps) {
- this._gl.generateMipmap(this._gl.TEXTURE_2D);
- }
- this._gl.bindTexture(this._gl.TEXTURE_2D, null);
- this.resetTextureCache();
- texture.isReady = true;
- };
- Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
- if (texture._isDisabled) {
- return;
- }
- this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
- this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
- try {
- // Testing video texture support
- if (this._videoTextureSupported === undefined) {
- this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
- if (this._gl.getError() !== 0) {
- this._videoTextureSupported = false;
- }
- else {
- this._videoTextureSupported = true;
- }
- }
- // Copy video through the current working canvas if video texture is not supported
- if (!this._videoTextureSupported) {
- if (!texture._workingCanvas) {
- texture._workingCanvas = document.createElement("canvas");
- texture._workingContext = texture._workingCanvas.getContext("2d");
- texture._workingCanvas.width = texture._width;
- texture._workingCanvas.height = texture._height;
- }
- texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
- this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
- }
- else {
- this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
- }
- if (texture.generateMipMaps) {
- this._gl.generateMipmap(this._gl.TEXTURE_2D);
- }
- this._gl.bindTexture(this._gl.TEXTURE_2D, null);
- this.resetTextureCache();
- texture.isReady = true;
- }
- catch (ex) {
- // Something unexpected
- // Let's disable the texture
- texture._isDisabled = true;
- }
- };
- Engine.prototype.createRenderTargetTexture = function (size, options) {
- // old version had a "generateMipMaps" arg instead of options.
- // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
- // in the same way, generateDepthBuffer is defaulted to true
- var generateMipMaps = false;
- var generateDepthBuffer = true;
- var type = Engine.TEXTURETYPE_UNSIGNED_INT;
- var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
- if (options !== undefined) {
- generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
- generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
- type = options.type === undefined ? type : options.type;
- if (options.samplingMode !== undefined) {
- samplingMode = options.samplingMode;
- }
- if (type === Engine.TEXTURETYPE_FLOAT) {
- // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
- samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
- }
- }
- var gl = this._gl;
- var texture = gl.createTexture();
- gl.bindTexture(gl.TEXTURE_2D, texture);
- var width = size.width || size;
- var height = size.height || size;
- var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
- if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
- type = Engine.TEXTURETYPE_UNSIGNED_INT;
- BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
- }
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
- var depthBuffer;
- // Create the depth buffer
- if (generateDepthBuffer) {
- depthBuffer = gl.createRenderbuffer();
- gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
- gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
- }
- // Create the framebuffer
- var framebuffer = gl.createFramebuffer();
- gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
- if (generateDepthBuffer) {
- gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
- }
- if (generateMipMaps) {
- this._gl.generateMipmap(this._gl.TEXTURE_2D);
- }
- // Unbind
- gl.bindTexture(gl.TEXTURE_2D, null);
- gl.bindRenderbuffer(gl.RENDERBUFFER, null);
- gl.bindFramebuffer(gl.FRAMEBUFFER, null);
- texture._framebuffer = framebuffer;
- if (generateDepthBuffer) {
- texture._depthBuffer = depthBuffer;
- }
- texture._width = width;
- texture._height = height;
- texture.isReady = true;
- texture.generateMipMaps = generateMipMaps;
- texture.references = 1;
- texture.samplingMode = samplingMode;
- this.resetTextureCache();
- this._loadedTexturesCache.push(texture);
- return texture;
- };
- Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
- var gl = this._gl;
- var texture = gl.createTexture();
- var generateMipMaps = true;
- var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
- if (options !== undefined) {
- generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
- if (options.samplingMode !== undefined) {
- samplingMode = options.samplingMode;
- }
- }
- texture.isCube = true;
- texture.references = 1;
- texture.generateMipMaps = generateMipMaps;
- texture.references = 1;
- texture.samplingMode = samplingMode;
- var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
- gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
- for (var face = 0; face < 6; face++) {
- gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
- }
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- // Create the depth buffer
- var depthBuffer = gl.createRenderbuffer();
- gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
- gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
- // Create the framebuffer
- var framebuffer = gl.createFramebuffer();
- gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
- gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
- // Mipmaps
- if (texture.generateMipMaps) {
- gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
- gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
- }
- // Unbind
- gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
- gl.bindRenderbuffer(gl.RENDERBUFFER, null);
- gl.bindFramebuffer(gl.FRAMEBUFFER, null);
- texture._framebuffer = framebuffer;
- texture._depthBuffer = depthBuffer;
- this.resetTextureCache();
- texture._width = size;
- texture._height = size;
- texture.isReady = true;
- return texture;
- };
- Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
- var _this = this;
- var gl = this._gl;
- var texture = gl.createTexture();
- texture.isCube = true;
- texture.url = rootUrl;
- texture.references = 1;
- var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
- var isDDS = this.getCaps().s3tc && (extension === ".dds");
- if (isDDS) {
- BABYLON.Tools.LoadFile(rootUrl, function (data) {
- var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
- var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
- gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
- BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
- if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
- gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
- }
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
- _this.resetTextureCache();
- texture._width = info.width;
- texture._height = info.height;
- texture.isReady = true;
- }, null, null, true);
- }
- else {
- cascadeLoad(rootUrl, scene, function (imgs) {
- var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
- var height = width;
- _this._prepareWorkingCanvas();
- _this._workingCanvas.width = width;
- _this._workingCanvas.height = height;
- var faces = [
- gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
- gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
- ];
- gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
- for (var index = 0; index < faces.length; index++) {
- _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
- gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
- }
- if (!noMipmap) {
- gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
- }
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
- _this.resetTextureCache();
- texture._width = width;
- texture._height = height;
- texture.isReady = true;
- }, files);
- }
- return texture;
- };
- Engine.prototype.updateTextureSize = function (texture, width, height) {
- texture._width = width;
- texture._height = height;
- };
- Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
- var _this = this;
- var gl = this._gl;
- var texture = gl.createTexture();
- scene._addPendingData(texture);
- texture.isCube = true;
- texture.references = 1;
- texture.url = url;
- var internalFormat = this._getInternalFormat(format);
- var textureType = gl.UNSIGNED_BYTE;
- if (type === Engine.TEXTURETYPE_FLOAT) {
- textureType = gl.FLOAT;
- }
- var width = size;
- var height = width;
- var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
- texture._width = width;
- texture._height = height;
- var onerror = function () {
- scene._removePendingData(texture);
- };
- var internalCallback = function (data) {
- var rgbeDataArrays = callback(data);
- var facesIndex = [
- gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
- gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
- ];
- width = texture._width;
- height = texture._height;
- isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
- gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
- if (!noMipmap && isPot) {
- if (mipmmapGenerator) {
- var arrayTemp = [];
- // Data are known to be in +X +Y +Z -X -Y -Z
- // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
- arrayTemp.push(rgbeDataArrays[0]); // +X
- arrayTemp.push(rgbeDataArrays[3]); // -X
- arrayTemp.push(rgbeDataArrays[1]); // +Y
- arrayTemp.push(rgbeDataArrays[4]); // -Y
- arrayTemp.push(rgbeDataArrays[2]); // +Z
- arrayTemp.push(rgbeDataArrays[5]); // -Z
- var mipData = mipmmapGenerator(arrayTemp);
- for (var level = 0; level < mipData.length; level++) {
- var mipSize = width >> level;
- // mipData is order in +X -X +Y -Y +Z -Z
- gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
- gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
- gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
- gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
- gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
- gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
- }
- }
- else {
- // Data are known to be in +X +Y +Z -X -Y -Z
- for (var index = 0; index < facesIndex.length; index++) {
- var faceData = rgbeDataArrays[index];
- gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
- }
- gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
- }
- }
- else {
- noMipmap = true;
- }
- if (textureType == gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
- }
- else {
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
- }
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
- texture.isReady = true;
- _this.resetTextureCache();
- scene._removePendingData(texture);
- };
- BABYLON.Tools.LoadFile(url, function (data) {
- internalCallback(data);
- }, onerror, scene.database, true);
- return texture;
- };
- ;
- Engine.prototype._releaseTexture = function (texture) {
- var gl = this._gl;
- if (texture._framebuffer) {
- gl.deleteFramebuffer(texture._framebuffer);
- }
- if (texture._depthBuffer) {
- gl.deleteRenderbuffer(texture._depthBuffer);
- }
- gl.deleteTexture(texture);
- // Unbind channels
- this.unbindAllTextures();
- var index = this._loadedTexturesCache.indexOf(texture);
- if (index !== -1) {
- this._loadedTexturesCache.splice(index, 1);
- }
- };
- Engine.prototype.bindSamplers = function (effect) {
- this._gl.useProgram(effect.getProgram());
- var samplers = effect.getSamplers();
- for (var index = 0; index < samplers.length; index++) {
- var uniform = effect.getUniform(samplers[index]);
- this._gl.uniform1i(uniform, index);
- }
- this._currentEffect = null;
- };
- Engine.prototype._bindTexture = function (channel, texture) {
- this._gl.activeTexture(this._gl["TEXTURE" + channel]);
- this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
- this._activeTexturesCache[channel] = null;
- };
- Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
- this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
- };
- Engine.prototype.unbindAllTextures = function () {
- for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
- this._gl.activeTexture(this._gl["TEXTURE" + channel]);
- this._gl.bindTexture(this._gl.TEXTURE_2D, null);
- this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
- this._activeTexturesCache[channel] = null;
- }
- };
- Engine.prototype.setTexture = function (channel, texture) {
- if (channel < 0) {
- return;
- }
- // Not ready?
- if (!texture || !texture.isReady()) {
- if (this._activeTexturesCache[channel] != null) {
- this._gl.activeTexture(this._gl["TEXTURE" + channel]);
- this._gl.bindTexture(this._gl.TEXTURE_2D, null);
- this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
- this._activeTexturesCache[channel] = null;
- }
- return;
- }
- // Video
- var alreadyActivated = false;
- if (texture instanceof BABYLON.VideoTexture) {
- this._gl.activeTexture(this._gl["TEXTURE" + channel]);
- alreadyActivated = true;
- texture.update();
- }
- else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
- texture.delayLoad();
- return;
- }
- if (this._activeTexturesCache[channel] === texture) {
- return;
- }
- this._activeTexturesCache[channel] = texture;
- var internalTexture = texture.getInternalTexture();
- if (!alreadyActivated) {
- this._gl.activeTexture(this._gl["TEXTURE" + channel]);
- }
- if (internalTexture.isCube) {
- this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
- if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
- internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
- // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
- var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
- this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
- this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
- }
- this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
- }
- else {
- this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
- if (internalTexture._cachedWrapU !== texture.wrapU) {
- internalTexture._cachedWrapU = texture.wrapU;
- switch (texture.wrapU) {
- case BABYLON.Texture.WRAP_ADDRESSMODE:
- this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
- break;
- case BABYLON.Texture.CLAMP_ADDRESSMODE:
- this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
- break;
- case BABYLON.Texture.MIRROR_ADDRESSMODE:
- this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
- break;
- }
- }
- if (internalTexture._cachedWrapV !== texture.wrapV) {
- internalTexture._cachedWrapV = texture.wrapV;
- switch (texture.wrapV) {
- case BABYLON.Texture.WRAP_ADDRESSMODE:
- this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
- break;
- case BABYLON.Texture.CLAMP_ADDRESSMODE:
- this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
- break;
- case BABYLON.Texture.MIRROR_ADDRESSMODE:
- this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
- break;
- }
- }
- this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
- }
- };
- Engine.prototype._setAnisotropicLevel = function (key, texture) {
- var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
- var value = texture.anisotropicFilteringLevel;
- if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
- value = 1;
- }
- if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
- this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
- texture._cachedAnisotropicFilteringLevel = value;
- }
- };
- Engine.prototype.readPixels = function (x, y, width, height) {
- var data = new Uint8Array(height * width * 4);
- this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
- return data;
- };
- Engine.prototype.releaseInternalTexture = function (texture) {
- if (!texture) {
- return;
- }
- texture.references--;
- // Final reference ?
- if (texture.references === 0) {
- var texturesCache = this.getLoadedTexturesCache();
- var index = texturesCache.indexOf(texture);
- if (index > -1) {
- texturesCache.splice(index, 1);
- }
- this._releaseTexture(texture);
- }
- };
- // Dispose
- Engine.prototype.dispose = function () {
- this.hideLoadingUI();
- this.stopRenderLoop();
- // Release scenes
- while (this.scenes.length) {
- this.scenes[0].dispose();
- }
- // Release audio engine
- Engine.audioEngine.dispose();
- // Release effects
- for (var name in this._compiledEffects) {
- this._gl.deleteProgram(this._compiledEffects[name]._program);
- }
- // Unbind
- for (var i in this._vertexAttribArrays) {
- //making sure this is a string
- var iAsNumber = +i;
- if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
- continue;
- }
- this._gl.disableVertexAttribArray(iAsNumber);
- }
- this._gl = null;
- // Events
- window.removeEventListener("blur", this._onBlur);
- window.removeEventListener("focus", this._onFocus);
- document.removeEventListener("fullscreenchange", this._onFullscreenChange);
- document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
- document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
- document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
- document.removeEventListener("pointerlockchange", this._onPointerLockChange);
- document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
- document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
- document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
- };
- // Loading screen
- Engine.prototype.displayLoadingUI = function () {
- this._loadingScreen.displayLoadingUI();
- };
- Engine.prototype.hideLoadingUI = function () {
- this._loadingScreen.hideLoadingUI();
- };
- Object.defineProperty(Engine.prototype, "loadingScreen", {
- get: function () {
- return this._loadingScreen;
- },
- set: function (loadingScreen) {
- this._loadingScreen = loadingScreen;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine.prototype, "loadingUIText", {
- set: function (text) {
- this._loadingScreen.loadingUIText = text;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
- set: function (color) {
- this._loadingScreen.loadingUIBackgroundColor = color;
- },
- enumerable: true,
- configurable: true
- });
- // FPS
- Engine.prototype.getFps = function () {
- return this.fps;
- };
- Engine.prototype.getDeltaTime = function () {
- return this.deltaTime;
- };
- Engine.prototype._measureFps = function () {
- this.previousFramesDuration.push(BABYLON.Tools.Now);
- var length = this.previousFramesDuration.length;
- if (length >= 2) {
- this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
- }
- if (length >= this.fpsRange) {
- if (length > this.fpsRange) {
- this.previousFramesDuration.splice(0, 1);
- length = this.previousFramesDuration.length;
- }
- var sum = 0;
- for (var id = 0; id < length - 1; id++) {
- sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
- }
- this.fps = 1000.0 / (sum / (length - 1));
- }
- };
- // Statics
- Engine.isSupported = function () {
- try {
- // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
- if (navigator.isCocoonJS) {
- return true;
- }
- var tempcanvas = document.createElement("canvas");
- var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
- return gl != null && !!window.WebGLRenderingContext;
- }
- catch (e) {
- return false;
- }
- };
- // Const statics
- Engine._ALPHA_DISABLE = 0;
- Engine._ALPHA_ADD = 1;
- Engine._ALPHA_COMBINE = 2;
- Engine._ALPHA_SUBTRACT = 3;
- Engine._ALPHA_MULTIPLY = 4;
- Engine._ALPHA_MAXIMIZED = 5;
- Engine._ALPHA_ONEONE = 6;
- Engine._DELAYLOADSTATE_NONE = 0;
- Engine._DELAYLOADSTATE_LOADED = 1;
- Engine._DELAYLOADSTATE_LOADING = 2;
- Engine._DELAYLOADSTATE_NOTLOADED = 4;
- Engine._TEXTUREFORMAT_ALPHA = 0;
- Engine._TEXTUREFORMAT_LUMINANCE = 1;
- Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
- Engine._TEXTUREFORMAT_RGB = 4;
- Engine._TEXTUREFORMAT_RGBA = 5;
- Engine._TEXTURETYPE_UNSIGNED_INT = 0;
- Engine._TEXTURETYPE_FLOAT = 1;
- // Updatable statics so stick with vars here
- Engine.CollisionsEpsilon = 0.001;
- Engine.CodeRepository = "src/";
- Engine.ShadersRepository = "src/Shaders/";
- return Engine;
- })();
- BABYLON.Engine = Engine;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- /**
- * Node is the basic class for all scene objects (Mesh, Light Camera).
- */
- var Node = (function () {
- /**
- * @constructor
- * @param {string} name - the name and id to be given to this node
- * @param {BABYLON.Scene} the scene this node will be added to
- */
- function Node(name, scene) {
- this.state = "";
- this.animations = new Array();
- this._ranges = {};
- this._childrenFlag = -1;
- this._isEnabled = true;
- this._isReady = true;
- this._currentRenderId = -1;
- this._parentRenderId = -1;
- this.name = name;
- this.id = name;
- this._scene = scene;
- this._initCache();
- }
- Object.defineProperty(Node.prototype, "parent", {
- get: function () {
- return this._parentNode;
- },
- set: function (parent) {
- if (this._parentNode === parent) {
- return;
- }
- if (this._parentNode) {
- var index = this._parentNode._children.indexOf(this);
- if (index !== -1) {
- this._parentNode._children.splice(index, 1);
- }
- }
- this._parentNode = parent;
- if (this._parentNode) {
- if (!this._parentNode._children) {
- this._parentNode._children = new Array();
- }
- this._parentNode._children.push(this);
- }
- },
- enumerable: true,
- configurable: true
- });
- Node.prototype.getScene = function () {
- return this._scene;
- };
- Node.prototype.getEngine = function () {
- return this._scene.getEngine();
- };
- // override it in derived class
- Node.prototype.getWorldMatrix = function () {
- return BABYLON.Matrix.Identity();
- };
- // override it in derived class if you add new variables to the cache
- // and call the parent class method
- Node.prototype._initCache = function () {
- this._cache = {};
- this._cache.parent = undefined;
- };
- Node.prototype.updateCache = function (force) {
- if (!force && this.isSynchronized())
- return;
- this._cache.parent = this.parent;
- this._updateCache();
- };
- // override it in derived class if you add new variables to the cache
- // and call the parent class method if !ignoreParentClass
- Node.prototype._updateCache = function (ignoreParentClass) {
- };
- // override it in derived class if you add new variables to the cache
- Node.prototype._isSynchronized = function () {
- return true;
- };
- Node.prototype._markSyncedWithParent = function () {
- this._parentRenderId = this.parent._currentRenderId;
- };
- Node.prototype.isSynchronizedWithParent = function () {
- if (!this.parent) {
- return true;
- }
- if (this._parentRenderId !== this.parent._currentRenderId) {
- return false;
- }
- return this.parent.isSynchronized();
- };
- Node.prototype.isSynchronized = function (updateCache) {
- var check = this.hasNewParent();
- check = check || !this.isSynchronizedWithParent();
- check = check || !this._isSynchronized();
- if (updateCache)
- this.updateCache(true);
- return !check;
- };
- Node.prototype.hasNewParent = function (update) {
- if (this._cache.parent === this.parent)
- return false;
- if (update)
- this._cache.parent = this.parent;
- return true;
- };
- /**
- * Is this node ready to be used/rendered
- * @return {boolean} is it ready
- */
- Node.prototype.isReady = function () {
- return this._isReady;
- };
- /**
- * Is this node enabled.
- * If the node has a parent and is enabled, the parent will be inspected as well.
- * @return {boolean} whether this node (and its parent) is enabled.
- * @see setEnabled
- */
- Node.prototype.isEnabled = function () {
- if (!this._isEnabled) {
- return false;
- }
- if (this.parent) {
- return this.parent.isEnabled();
- }
- return true;
- };
- /**
- * Set the enabled state of this node.
- * @param {boolean} value - the new enabled state
- * @see isEnabled
- */
- Node.prototype.setEnabled = function (value) {
- this._isEnabled = value;
- };
- /**
- * Is this node a descendant of the given node.
- * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
- * @param {BABYLON.Node} ancestor - The parent node to inspect
- * @see parent
- */
- Node.prototype.isDescendantOf = function (ancestor) {
- if (this.parent) {
- if (this.parent === ancestor) {
- return true;
- }
- return this.parent.isDescendantOf(ancestor);
- }
- return false;
- };
- /**
- * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
- * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
- * @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.
- * @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.
- */
- Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
- if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
- if (!this._children) {
- return;
- }
- for (var index = 0; index < this._children.length; index++) {
- var item = this._children[index];
- if (!predicate || predicate(item)) {
- results.push(item);
- }
- if (!directDescendantsOnly) {
- item._getDescendants(results, false, predicate);
- }
- }
- };
- /**
- * Will return all nodes that have this node as ascendant.
- * @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.
- * @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.
- * @return {BABYLON.Node[]} all children nodes of all types.
- */
- Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
- var results = [];
- this._getDescendants(results, directDescendantsOnly, predicate);
- return results;
- };
- /**
- * @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.
- * @Deprecated, legacy support.
- * use getDecendants instead.
- */
- Node.prototype.getChildren = function (predicate) {
- return this.getDescendants(true, predicate);
- };
- /**
- * Get all child-meshes of this node.
- */
- Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
- var results = [];
- this._getDescendants(results, directDecendantsOnly, function (node) {
- return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
- });
- return results;
- };
- Node.prototype._setReady = function (state) {
- if (state === this._isReady) {
- return;
- }
- if (!state) {
- this._isReady = false;
- return;
- }
- this._isReady = true;
- if (this.onReady) {
- this.onReady(this);
- }
- };
- Node.prototype.getAnimationByName = function (name) {
- for (var i = 0; i < this.animations.length; i++) {
- var animation = this.animations[i];
- if (animation.name === name) {
- return animation;
- }
- }
- return null;
- };
- Node.prototype.createAnimationRange = function (name, from, to) {
- // check name not already in use
- if (!this._ranges[name]) {
- this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
- for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
- if (this.animations[i]) {
- this.animations[i].createRange(name, from, to);
- }
- }
- }
- };
- Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
- if (deleteFrames === void 0) { deleteFrames = true; }
- for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
- if (this.animations[i]) {
- this.animations[i].deleteRange(name, deleteFrames);
- }
- }
- this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
- };
- Node.prototype.getAnimationRange = function (name) {
- return this._ranges[name];
- };
- Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
- var range = this.getAnimationRange(name);
- if (!range) {
- return null;
- }
- this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
- };
- Node.prototype.serializeAnimationRanges = function () {
- var serializationRanges = [];
- for (var name in this._ranges) {
- var range = {};
- range.name = name;
- range.from = this._ranges[name].from;
- range.to = this._ranges[name].to;
- serializationRanges.push(range);
- }
- return serializationRanges;
- };
- Node.prototype.dispose = function () {
- this.parent = null;
- };
- Node.ParseAnimationRanges = function (node, parsedNode, scene) {
- if (parsedNode.ranges) {
- for (var index = 0; index < parsedNode.ranges.length; index++) {
- var data = parsedNode.ranges[index];
- node.createAnimationRange(data.name, data.from, data.to);
- }
- }
- };
- __decorate([
- BABYLON.serialize()
- ], Node.prototype, "name", void 0);
- __decorate([
- BABYLON.serialize()
- ], Node.prototype, "id", void 0);
- __decorate([
- BABYLON.serialize()
- ], Node.prototype, "uniqueId", void 0);
- __decorate([
- BABYLON.serialize()
- ], Node.prototype, "state", void 0);
- return Node;
- })();
- BABYLON.Node = Node;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var FilesInput = (function () {
- /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
- /// loading progress callback and optionnal addionnal logic to call in the rendering loop
- function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
- this._engine = p_engine;
- this._canvas = p_canvas;
- this._currentScene = p_scene;
- this._sceneLoadedCallback = p_sceneLoadedCallback;
- this._progressCallback = p_progressCallback;
- this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
- this._textureLoadingCallback = p_textureLoadingCallback;
- this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
- }
- FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
- var _this = this;
- if (p_elementToMonitor) {
- this._elementToMonitor = p_elementToMonitor;
- this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
- this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
- this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
- }
- };
- FilesInput.prototype.renderFunction = function () {
- if (this._additionnalRenderLoopLogicCallback) {
- this._additionnalRenderLoopLogicCallback();
- }
- if (this._currentScene) {
- if (this._textureLoadingCallback) {
- var remaining = this._currentScene.getWaitingItemsCount();
- if (remaining > 0) {
- this._textureLoadingCallback(remaining);
- }
- }
- this._currentScene.render();
- }
- };
- FilesInput.prototype.drag = function (e) {
- e.stopPropagation();
- e.preventDefault();
- };
- FilesInput.prototype.drop = function (eventDrop) {
- eventDrop.stopPropagation();
- eventDrop.preventDefault();
- this.loadFiles(eventDrop);
- };
- FilesInput.prototype.loadFiles = function (event) {
- if (this._startingProcessingFilesCallback)
- this._startingProcessingFilesCallback();
- // Handling data transfer via drag'n'drop
- if (event && event.dataTransfer && event.dataTransfer.files) {
- this._filesToLoad = event.dataTransfer.files;
- }
- // Handling files from input files
- if (event && event.target && event.target.files) {
- this._filesToLoad = event.target.files;
- }
- if (this._filesToLoad && this._filesToLoad.length > 0) {
- for (var i = 0; i < this._filesToLoad.length; i++) {
- switch (this._filesToLoad[i].type) {
- case "image/jpeg":
- case "image/png":
- case "image/bmp":
- FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
- break;
- case "image/targa":
- case "image/vnd.ms-dds":
- case "audio/wav":
- case "audio/x-wav":
- case "audio/mp3":
- case "audio/mpeg":
- case "audio/mpeg3":
- case "audio/x-mpeg-3":
- case "audio/ogg":
- FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
- break;
- default:
- if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
- FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
- }
- else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
- this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
- this._filesToLoad[i].name.indexOf(".obj") !== -1)
- && this._filesToLoad[i].name.indexOf(".manifest") === -1
- && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
- && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
- this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
- this._sceneFileToLoad = this._filesToLoad[i];
- }
- break;
- }
- }
- this.reload();
- }
- };
- FilesInput.prototype.reload = function () {
- var _this = this;
- var that = this;
- // If a ".babylon" file has been provided
- if (this._sceneFileToLoad) {
- if (this._currentScene) {
- if (BABYLON.Tools.errorsCount > 0) {
- BABYLON.Tools.ClearLogCache();
- BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
- }
- this._engine.stopRenderLoop();
- this._currentScene.dispose();
- }
- BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
- that._currentScene = newScene;
- // Wait for textures and shaders to be ready
- that._currentScene.executeWhenReady(function () {
- // Attach camera to canvas inputs
- if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
- that._currentScene.createDefaultCameraOrLight();
- }
- that._currentScene.activeCamera.attachControl(that._canvas);
- if (that._sceneLoadedCallback) {
- that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
- }
- that._engine.runRenderLoop(function () { that.renderFunction(); });
- });
- }, function (progress) {
- if (_this._progressCallback) {
- _this._progressCallback(progress);
- }
- });
- }
- else {
- BABYLON.Tools.Error("Please provide a valid .babylon file.");
- }
- };
- FilesInput.FilesTextures = new Array();
- FilesInput.FilesToLoad = new Array();
- return FilesInput;
- })();
- BABYLON.FilesInput = FilesInput;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var IntersectionInfo = (function () {
- function IntersectionInfo(bu, bv, distance) {
- this.bu = bu;
- this.bv = bv;
- this.distance = distance;
- this.faceId = 0;
- this.subMeshId = 0;
- }
- return IntersectionInfo;
- })();
- BABYLON.IntersectionInfo = IntersectionInfo;
- var PickingInfo = (function () {
- function PickingInfo() {
- this.hit = false;
- this.distance = 0;
- this.pickedPoint = null;
- this.pickedMesh = null;
- this.bu = 0;
- this.bv = 0;
- this.faceId = -1;
- this.subMeshId = 0;
- this.pickedSprite = null;
- }
- // Methods
- PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
- if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
- if (useVerticesNormals === void 0) { useVerticesNormals = true; }
- if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
- return null;
- }
- var indices = this.pickedMesh.getIndices();
- var result;
- if (useVerticesNormals) {
- var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
- var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
- var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
- var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
- normal0 = normal0.scale(this.bu);
- normal1 = normal1.scale(this.bv);
- normal2 = normal2.scale(1.0 - this.bu - this.bv);
- result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
- }
- else {
- var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
- var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
- var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
- var p1p2 = vertex1.subtract(vertex2);
- var p3p2 = vertex3.subtract(vertex2);
- result = BABYLON.Vector3.Cross(p1p2, p3p2);
- }
- if (useWorldCoordinates) {
- result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
- }
- return BABYLON.Vector3.Normalize(result);
- };
- PickingInfo.prototype.getTextureCoordinates = function () {
- if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
- return null;
- }
- var indices = this.pickedMesh.getIndices();
- var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
- var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
- var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
- var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
- uv0 = uv0.scale(1.0 - this.bu - this.bv);
- uv1 = uv1.scale(this.bu);
- uv2 = uv2.scale(this.bv);
- return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
- };
- return PickingInfo;
- })();
- BABYLON.PickingInfo = PickingInfo;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var BoundingSphere = (function () {
- function BoundingSphere(minimum, maximum) {
- this.minimum = minimum;
- this.maximum = maximum;
- this._tempRadiusVector = BABYLON.Vector3.Zero();
- var distance = BABYLON.Vector3.Distance(minimum, maximum);
- this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
- this.radius = distance * 0.5;
- this.centerWorld = BABYLON.Vector3.Zero();
- this._update(BABYLON.Matrix.Identity());
- }
- // Methods
- BoundingSphere.prototype._update = function (world) {
- BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
- BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
- this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
- };
- BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
- for (var i = 0; i < 6; i++) {
- if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
- return false;
- }
- return true;
- };
- BoundingSphere.prototype.intersectsPoint = function (point) {
- var x = this.centerWorld.x - point.x;
- var y = this.centerWorld.y - point.y;
- var z = this.centerWorld.z - point.z;
- var distance = Math.sqrt((x * x) + (y * y) + (z * z));
- if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
- return false;
- return true;
- };
- // Statics
- BoundingSphere.Intersects = function (sphere0, sphere1) {
- var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
- var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
- var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
- var distance = Math.sqrt((x * x) + (y * y) + (z * z));
- if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
- return false;
- return true;
- };
- return BoundingSphere;
- })();
- BABYLON.BoundingSphere = BoundingSphere;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var BoundingBox = (function () {
- function BoundingBox(minimum, maximum) {
- this.minimum = minimum;
- this.maximum = maximum;
- this.vectors = new Array();
- this.vectorsWorld = new Array();
- // Bounding vectors
- this.vectors.push(this.minimum.clone());
- this.vectors.push(this.maximum.clone());
- this.vectors.push(this.minimum.clone());
- this.vectors[2].x = this.maximum.x;
- this.vectors.push(this.minimum.clone());
- this.vectors[3].y = this.maximum.y;
- this.vectors.push(this.minimum.clone());
- this.vectors[4].z = this.maximum.z;
- this.vectors.push(this.maximum.clone());
- this.vectors[5].z = this.minimum.z;
- this.vectors.push(this.maximum.clone());
- this.vectors[6].x = this.minimum.x;
- this.vectors.push(this.maximum.clone());
- this.vectors[7].y = this.minimum.y;
- // OBB
- this.center = this.maximum.add(this.minimum).scale(0.5);
- this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
- this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
- // World
- for (var index = 0; index < this.vectors.length; index++) {
- this.vectorsWorld[index] = BABYLON.Vector3.Zero();
- }
- this.minimumWorld = BABYLON.Vector3.Zero();
- this.maximumWorld = BABYLON.Vector3.Zero();
- this._update(BABYLON.Matrix.Identity());
- }
- // Methods
- BoundingBox.prototype.getWorldMatrix = function () {
- return this._worldMatrix;
- };
- BoundingBox.prototype.setWorldMatrix = function (matrix) {
- this._worldMatrix.copyFrom(matrix);
- return this;
- };
- BoundingBox.prototype._update = function (world) {
- BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
- BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
- for (var index = 0; index < this.vectors.length; index++) {
- var v = this.vectorsWorld[index];
- BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
- if (v.x < this.minimumWorld.x)
- this.minimumWorld.x = v.x;
- if (v.y < this.minimumWorld.y)
- this.minimumWorld.y = v.y;
- if (v.z < this.minimumWorld.z)
- this.minimumWorld.z = v.z;
- if (v.x > this.maximumWorld.x)
- this.maximumWorld.x = v.x;
- if (v.y > this.maximumWorld.y)
- this.maximumWorld.y = v.y;
- if (v.z > this.maximumWorld.z)
- this.maximumWorld.z = v.z;
- }
- // OBB
- this.maximumWorld.addToRef(this.minimumWorld, this.center);
- this.center.scaleInPlace(0.5);
- BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
- BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
- BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
- this._worldMatrix = world;
- };
- BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
- return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
- };
- BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
- return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
- };
- BoundingBox.prototype.intersectsPoint = function (point) {
- var delta = -BABYLON.Epsilon;
- if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
- return false;
- if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
- return false;
- if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
- return false;
- return true;
- };
- BoundingBox.prototype.intersectsSphere = function (sphere) {
- return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
- };
- BoundingBox.prototype.intersectsMinMax = function (min, max) {
- if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
- return false;
- if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
- return false;
- if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
- return false;
- return true;
- };
- // Statics
- BoundingBox.Intersects = function (box0, box1) {
- if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
- return false;
- if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
- return false;
- if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
- return false;
- return true;
- };
- BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
- var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
- var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
- return (num <= (sphereRadius * sphereRadius));
- };
- BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
- for (var p = 0; p < 6; p++) {
- for (var i = 0; i < 8; i++) {
- if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
- return false;
- }
- }
- }
- return true;
- };
- BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
- for (var p = 0; p < 6; p++) {
- var inCount = 8;
- for (var i = 0; i < 8; i++) {
- if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
- --inCount;
- }
- else {
- break;
- }
- }
- if (inCount === 0)
- return false;
- }
- return true;
- };
- return BoundingBox;
- })();
- BABYLON.BoundingBox = BoundingBox;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var computeBoxExtents = function (axis, box) {
- var p = BABYLON.Vector3.Dot(box.center, axis);
- var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
- var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
- var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
- var r = r0 + r1 + r2;
- return {
- min: p - r,
- max: p + r
- };
- };
- var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
- var axisOverlap = function (axis, box0, box1) {
- var result0 = computeBoxExtents(axis, box0);
- var result1 = computeBoxExtents(axis, box1);
- return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
- };
- var BoundingInfo = (function () {
- function BoundingInfo(minimum, maximum) {
- this.minimum = minimum;
- this.maximum = maximum;
- this._isLocked = false;
- this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
- this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
- }
- Object.defineProperty(BoundingInfo.prototype, "isLocked", {
- get: function () {
- return this._isLocked;
- },
- set: function (value) {
- this._isLocked = value;
- },
- enumerable: true,
- configurable: true
- });
- // Methods
- BoundingInfo.prototype.update = function (world) {
- if (this._isLocked) {
- return;
- }
- this.boundingBox._update(world);
- this.boundingSphere._update(world);
- };
- BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
- if (!this.boundingSphere.isInFrustum(frustumPlanes))
- return false;
- return this.boundingBox.isInFrustum(frustumPlanes);
- };
- BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
- return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
- };
- BoundingInfo.prototype._checkCollision = function (collider) {
- return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
- };
- BoundingInfo.prototype.intersectsPoint = function (point) {
- if (!this.boundingSphere.centerWorld) {
- return false;
- }
- if (!this.boundingSphere.intersectsPoint(point)) {
- return false;
- }
- if (!this.boundingBox.intersectsPoint(point)) {
- return false;
- }
- return true;
- };
- BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
- if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
- return false;
- }
- if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
- return false;
- }
- if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
- return false;
- }
- if (!precise) {
- return true;
- }
- var box0 = this.boundingBox;
- var box1 = boundingInfo.boundingBox;
- if (!axisOverlap(box0.directions[0], box0, box1))
- return false;
- if (!axisOverlap(box0.directions[1], box0, box1))
- return false;
- if (!axisOverlap(box0.directions[2], box0, box1))
- return false;
- if (!axisOverlap(box1.directions[0], box0, box1))
- return false;
- if (!axisOverlap(box1.directions[1], box0, box1))
- return false;
- if (!axisOverlap(box1.directions[2], box0, box1))
- return false;
- if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
- return false;
- if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
- return false;
- if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
- return false;
- if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
- return false;
- if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
- return false;
- if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
- return false;
- if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
- return false;
- if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
- return false;
- if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
- return false;
- return true;
- };
- return BoundingInfo;
- })();
- BABYLON.BoundingInfo = BoundingInfo;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Ray = (function () {
- function Ray(origin, direction, length) {
- if (length === void 0) { length = Number.MAX_VALUE; }
- this.origin = origin;
- this.direction = direction;
- this.length = length;
- }
- // Methods
- Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
- var d = 0.0;
- var maxValue = Number.MAX_VALUE;
- var inv;
- var min;
- var max;
- var temp;
- if (Math.abs(this.direction.x) < 0.0000001) {
- if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
- return false;
- }
- }
- else {
- inv = 1.0 / this.direction.x;
- min = (minimum.x - this.origin.x) * inv;
- max = (maximum.x - this.origin.x) * inv;
- if (max === -Infinity) {
- max = Infinity;
- }
- if (min > max) {
- temp = min;
- min = max;
- max = temp;
- }
- d = Math.max(min, d);
- maxValue = Math.min(max, maxValue);
- if (d > maxValue) {
- return false;
- }
- }
- if (Math.abs(this.direction.y) < 0.0000001) {
- if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
- return false;
- }
- }
- else {
- inv = 1.0 / this.direction.y;
- min = (minimum.y - this.origin.y) * inv;
- max = (maximum.y - this.origin.y) * inv;
- if (max === -Infinity) {
- max = Infinity;
- }
- if (min > max) {
- temp = min;
- min = max;
- max = temp;
- }
- d = Math.max(min, d);
- maxValue = Math.min(max, maxValue);
- if (d > maxValue) {
- return false;
- }
- }
- if (Math.abs(this.direction.z) < 0.0000001) {
- if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
- return false;
- }
- }
- else {
- inv = 1.0 / this.direction.z;
- min = (minimum.z - this.origin.z) * inv;
- max = (maximum.z - this.origin.z) * inv;
- if (max === -Infinity) {
- max = Infinity;
- }
- if (min > max) {
- temp = min;
- min = max;
- max = temp;
- }
- d = Math.max(min, d);
- maxValue = Math.min(max, maxValue);
- if (d > maxValue) {
- return false;
- }
- }
- return true;
- };
- Ray.prototype.intersectsBox = function (box) {
- return this.intersectsBoxMinMax(box.minimum, box.maximum);
- };
- Ray.prototype.intersectsSphere = function (sphere) {
- var x = sphere.center.x - this.origin.x;
- var y = sphere.center.y - this.origin.y;
- var z = sphere.center.z - this.origin.z;
- var pyth = (x * x) + (y * y) + (z * z);
- var rr = sphere.radius * sphere.radius;
- if (pyth <= rr) {
- return true;
- }
- var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
- if (dot < 0.0) {
- return false;
- }
- var temp = pyth - (dot * dot);
- return temp <= rr;
- };
- Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
- if (!this._edge1) {
- this._edge1 = BABYLON.Vector3.Zero();
- this._edge2 = BABYLON.Vector3.Zero();
- this._pvec = BABYLON.Vector3.Zero();
- this._tvec = BABYLON.Vector3.Zero();
- this._qvec = BABYLON.Vector3.Zero();
- }
- vertex1.subtractToRef(vertex0, this._edge1);
- vertex2.subtractToRef(vertex0, this._edge2);
- BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
- var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
- if (det === 0) {
- return null;
- }
- var invdet = 1 / det;
- this.origin.subtractToRef(vertex0, this._tvec);
- var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
- if (bu < 0 || bu > 1.0) {
- return null;
- }
- BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
- var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
- if (bv < 0 || bu + bv > 1.0) {
- return null;
- }
- //check if the distance is longer than the predefined length.
- var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
- if (distance > this.length) {
- return null;
- }
- return new BABYLON.IntersectionInfo(bu, bv, distance);
- };
- Ray.prototype.intersectsPlane = function (plane) {
- var distance;
- var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
- if (Math.abs(result1) < 9.99999997475243E-07) {
- return null;
- }
- else {
- var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
- distance = (-plane.d - result2) / result1;
- if (distance < 0.0) {
- if (distance < -9.99999997475243E-07) {
- return null;
- }
- else {
- return 0;
- }
- }
- return distance;
- }
- };
- /**
- * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
- * @param sega the first point of the segment to test the intersection against
- * @param segb the second point of the segment to test the intersection against
- * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
- * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
- */
- Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
- var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
- var u = segb.subtract(sega);
- var v = rsegb.subtract(this.origin);
- var w = sega.subtract(this.origin);
- var a = BABYLON.Vector3.Dot(u, u); // always >= 0
- var b = BABYLON.Vector3.Dot(u, v);
- var c = BABYLON.Vector3.Dot(v, v); // always >= 0
- var d = BABYLON.Vector3.Dot(u, w);
- var e = BABYLON.Vector3.Dot(v, w);
- var D = a * c - b * b; // always >= 0
- var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
- var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
- // compute the line parameters of the two closest points
- if (D < Ray.smallnum) {
- sN = 0.0; // force using point P0 on segment S1
- sD = 1.0; // to prevent possible division by 0.0 later
- tN = e;
- tD = c;
- }
- else {
- sN = (b * e - c * d);
- tN = (a * e - b * d);
- if (sN < 0.0) {
- sN = 0.0;
- tN = e;
- tD = c;
- }
- else if (sN > sD) {
- sN = sD;
- tN = e + b;
- tD = c;
- }
- }
- if (tN < 0.0) {
- tN = 0.0;
- // recompute sc for this edge
- if (-d < 0.0) {
- sN = 0.0;
- }
- else if (-d > a)
- sN = sD;
- else {
- sN = -d;
- sD = a;
- }
- }
- else if (tN > tD) {
- tN = tD;
- // recompute sc for this edge
- if ((-d + b) < 0.0) {
- sN = 0;
- }
- else if ((-d + b) > a) {
- sN = sD;
- }
- else {
- sN = (-d + b);
- sD = a;
- }
- }
- // finally do the division to get sc and tc
- sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
- tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
- // get the difference of the two closest points
- var qtc = v.multiplyByFloats(tc, tc, tc);
- var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
- var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
- if (isIntersected) {
- return qtc.length();
- }
- return -1;
- };
- // Statics
- Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
- var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
- var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
- var direction = end.subtract(start);
- direction.normalize();
- return new Ray(start, direction);
- };
- /**
- * 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
- * transformed to the given world matrix.
- * @param origin The origin point
- * @param end The end point
- * @param world a matrix to transform the ray to. Default is the identity matrix.
- */
- Ray.CreateNewFromTo = function (origin, end, world) {
- if (world === void 0) { world = BABYLON.Matrix.Identity(); }
- var direction = end.subtract(origin);
- var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
- direction.normalize();
- return Ray.Transform(new Ray(origin, direction, length), world);
- };
- Ray.Transform = function (ray, matrix) {
- var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
- var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
- newDirection.normalize();
- return new Ray(newOrigin, newDirection, ray.length);
- };
- Ray.smallnum = 0.00000001;
- Ray.rayl = 10e8;
- return Ray;
- })();
- BABYLON.Ray = Ray;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var AbstractMesh = (function (_super) {
- __extends(AbstractMesh, _super);
- // Constructor
- function AbstractMesh(name, scene) {
- var _this = this;
- _super.call(this, name, scene);
- // Events
- /**
- * An event triggered when this mesh collides with another one
- * @type {BABYLON.Observable}
- */
- this.onCollideObservable = new BABYLON.Observable();
- /**
- * An event triggered when the collision's position changes
- * @type {BABYLON.Observable}
- */
- this.onCollisionPositionChangeObservable = new BABYLON.Observable();
- /**
- * An event triggered after the world matrix is updated
- * @type {BABYLON.Observable}
- */
- this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
- // Properties
- this.definedFacingForward = true; // orientation for POV movement & rotation
- this.position = new BABYLON.Vector3(0, 0, 0);
- this._rotation = new BABYLON.Vector3(0, 0, 0);
- this._scaling = new BABYLON.Vector3(1, 1, 1);
- this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
- this.visibility = 1.0;
- this.alphaIndex = Number.MAX_VALUE;
- this.infiniteDistance = false;
- this.isVisible = true;
- this.isPickable = true;
- this.showBoundingBox = false;
- this.showSubMeshesBoundingBox = false;
- this.onDispose = null;
- this.isBlocker = false;
- this.renderingGroupId = 0;
- this.receiveShadows = false;
- this.renderOutline = false;
- this.outlineColor = BABYLON.Color3.Red();
- this.outlineWidth = 0.02;
- this.renderOverlay = false;
- this.overlayColor = BABYLON.Color3.Red();
- this.overlayAlpha = 0.5;
- this.hasVertexAlpha = false;
- this.useVertexColors = true;
- this.applyFog = true;
- this.computeBonesUsingShaders = true;
- this.scalingDeterminant = 1;
- this.numBoneInfluencers = 4;
- this.useOctreeForRenderingSelection = true;
- this.useOctreeForPicking = true;
- this.useOctreeForCollisions = true;
- this.layerMask = 0x0FFFFFFF;
- this.alwaysSelectAsActiveMesh = false;
- // Collisions
- this._checkCollisions = false;
- this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
- this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
- this._collider = new BABYLON.Collider();
- this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
- this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
- this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
- // Edges
- this.edgesWidth = 1;
- this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
- // Cache
- this._localWorld = BABYLON.Matrix.Zero();
- this._worldMatrix = BABYLON.Matrix.Zero();
- this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
- this._absolutePosition = BABYLON.Vector3.Zero();
- this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
- this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
- this._isDirty = false;
- this._pivotMatrix = BABYLON.Matrix.Identity();
- this._isDisposed = false;
- this._renderId = 0;
- this._intersectionsInProgress = new Array();
- this._isWorldMatrixFrozen = false;
- this._unIndexed = false;
- this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
- if (collidedMesh === void 0) { collidedMesh = null; }
- //TODO move this to the collision coordinator!
- if (_this.getScene().workerCollisions)
- newPosition.multiplyInPlace(_this._collider.radius);
- newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
- if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
- _this.position.addInPlace(_this._diffPositionForCollisions);
- }
- if (collidedMesh) {
- _this.onCollideObservable.notifyObservers(collidedMesh);
- }
- _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
- };
- scene.addMesh(this);
- }
- Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
- get: function () {
- return AbstractMesh._BILLBOARDMODE_NONE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
- get: function () {
- return AbstractMesh._BILLBOARDMODE_X;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
- get: function () {
- return AbstractMesh._BILLBOARDMODE_Y;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
- get: function () {
- return AbstractMesh._BILLBOARDMODE_Z;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
- get: function () {
- return AbstractMesh._BILLBOARDMODE_ALL;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh.prototype, "onCollide", {
- set: function (callback) {
- if (this._onCollideObserver) {
- this.onCollideObservable.remove(this._onCollideObserver);
- }
- this._onCollideObserver = this.onCollideObservable.add(callback);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
- set: function (callback) {
- if (this._onCollisionPositionChangeObserver) {
- this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
- }
- this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh.prototype, "skeleton", {
- get: function () {
- return this._skeleton;
- },
- set: function (value) {
- if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
- this._skeleton._unregisterMeshWithPoseMatrix(this);
- }
- if (value && value.needInitialSkinMatrix) {
- value._registerMeshWithPoseMatrix(this);
- }
- this._skeleton = value;
- if (!this._skeleton) {
- this._bonesTransformMatrices = null;
- }
- },
- enumerable: true,
- configurable: true
- });
- /**
- * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
- */
- AbstractMesh.prototype.toString = function (fullDetails) {
- var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
- ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
- if (this._skeleton) {
- ret += ", skeleton: " + this._skeleton.name;
- }
- if (fullDetails) {
- ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
- ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
- }
- return ret;
- };
- Object.defineProperty(AbstractMesh.prototype, "rotation", {
- /**
- * Getting the rotation object.
- * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
- */
- get: function () {
- return this._rotation;
- },
- set: function (newRotation) {
- this._rotation = newRotation;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh.prototype, "scaling", {
- get: function () {
- return this._scaling;
- },
- set: function (newScaling) {
- this._scaling = newScaling;
- if (this.physicsImpostor) {
- this.physicsImpostor.forceUpdate();
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
- get: function () {
- return this._rotationQuaternion;
- },
- set: function (quaternion) {
- this._rotationQuaternion = quaternion;
- //reset the rotation vector.
- if (quaternion && this.rotation.length()) {
- this.rotation.copyFromFloats(0, 0, 0);
- }
- },
- enumerable: true,
- configurable: true
- });
- // Methods
- AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
- this._poseMatrix.copyFrom(matrix);
- };
- AbstractMesh.prototype.getPoseMatrix = function () {
- return this._poseMatrix;
- };
- AbstractMesh.prototype.disableEdgesRendering = function () {
- if (this._edgesRenderer !== undefined) {
- this._edgesRenderer.dispose();
- this._edgesRenderer = undefined;
- }
- };
- AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
- if (epsilon === void 0) { epsilon = 0.95; }
- if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
- this.disableEdgesRendering();
- this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
- };
- Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
- get: function () {
- return false;
- },
- enumerable: true,
- configurable: true
- });
- AbstractMesh.prototype.getLOD = function (camera) {
- return this;
- };
- AbstractMesh.prototype.getTotalVertices = function () {
- return 0;
- };
- AbstractMesh.prototype.getIndices = function () {
- return null;
- };
- AbstractMesh.prototype.getVerticesData = function (kind) {
- return null;
- };
- AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
- return false;
- };
- AbstractMesh.prototype.getBoundingInfo = function () {
- if (this._masterMesh) {
- return this._masterMesh.getBoundingInfo();
- }
- if (!this._boundingInfo) {
- this._updateBoundingInfo();
- }
- return this._boundingInfo;
- };
- Object.defineProperty(AbstractMesh.prototype, "useBones", {
- get: function () {
- return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
- },
- enumerable: true,
- configurable: true
- });
- AbstractMesh.prototype._preActivate = function () {
- };
- AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
- };
- AbstractMesh.prototype._activate = function (renderId) {
- this._renderId = renderId;
- };
- AbstractMesh.prototype.getWorldMatrix = function () {
- if (this._masterMesh) {
- return this._masterMesh.getWorldMatrix();
- }
- if (this._currentRenderId !== this.getScene().getRenderId()) {
- this.computeWorldMatrix();
- }
- return this._worldMatrix;
- };
- Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
- get: function () {
- return this._worldMatrix;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
- get: function () {
- return this._absolutePosition;
- },
- enumerable: true,
- configurable: true
- });
- AbstractMesh.prototype.freezeWorldMatrix = function () {
- this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
- this.computeWorldMatrix(true);
- this._isWorldMatrixFrozen = true;
- };
- AbstractMesh.prototype.unfreezeWorldMatrix = function () {
- this._isWorldMatrixFrozen = false;
- this.computeWorldMatrix(true);
- };
- Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
- get: function () {
- return this._isWorldMatrixFrozen;
- },
- enumerable: true,
- configurable: true
- });
- AbstractMesh.prototype.rotate = function (axis, amount, space) {
- axis.normalize();
- if (!this.rotationQuaternion) {
- this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
- this.rotation = BABYLON.Vector3.Zero();
- }
- var rotationQuaternion;
- if (!space || space === BABYLON.Space.LOCAL) {
- rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
- this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
- }
- else {
- if (this.parent) {
- var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
- invertParentWorldMatrix.invert();
- axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
- }
- rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
- this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
- }
- };
- AbstractMesh.prototype.translate = function (axis, distance, space) {
- var displacementVector = axis.scale(distance);
- if (!space || space === BABYLON.Space.LOCAL) {
- var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
- this.setPositionWithLocalVector(tempV3);
- }
- else {
- this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
- }
- };
- AbstractMesh.prototype.getAbsolutePosition = function () {
- this.computeWorldMatrix();
- return this._absolutePosition;
- };
- AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
- if (!absolutePosition) {
- return;
- }
- var absolutePositionX;
- var absolutePositionY;
- var absolutePositionZ;
- if (absolutePosition.x === undefined) {
- if (arguments.length < 3) {
- return;
- }
- absolutePositionX = arguments[0];
- absolutePositionY = arguments[1];
- absolutePositionZ = arguments[2];
- }
- else {
- absolutePositionX = absolutePosition.x;
- absolutePositionY = absolutePosition.y;
- absolutePositionZ = absolutePosition.z;
- }
- if (this.parent) {
- var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
- invertParentWorldMatrix.invert();
- var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
- this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
- }
- else {
- this.position.x = absolutePositionX;
- this.position.y = absolutePositionY;
- this.position.z = absolutePositionZ;
- }
- };
- // ================================== Point of View Movement =================================
- /**
- * Perform relative position change from the point of view of behind the front of the mesh.
- * This is performed taking into account the meshes current rotation, so you do not have to care.
- * Supports definition of mesh facing forward or backward.
- * @param {number} amountRight
- * @param {number} amountUp
- * @param {number} amountForward
- */
- AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
- this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
- };
- /**
- * Calculate relative position change from the point of view of behind the front of the mesh.
- * This is performed taking into account the meshes current rotation, so you do not have to care.
- * Supports definition of mesh facing forward or backward.
- * @param {number} amountRight
- * @param {number} amountUp
- * @param {number} amountForward
- */
- AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
- var rotMatrix = new BABYLON.Matrix();
- var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
- rotQuaternion.toRotationMatrix(rotMatrix);
- var translationDelta = BABYLON.Vector3.Zero();
- var defForwardMult = this.definedFacingForward ? -1 : 1;
- BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
- return translationDelta;
- };
- // ================================== Point of View Rotation =================================
- /**
- * Perform relative rotation change from the point of view of behind the front of the mesh.
- * Supports definition of mesh facing forward or backward.
- * @param {number} flipBack
- * @param {number} twirlClockwise
- * @param {number} tiltRight
- */
- AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
- this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
- };
- /**
- * Calculate relative rotation change from the point of view of behind the front of the mesh.
- * Supports definition of mesh facing forward or backward.
- * @param {number} flipBack
- * @param {number} twirlClockwise
- * @param {number} tiltRight
- */
- AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
- var defForwardMult = this.definedFacingForward ? 1 : -1;
- return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
- };
- AbstractMesh.prototype.setPivotMatrix = function (matrix) {
- this._pivotMatrix = matrix;
- this._cache.pivotMatrixUpdated = true;
- };
- AbstractMesh.prototype.getPivotMatrix = function () {
- return this._pivotMatrix;
- };
- AbstractMesh.prototype._isSynchronized = function () {
- if (this._isDirty) {
- return false;
- }
- if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
- return false;
- if (this._cache.pivotMatrixUpdated) {
- return false;
- }
- if (this.infiniteDistance) {
- return false;
- }
- if (!this._cache.position.equals(this.position))
- return false;
- if (this.rotationQuaternion) {
- if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
- return false;
- }
- else {
- if (!this._cache.rotation.equals(this.rotation))
- return false;
- }
- if (!this._cache.scaling.equals(this.scaling))
- return false;
- return true;
- };
- AbstractMesh.prototype._initCache = function () {
- _super.prototype._initCache.call(this);
- this._cache.localMatrixUpdated = false;
- this._cache.position = BABYLON.Vector3.Zero();
- this._cache.scaling = BABYLON.Vector3.Zero();
- this._cache.rotation = BABYLON.Vector3.Zero();
- this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
- this._cache.billboardMode = -1;
- };
- AbstractMesh.prototype.markAsDirty = function (property) {
- if (property === "rotation") {
- this.rotationQuaternion = null;
- }
- this._currentRenderId = Number.MAX_VALUE;
- this._isDirty = true;
- };
- AbstractMesh.prototype._updateBoundingInfo = function () {
- this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
- this._boundingInfo.update(this.worldMatrixFromCache);
- this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
- };
- AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
- if (!this.subMeshes) {
- return;
- }
- for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
- var subMesh = this.subMeshes[subIndex];
- if (!subMesh.IsGlobal) {
- subMesh.updateBoundingInfo(matrix);
- }
- }
- };
- AbstractMesh.prototype.computeWorldMatrix = function (force) {
- if (this._isWorldMatrixFrozen) {
- return this._worldMatrix;
- }
- if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
- this._currentRenderId = this.getScene().getRenderId();
- return this._worldMatrix;
- }
- this._cache.position.copyFrom(this.position);
- this._cache.scaling.copyFrom(this.scaling);
- this._cache.pivotMatrixUpdated = false;
- this._cache.billboardMode = this.billboardMode;
- this._currentRenderId = this.getScene().getRenderId();
- this._isDirty = false;
- // Scaling
- BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
- // Rotation
- //rotate, if quaternion is set and rotation was used
- if (this.rotationQuaternion) {
- var len = this.rotation.length();
- if (len) {
- this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
- this.rotation.copyFromFloats(0, 0, 0);
- }
- }
- if (this.rotationQuaternion) {
- this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
- this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
- }
- else {
- BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
- this._cache.rotation.copyFrom(this.rotation);
- }
- // Translation
- if (this.infiniteDistance && !this.parent) {
- var camera = this.getScene().activeCamera;
- if (camera) {
- var cameraWorldMatrix = camera.getWorldMatrix();
- var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
- BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
- }
- }
- else {
- BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
- }
- // Composing transformations
- this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
- BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
- // Billboarding
- if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
- BABYLON.Tmp.Vector3[0].copyFrom(this.position);
- var localPosition = BABYLON.Tmp.Vector3[0];
- if (this.parent && this.parent.getWorldMatrix) {
- this._markSyncedWithParent();
- var parentMatrix;
- if (this._meshToBoneReferal) {
- this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
- parentMatrix = BABYLON.Tmp.Matrix[6];
- }
- else {
- parentMatrix = this.parent.getWorldMatrix();
- }
- BABYLON.Vector3.TransformCoordinatesToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
- localPosition = BABYLON.Tmp.Vector3[1];
- }
- var zero = this.getScene().activeCamera.globalPosition.clone();
- if (this.parent && this.parent.position) {
- localPosition.addInPlace(this.parent.position);
- BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
- }
- if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
- if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
- zero.x = localPosition.x + BABYLON.Epsilon;
- if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
- zero.y = localPosition.y + BABYLON.Epsilon;
- if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
- zero.z = localPosition.z + BABYLON.Epsilon;
- }
- BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
- BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
- BABYLON.Tmp.Matrix[3].invert();
- BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
- this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
- }
- // Local world
- BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
- // Parent
- if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
- this._markSyncedWithParent();
- if (this._meshToBoneReferal) {
- this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
- BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
- }
- else {
- this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
- }
- }
- else {
- this._worldMatrix.copyFrom(this._localWorld);
- }
- // Bounding info
- this._updateBoundingInfo();
- // Absolute position
- this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
- // Callbacks
- this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
- if (!this._poseMatrix) {
- this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
- }
- return this._worldMatrix;
- };
- /**
- * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
- * @param func: callback function to add
- */
- AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
- this.onAfterWorldMatrixUpdateObservable.add(func);
- };
- AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
- this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
- };
- AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
- this.computeWorldMatrix();
- this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
- };
- AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
- this.computeWorldMatrix();
- var invLocalWorldMatrix = this._localWorld.clone();
- invLocalWorldMatrix.invert();
- return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
- };
- AbstractMesh.prototype.locallyTranslate = function (vector3) {
- this.computeWorldMatrix(true);
- this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
- };
- AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
- /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
- /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
- /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
- /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
- /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
- /// <returns>Mesh oriented towards targetMesh</returns>
- yawCor = yawCor || 0; // default to zero if undefined
- pitchCor = pitchCor || 0;
- rollCor = rollCor || 0;
- var dv = targetPoint.subtract(this.position);
- var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
- var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
- var pitch = Math.atan2(dv.y, len);
- this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
- };
- AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
- this._meshToBoneReferal = affectedMesh;
- this.parent = bone;
- if (bone.getWorldMatrix().determinant() < 0) {
- this.scalingDeterminant *= -1;
- }
- };
- AbstractMesh.prototype.detachFromBone = function () {
- if (this.parent.getWorldMatrix().determinant() < 0) {
- this.scalingDeterminant *= -1;
- }
- this._meshToBoneReferal = null;
- this.parent = null;
- };
- AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
- return this._boundingInfo.isInFrustum(frustumPlanes);
- };
- AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
- if (!camera) {
- camera = this.getScene().activeCamera;
- }
- var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
- if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
- return false;
- }
- return true;
- };
- AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
- if (!this._boundingInfo || !mesh._boundingInfo) {
- return false;
- }
- return this._boundingInfo.intersects(mesh._boundingInfo, precise);
- };
- AbstractMesh.prototype.intersectsPoint = function (point) {
- if (!this._boundingInfo) {
- return false;
- }
- return this._boundingInfo.intersectsPoint(point);
- };
- // Physics
- /**
- * @Deprecated. Use new PhysicsImpostor instead.
- * */
- AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
- //legacy support
- if (impostor.impostor) {
- options = impostor;
- impostor = impostor.impostor;
- }
- this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
- return this.physicsImpostor.physicsBody;
- };
- AbstractMesh.prototype.getPhysicsImpostor = function () {
- return this.physicsImpostor;
- };
- /**
- * @Deprecated. Use getPhysicsImpostor().getParam("mass");
- */
- AbstractMesh.prototype.getPhysicsMass = function () {
- return this.physicsImpostor.getParam("mass");
- };
- /**
- * @Deprecated. Use getPhysicsImpostor().getParam("friction");
- */
- AbstractMesh.prototype.getPhysicsFriction = function () {
- return this.physicsImpostor.getParam("friction");
- };
- /**
- * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
- */
- AbstractMesh.prototype.getPhysicsRestitution = function () {
- return this.physicsImpostor.getParam("resitution");
- };
- AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
- if (!camera) {
- camera = this.getScene().activeCamera;
- }
- return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
- };
- AbstractMesh.prototype.getDistanceToCamera = function (camera) {
- if (!camera) {
- camera = this.getScene().activeCamera;
- }
- return this.absolutePosition.subtract(camera.position).length();
- };
- AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
- if (!this.physicsImpostor) {
- return;
- }
- this.physicsImpostor.applyImpulse(force, contactPoint);
- };
- AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
- if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
- return;
- }
- this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
- mainPivot: pivot1,
- connectedPivot: pivot2,
- nativeParams: options
- });
- };
- /**
- * @Deprecated
- */
- AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
- BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
- this.updatePhysicsBody();
- };
- /**
- * @Deprecated
- * Calling this function is not needed anymore.
- * The physics engine takes care of transofmration automatically.
- */
- AbstractMesh.prototype.updatePhysicsBody = function () {
- //Unneeded
- };
- Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
- // Collisions
- get: function () {
- return this._checkCollisions;
- },
- set: function (collisionEnabled) {
- this._checkCollisions = collisionEnabled;
- if (this.getScene().workerCollisions) {
- this.getScene().collisionCoordinator.onMeshUpdated(this);
- }
- },
- enumerable: true,
- configurable: true
- });
- AbstractMesh.prototype.moveWithCollisions = function (velocity) {
- var globalPosition = this.getAbsolutePosition();
- globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
- this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
- this._collider.radius = this.ellipsoid;
- this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
- };
- // Submeshes octree
- /**
- * This function will create an octree to help select the right submeshes for rendering, picking and collisions
- * Please note that you must have a decent number of submeshes to get performance improvements when using octree
- */
- AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
- if (maxCapacity === void 0) { maxCapacity = 64; }
- if (maxDepth === void 0) { maxDepth = 2; }
- if (!this._submeshesOctree) {
- this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
- }
- this.computeWorldMatrix(true);
- // Update octree
- var bbox = this.getBoundingInfo().boundingBox;
- this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
- return this._submeshesOctree;
- };
- // Collisions
- AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
- this._generatePointsArray();
- // Transformation
- if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
- subMesh._lastColliderTransformMatrix = transformMatrix.clone();
- subMesh._lastColliderWorldVertices = [];
- subMesh._trianglePlanes = [];
- var start = subMesh.verticesStart;
- var end = (subMesh.verticesStart + subMesh.verticesCount);
- for (var i = start; i < end; i++) {
- subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
- }
- }
- // Collide
- collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
- if (collider.collisionFound) {
- collider.collidedMesh = this;
- }
- };
- AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
- var subMeshes;
- var len;
- // Octrees
- if (this._submeshesOctree && this.useOctreeForCollisions) {
- var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
- var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
- len = intersections.length;
- subMeshes = intersections.data;
- }
- else {
- subMeshes = this.subMeshes;
- len = subMeshes.length;
- }
- for (var index = 0; index < len; index++) {
- var subMesh = subMeshes[index];
- // Bounding test
- if (len > 1 && !subMesh._checkCollision(collider))
- continue;
- this._collideForSubMesh(subMesh, transformMatrix, collider);
- }
- };
- AbstractMesh.prototype._checkCollision = function (collider) {
- // Bounding box test
- if (!this._boundingInfo._checkCollision(collider))
- return;
- // Transformation matrix
- BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
- this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
- this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
- };
- // Picking
- AbstractMesh.prototype._generatePointsArray = function () {
- return false;
- };
- AbstractMesh.prototype.intersects = function (ray, fastCheck) {
- var pickingInfo = new BABYLON.PickingInfo();
- if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
- return pickingInfo;
- }
- if (!this._generatePointsArray()) {
- return pickingInfo;
- }
- var intersectInfo = null;
- // Octrees
- var subMeshes;
- var len;
- if (this._submeshesOctree && this.useOctreeForPicking) {
- var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
- var intersections = this._submeshesOctree.intersectsRay(worldRay);
- len = intersections.length;
- subMeshes = intersections.data;
- }
- else {
- subMeshes = this.subMeshes;
- len = subMeshes.length;
- }
- for (var index = 0; index < len; index++) {
- var subMesh = subMeshes[index];
- // Bounding test
- if (len > 1 && !subMesh.canIntersects(ray))
- continue;
- var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
- if (currentIntersectInfo) {
- if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
- intersectInfo = currentIntersectInfo;
- intersectInfo.subMeshId = index;
- if (fastCheck) {
- break;
- }
- }
- }
- }
- if (intersectInfo) {
- // Get picked point
- var world = this.getWorldMatrix();
- var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
- var direction = ray.direction.clone();
- direction = direction.scale(intersectInfo.distance);
- var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
- var pickedPoint = worldOrigin.add(worldDirection);
- // Return result
- pickingInfo.hit = true;
- pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
- pickingInfo.pickedPoint = pickedPoint;
- pickingInfo.pickedMesh = this;
- pickingInfo.bu = intersectInfo.bu;
- pickingInfo.bv = intersectInfo.bv;
- pickingInfo.faceId = intersectInfo.faceId;
- pickingInfo.subMeshId = intersectInfo.subMeshId;
- return pickingInfo;
- }
- return pickingInfo;
- };
- AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
- return null;
- };
- AbstractMesh.prototype.releaseSubMeshes = function () {
- if (this.subMeshes) {
- while (this.subMeshes.length) {
- this.subMeshes[0].dispose();
- }
- }
- else {
- this.subMeshes = new Array();
- }
- };
- AbstractMesh.prototype.dispose = function (doNotRecurse) {
- var _this = this;
- var index;
- // Action manager
- if (this.actionManager) {
- this.actionManager.dispose();
- this.actionManager = null;
- }
- // Skeleton
- this.skeleton = null;
- // Animations
- this.getScene().stopAnimation(this);
- // Physics
- if (this.physicsImpostor) {
- this.physicsImpostor.dispose();
- }
- // Intersections in progress
- for (index = 0; index < this._intersectionsInProgress.length; index++) {
- var other = this._intersectionsInProgress[index];
- var pos = other._intersectionsInProgress.indexOf(this);
- other._intersectionsInProgress.splice(pos, 1);
- }
- this._intersectionsInProgress = [];
- // Lights
- var lights = this.getScene().lights;
- lights.forEach(function (light) {
- var meshIndex = light.includedOnlyMeshes.indexOf(_this);
- if (meshIndex !== -1) {
- light.includedOnlyMeshes.splice(meshIndex, 1);
- }
- meshIndex = light.excludedMeshes.indexOf(_this);
- if (meshIndex !== -1) {
- light.excludedMeshes.splice(meshIndex, 1);
- }
- });
- // Edges
- if (this._edgesRenderer) {
- this._edgesRenderer.dispose();
- this._edgesRenderer = null;
- }
- // SubMeshes
- this.releaseSubMeshes();
- // Remove from scene
- this.getScene().removeMesh(this);
- if (!doNotRecurse) {
- // Particles
- for (index = 0; index < this.getScene().particleSystems.length; index++) {
- if (this.getScene().particleSystems[index].emitter === this) {
- this.getScene().particleSystems[index].dispose();
- index--;
- }
- }
- // Children
- var objects = this.getDescendants(true);
- for (index = 0; index < objects.length; index++) {
- objects[index].dispose();
- }
- }
- else {
- var childMeshes = this.getChildMeshes(true);
- for (index = 0; index < childMeshes.length; index++) {
- var child = childMeshes[index];
- child.parent = null;
- child.computeWorldMatrix(true);
- }
- }
- _super.prototype.dispose.call(this);
- this.onAfterWorldMatrixUpdateObservable.clear();
- this._isDisposed = true;
- // Callback
- if (this.onDispose) {
- this.onDispose();
- }
- };
- // Statics
- AbstractMesh._BILLBOARDMODE_NONE = 0;
- AbstractMesh._BILLBOARDMODE_X = 1;
- AbstractMesh._BILLBOARDMODE_Y = 2;
- AbstractMesh._BILLBOARDMODE_Z = 4;
- AbstractMesh._BILLBOARDMODE_ALL = 7;
- return AbstractMesh;
- })(BABYLON.Node);
- BABYLON.AbstractMesh = AbstractMesh;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Light = (function (_super) {
- __extends(Light, _super);
- function Light(name, scene) {
- _super.call(this, name, scene);
- this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
- this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
- this.intensity = 1.0;
- this.range = Number.MAX_VALUE;
- this.includeOnlyWithLayerMask = 0;
- this.includedOnlyMeshes = new Array();
- this.excludedMeshes = new Array();
- this.excludeWithLayerMask = 0;
- // PBR Properties.
- this.radius = 0.00001;
- this._excludedMeshesIds = new Array();
- this._includedOnlyMeshesIds = new Array();
- scene.addLight(this);
- }
- /**
- * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
- */
- Light.prototype.toString = function (fullDetails) {
- var ret = "Name: " + this.name;
- ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
- if (this.animations) {
- for (var i = 0; i < this.animations.length; i++) {
- ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
- }
- }
- if (fullDetails) {
- }
- return ret;
- };
- Light.prototype.getShadowGenerator = function () {
- return this._shadowGenerator;
- };
- Light.prototype.getAbsolutePosition = function () {
- return BABYLON.Vector3.Zero();
- };
- Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
- };
- Light.prototype._getWorldMatrix = function () {
- return BABYLON.Matrix.Identity();
- };
- Light.prototype.canAffectMesh = function (mesh) {
- if (!mesh) {
- return true;
- }
- if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
- return false;
- }
- if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
- return false;
- }
- if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
- return false;
- }
- if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
- return false;
- }
- return true;
- };
- Light.prototype.getWorldMatrix = function () {
- this._currentRenderId = this.getScene().getRenderId();
- var worldMatrix = this._getWorldMatrix();
- if (this.parent && this.parent.getWorldMatrix) {
- if (!this._parentedWorldMatrix) {
- this._parentedWorldMatrix = BABYLON.Matrix.Identity();
- }
- worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
- this._markSyncedWithParent();
- return this._parentedWorldMatrix;
- }
- return worldMatrix;
- };
- Light.prototype.dispose = function () {
- if (this._shadowGenerator) {
- this._shadowGenerator.dispose();
- this._shadowGenerator = null;
- }
- // Animations
- this.getScene().stopAnimation(this);
- // Remove from scene
- this.getScene().removeLight(this);
- _super.prototype.dispose.call(this);
- };
- Light.prototype.getTypeID = function () {
- return 0;
- };
- Light.prototype.clone = function (name) {
- return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
- };
- Light.prototype.serialize = function () {
- var serializationObject = BABYLON.SerializationHelper.Serialize(this);
- // Type
- serializationObject.type = this.getTypeID();
- // Parent
- if (this.parent) {
- serializationObject.parentId = this.parent.id;
- }
- // Inclusion / exclusions
- if (this.excludedMeshes.length > 0) {
- serializationObject.excludedMeshesIds = [];
- this.excludedMeshes.forEach(function (mesh) {
- serializationObject.excludedMeshesIds.push(mesh.id);
- });
- }
- if (this.includedOnlyMeshes.length > 0) {
- serializationObject.includedOnlyMeshesIds = [];
- this.includedOnlyMeshes.forEach(function (mesh) {
- serializationObject.includedOnlyMeshesIds.push(mesh.id);
- });
- }
- // Animations
- BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
- serializationObject.ranges = this.serializeAnimationRanges();
- return serializationObject;
- };
- Light.GetConstructorFromName = function (type, name, scene) {
- switch (type) {
- case 0:
- return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
- case 1:
- return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
- case 2:
- return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
- case 3:
- return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
- }
- };
- Light.Parse = function (parsedLight, scene) {
- var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
- // Inclusion / exclusions
- if (parsedLight.excludedMeshesIds) {
- light._excludedMeshesIds = parsedLight.excludedMeshesIds;
- }
- if (parsedLight.includedOnlyMeshesIds) {
- light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
- }
- // Parent
- if (parsedLight.parentId) {
- light._waitingParentId = parsedLight.parentId;
- }
- // Animations
- if (parsedLight.animations) {
- for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
- var parsedAnimation = parsedLight.animations[animationIndex];
- light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
- }
- BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
- }
- if (parsedLight.autoAnimate) {
- scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
- }
- return light;
- };
- __decorate([
- BABYLON.serializeAsColor3()
- ], Light.prototype, "diffuse", void 0);
- __decorate([
- BABYLON.serializeAsColor3()
- ], Light.prototype, "specular", void 0);
- __decorate([
- BABYLON.serialize()
- ], Light.prototype, "intensity", void 0);
- __decorate([
- BABYLON.serialize()
- ], Light.prototype, "range", void 0);
- __decorate([
- BABYLON.serialize()
- ], Light.prototype, "includeOnlyWithLayerMask", void 0);
- __decorate([
- BABYLON.serialize()
- ], Light.prototype, "excludeWithLayerMask", void 0);
- __decorate([
- BABYLON.serialize()
- ], Light.prototype, "radius", void 0);
- return Light;
- })(BABYLON.Node);
- BABYLON.Light = Light;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var PointLight = (function (_super) {
- __extends(PointLight, _super);
- function PointLight(name, position, scene) {
- _super.call(this, name, scene);
- this.position = position;
- }
- PointLight.prototype.getAbsolutePosition = function () {
- return this.transformedPosition ? this.transformedPosition : this.position;
- };
- PointLight.prototype.computeTransformedPosition = function () {
- if (this.parent && this.parent.getWorldMatrix) {
- if (!this.transformedPosition) {
- this.transformedPosition = BABYLON.Vector3.Zero();
- }
- BABYLON.Vector3.TransformCoordinatesToRef(this.getAbsolutePosition(), this.parent.getWorldMatrix(), this.transformedPosition);
- return true;
- }
- return false;
- };
- PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
- if (this.parent && this.parent.getWorldMatrix) {
- this.computeTransformedPosition();
- effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
- return;
- }
- effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
- };
- PointLight.prototype.needCube = function () {
- return true;
- };
- PointLight.prototype.supportsVSM = function () {
- return false;
- };
- PointLight.prototype.needRefreshPerFrame = function () {
- return false;
- };
- PointLight.prototype.getShadowDirection = function (faceIndex) {
- switch (faceIndex) {
- case 0:
- return new BABYLON.Vector3(1, 0, 0);
- case 1:
- return new BABYLON.Vector3(-1, 0, 0);
- case 2:
- return new BABYLON.Vector3(0, -1, 0);
- case 3:
- return new BABYLON.Vector3(0, 1, 0);
- case 4:
- return new BABYLON.Vector3(0, 0, 1);
- case 5:
- return new BABYLON.Vector3(0, 0, -1);
- }
- return BABYLON.Vector3.Zero();
- };
- PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
- var activeCamera = this.getScene().activeCamera;
- BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
- };
- PointLight.prototype._getWorldMatrix = function () {
- if (!this._worldMatrix) {
- this._worldMatrix = BABYLON.Matrix.Identity();
- }
- BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
- return this._worldMatrix;
- };
- PointLight.prototype.getTypeID = function () {
- return 0;
- };
- __decorate([
- BABYLON.serializeAsVector3()
- ], PointLight.prototype, "position", void 0);
- return PointLight;
- })(BABYLON.Light);
- BABYLON.PointLight = PointLight;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var SpotLight = (function (_super) {
- __extends(SpotLight, _super);
- function SpotLight(name, position, direction, angle, exponent, scene) {
- _super.call(this, name, scene);
- this.position = position;
- this.direction = direction;
- this.angle = angle;
- this.exponent = exponent;
- }
- SpotLight.prototype.getAbsolutePosition = function () {
- return this.transformedPosition ? this.transformedPosition : this.position;
- };
- SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
- var activeCamera = this.getScene().activeCamera;
- BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
- };
- SpotLight.prototype.needCube = function () {
- return false;
- };
- SpotLight.prototype.supportsVSM = function () {
- return true;
- };
- SpotLight.prototype.needRefreshPerFrame = function () {
- return false;
- };
- SpotLight.prototype.getShadowDirection = function (faceIndex) {
- return this.direction;
- };
- SpotLight.prototype.setDirectionToTarget = function (target) {
- this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
- return this.direction;
- };
- SpotLight.prototype.computeTransformedPosition = function () {
- if (this.parent && this.parent.getWorldMatrix) {
- if (!this.transformedPosition) {
- this.transformedPosition = BABYLON.Vector3.Zero();
- }
- BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
- return true;
- }
- return false;
- };
- SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
- var normalizeDirection;
- if (this.parent && this.parent.getWorldMatrix) {
- if (!this._transformedDirection) {
- this._transformedDirection = BABYLON.Vector3.Zero();
- }
- this.computeTransformedPosition();
- BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
- effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
- normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
- }
- else {
- effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
- normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
- }
- effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
- };
- SpotLight.prototype._getWorldMatrix = function () {
- if (!this._worldMatrix) {
- this._worldMatrix = BABYLON.Matrix.Identity();
- }
- BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
- return this._worldMatrix;
- };
- SpotLight.prototype.getTypeID = function () {
- return 2;
- };
- __decorate([
- BABYLON.serializeAsVector3()
- ], SpotLight.prototype, "position", void 0);
- __decorate([
- BABYLON.serializeAsVector3()
- ], SpotLight.prototype, "direction", void 0);
- __decorate([
- BABYLON.serialize()
- ], SpotLight.prototype, "angle", void 0);
- __decorate([
- BABYLON.serialize()
- ], SpotLight.prototype, "exponent", void 0);
- return SpotLight;
- })(BABYLON.Light);
- BABYLON.SpotLight = SpotLight;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var HemisphericLight = (function (_super) {
- __extends(HemisphericLight, _super);
- function HemisphericLight(name, direction, scene) {
- _super.call(this, name, scene);
- this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
- this.direction = direction;
- }
- HemisphericLight.prototype.setDirectionToTarget = function (target) {
- this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
- return this.direction;
- };
- HemisphericLight.prototype.getShadowGenerator = function () {
- return null;
- };
- HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
- var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
- effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
- effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
- };
- HemisphericLight.prototype._getWorldMatrix = function () {
- if (!this._worldMatrix) {
- this._worldMatrix = BABYLON.Matrix.Identity();
- }
- return this._worldMatrix;
- };
- HemisphericLight.prototype.getTypeID = function () {
- return 3;
- };
- __decorate([
- BABYLON.serializeAsColor3()
- ], HemisphericLight.prototype, "groundColor", void 0);
- __decorate([
- BABYLON.serializeAsVector3()
- ], HemisphericLight.prototype, "direction", void 0);
- return HemisphericLight;
- })(BABYLON.Light);
- BABYLON.HemisphericLight = HemisphericLight;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var DirectionalLight = (function (_super) {
- __extends(DirectionalLight, _super);
- function DirectionalLight(name, direction, scene) {
- _super.call(this, name, scene);
- this.shadowOrthoScale = 0.5;
- this.autoUpdateExtends = true;
- // Cache
- this._orthoLeft = Number.MAX_VALUE;
- this._orthoRight = Number.MIN_VALUE;
- this._orthoTop = Number.MIN_VALUE;
- this._orthoBottom = Number.MAX_VALUE;
- this.position = direction.scale(-1);
- this.direction = direction;
- }
- DirectionalLight.prototype.getAbsolutePosition = function () {
- return this.transformedPosition ? this.transformedPosition : this.position;
- };
- DirectionalLight.prototype.setDirectionToTarget = function (target) {
- this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
- return this.direction;
- };
- DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
- var activeCamera = this.getScene().activeCamera;
- // Check extends
- if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
- var tempVector3 = BABYLON.Vector3.Zero();
- this._orthoLeft = Number.MAX_VALUE;
- this._orthoRight = Number.MIN_VALUE;
- this._orthoTop = Number.MIN_VALUE;
- this._orthoBottom = Number.MAX_VALUE;
- for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
- var mesh = renderList[meshIndex];
- if (!mesh) {
- continue;
- }
- var boundingInfo = mesh.getBoundingInfo();
- if (!boundingInfo) {
- continue;
- }
- var boundingBox = boundingInfo.boundingBox;
- for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
- BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
- if (tempVector3.x < this._orthoLeft)
- this._orthoLeft = tempVector3.x;
- if (tempVector3.y < this._orthoBottom)
- this._orthoBottom = tempVector3.y;
- if (tempVector3.x > this._orthoRight)
- this._orthoRight = tempVector3.x;
- if (tempVector3.y > this._orthoTop)
- this._orthoTop = tempVector3.y;
- }
- }
- }
- var xOffset = this._orthoRight - this._orthoLeft;
- var yOffset = this._orthoTop - this._orthoBottom;
- 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);
- };
- DirectionalLight.prototype.supportsVSM = function () {
- return true;
- };
- DirectionalLight.prototype.needRefreshPerFrame = function () {
- return true;
- };
- DirectionalLight.prototype.needCube = function () {
- return false;
- };
- DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
- return this.direction;
- };
- DirectionalLight.prototype.computeTransformedPosition = function () {
- if (this.parent && this.parent.getWorldMatrix) {
- if (!this.transformedPosition) {
- this.transformedPosition = BABYLON.Vector3.Zero();
- }
- BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
- return true;
- }
- return false;
- };
- DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
- if (this.parent && this.parent.getWorldMatrix) {
- if (!this._transformedDirection) {
- this._transformedDirection = BABYLON.Vector3.Zero();
- }
- BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
- effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
- return;
- }
- effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
- };
- DirectionalLight.prototype._getWorldMatrix = function () {
- if (!this._worldMatrix) {
- this._worldMatrix = BABYLON.Matrix.Identity();
- }
- BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
- return this._worldMatrix;
- };
- DirectionalLight.prototype.getTypeID = function () {
- return 1;
- };
- __decorate([
- BABYLON.serializeAsVector3()
- ], DirectionalLight.prototype, "position", void 0);
- __decorate([
- BABYLON.serializeAsVector3()
- ], DirectionalLight.prototype, "direction", void 0);
- __decorate([
- BABYLON.serialize()
- ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
- __decorate([
- BABYLON.serialize()
- ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
- return DirectionalLight;
- })(BABYLON.Light);
- BABYLON.DirectionalLight = DirectionalLight;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var ShadowGenerator = (function () {
- function ShadowGenerator(mapSize, light) {
- var _this = this;
- // Members
- this._filter = ShadowGenerator.FILTER_NONE;
- this.blurScale = 2;
- this._blurBoxOffset = 0;
- this._bias = 0.00005;
- this._lightDirection = BABYLON.Vector3.Zero();
- this.forceBackFacesOnly = false;
- this._darkness = 0;
- this._transparencyShadow = false;
- this._viewMatrix = BABYLON.Matrix.Zero();
- this._projectionMatrix = BABYLON.Matrix.Zero();
- this._transformMatrix = BABYLON.Matrix.Zero();
- this._worldViewProjection = BABYLON.Matrix.Zero();
- this._currentFaceIndex = 0;
- this._currentFaceIndexCache = 0;
- this._light = light;
- this._scene = light.getScene();
- this._mapSize = mapSize;
- light._shadowGenerator = this;
- // Render target
- this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
- this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
- this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
- this._shadowMap.anisotropicFilteringLevel = 1;
- this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
- this._shadowMap.renderParticles = false;
- this._shadowMap.onBeforeRender = function (faceIndex) {
- _this._currentFaceIndex = faceIndex;
- };
- this._shadowMap.onAfterUnbind = function () {
- if (!_this.useBlurVarianceShadowMap) {
- return;
- }
- if (!_this._shadowMap2) {
- _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
- _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
- _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
- _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
- _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
- _this._downSamplePostprocess.onApply = function (effect) {
- effect.setTexture("textureSampler", _this._shadowMap);
- };
- _this.blurBoxOffset = 1;
- }
- _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
- };
- // Custom render function
- var renderSubMesh = function (subMesh) {
- var mesh = subMesh.getRenderingMesh();
- var scene = _this._scene;
- var engine = scene.getEngine();
- // Culling
- engine.setState(subMesh.getMaterial().backFaceCulling);
- // Managing instances
- var batch = mesh._getInstancesRenderList(subMesh._id);
- if (batch.mustReturn) {
- return;
- }
- var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
- if (_this.isReady(subMesh, hardwareInstancedRendering)) {
- engine.enableEffect(_this._effect);
- mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
- var material = subMesh.getMaterial();
- _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
- _this._effect.setVector3("lightPosition", _this.getLight().position);
- if (_this.getLight().needCube()) {
- _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
- }
- // Alpha test
- if (material && material.needAlphaTesting()) {
- var alphaTexture = material.getAlphaTestTexture();
- _this._effect.setTexture("diffuseSampler", alphaTexture);
- _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
- }
- // Bones
- if (mesh.useBones && mesh.computeBonesUsingShaders) {
- _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
- }
- if (_this.forceBackFacesOnly) {
- engine.setState(true, 0, false, true);
- }
- // Draw
- mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
- if (_this.forceBackFacesOnly) {
- engine.setState(true, 0, false, false);
- }
- }
- else {
- // Need to reset refresh rate of the shadowMap
- _this._shadowMap.resetRefreshCounter();
- }
- };
- this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
- var index;
- for (index = 0; index < opaqueSubMeshes.length; index++) {
- renderSubMesh(opaqueSubMeshes.data[index]);
- }
- for (index = 0; index < alphaTestSubMeshes.length; index++) {
- renderSubMesh(alphaTestSubMeshes.data[index]);
- }
- if (_this._transparencyShadow) {
- for (index = 0; index < transparentSubMeshes.length; index++) {
- renderSubMesh(transparentSubMeshes.data[index]);
- }
- }
- };
- this._shadowMap.onClear = function (engine) {
- if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
- engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
- }
- else {
- engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
- }
- };
- }
- Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
- // Static
- get: function () {
- return ShadowGenerator._FILTER_NONE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
- get: function () {
- return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
- get: function () {
- return ShadowGenerator._FILTER_POISSONSAMPLING;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
- get: function () {
- return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ShadowGenerator.prototype, "bias", {
- get: function () {
- return this._bias;
- },
- set: function (bias) {
- this._bias = bias;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
- get: function () {
- return this._blurBoxOffset;
- },
- set: function (value) {
- var _this = this;
- if (this._blurBoxOffset === value) {
- return;
- }
- this._blurBoxOffset = value;
- if (this._boxBlurPostprocess) {
- this._boxBlurPostprocess.dispose();
- }
- 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);
- this._boxBlurPostprocess.onApply = function (effect) {
- effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
- };
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ShadowGenerator.prototype, "filter", {
- get: function () {
- return this._filter;
- },
- set: function (value) {
- if (this._filter === value) {
- return;
- }
- this._filter = value;
- if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
- this._shadowMap.anisotropicFilteringLevel = 16;
- this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
- }
- else {
- this._shadowMap.anisotropicFilteringLevel = 1;
- this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
- get: function () {
- return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
- },
- set: function (value) {
- this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
- get: function () {
- return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
- (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
- this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
- },
- set: function (value) {
- this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
- get: function () {
- return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
- },
- set: function (value) {
- this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
- },
- enumerable: true,
- configurable: true
- });
- ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
- var defines = [];
- if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
- defines.push("#define VSM");
- }
- if (this.getLight().needCube()) {
- defines.push("#define CUBEMAP");
- }
- var attribs = [BABYLON.VertexBuffer.PositionKind];
- var mesh = subMesh.getMesh();
- var material = subMesh.getMaterial();
- // Alpha test
- if (material && material.needAlphaTesting()) {
- defines.push("#define ALPHATEST");
- if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
- attribs.push(BABYLON.VertexBuffer.UVKind);
- defines.push("#define UV1");
- }
- if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
- attribs.push(BABYLON.VertexBuffer.UV2Kind);
- defines.push("#define UV2");
- }
- }
- // Bones
- if (mesh.useBones && mesh.computeBonesUsingShaders) {
- attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
- attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
- if (mesh.numBoneInfluencers > 4) {
- attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
- attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
- }
- defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
- defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
- }
- else {
- defines.push("#define NUM_BONE_INFLUENCERS 0");
- }
- // Instances
- if (useInstances) {
- defines.push("#define INSTANCES");
- attribs.push("world0");
- attribs.push("world1");
- attribs.push("world2");
- attribs.push("world3");
- }
- // Get correct effect
- var join = defines.join("\n");
- if (this._cachedDefines !== join) {
- this._cachedDefines = join;
- this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
- }
- return this._effect.isReady();
- };
- ShadowGenerator.prototype.getShadowMap = function () {
- return this._shadowMap;
- };
- ShadowGenerator.prototype.getShadowMapForRendering = function () {
- if (this._shadowMap2) {
- return this._shadowMap2;
- }
- return this._shadowMap;
- };
- ShadowGenerator.prototype.getLight = function () {
- return this._light;
- };
- // Methods
- ShadowGenerator.prototype.getTransformMatrix = function () {
- var scene = this._scene;
- if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
- return this._transformMatrix;
- }
- this._currentRenderID = scene.getRenderId();
- this._currentFaceIndexCache = this._currentFaceIndex;
- var lightPosition = this._light.position;
- BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
- if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
- this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
- }
- if (this._light.computeTransformedPosition()) {
- lightPosition = this._light.transformedPosition;
- }
- if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
- this._cachedPosition = lightPosition.clone();
- this._cachedDirection = this._lightDirection.clone();
- BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
- this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
- this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
- }
- return this._transformMatrix;
- };
- ShadowGenerator.prototype.getDarkness = function () {
- return this._darkness;
- };
- ShadowGenerator.prototype.setDarkness = function (darkness) {
- if (darkness >= 1.0)
- this._darkness = 1.0;
- else if (darkness <= 0.0)
- this._darkness = 0.0;
- else
- this._darkness = darkness;
- };
- ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
- this._transparencyShadow = hasShadow;
- };
- ShadowGenerator.prototype._packHalf = function (depth) {
- var scale = depth * 255.0;
- var fract = scale - Math.floor(scale);
- return new BABYLON.Vector2(depth - fract / 255.0, fract);
- };
- ShadowGenerator.prototype.dispose = function () {
- this._shadowMap.dispose();
- if (this._shadowMap2) {
- this._shadowMap2.dispose();
- }
- if (this._downSamplePostprocess) {
- this._downSamplePostprocess.dispose();
- }
- if (this._boxBlurPostprocess) {
- this._boxBlurPostprocess.dispose();
- }
- };
- ShadowGenerator.prototype.serialize = function () {
- var serializationObject = {};
- serializationObject.lightId = this._light.id;
- serializationObject.mapSize = this.getShadowMap().getRenderSize();
- serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
- serializationObject.usePoissonSampling = this.usePoissonSampling;
- serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
- serializationObject.renderList = [];
- for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
- var mesh = this.getShadowMap().renderList[meshIndex];
- serializationObject.renderList.push(mesh.id);
- }
- return serializationObject;
- };
- ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
- //casting to point light, as light is missing the position attr and typescript complains.
- var light = scene.getLightByID(parsedShadowGenerator.lightId);
- var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
- for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
- var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
- meshes.forEach(function (mesh) {
- shadowGenerator.getShadowMap().renderList.push(mesh);
- });
- }
- if (parsedShadowGenerator.usePoissonSampling) {
- shadowGenerator.usePoissonSampling = true;
- }
- else if (parsedShadowGenerator.useVarianceShadowMap) {
- shadowGenerator.useVarianceShadowMap = true;
- }
- else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
- shadowGenerator.useBlurVarianceShadowMap = true;
- if (parsedShadowGenerator.blurScale) {
- shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
- }
- if (parsedShadowGenerator.blurBoxOffset) {
- shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
- }
- }
- if (parsedShadowGenerator.bias !== undefined) {
- shadowGenerator.bias = parsedShadowGenerator.bias;
- }
- shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
- return shadowGenerator;
- };
- ShadowGenerator._FILTER_NONE = 0;
- ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
- ShadowGenerator._FILTER_POISSONSAMPLING = 2;
- ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
- return ShadowGenerator;
- })();
- BABYLON.ShadowGenerator = ShadowGenerator;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
- if (boxMin.x > sphereCenter.x + sphereRadius)
- return false;
- if (sphereCenter.x - sphereRadius > boxMax.x)
- return false;
- if (boxMin.y > sphereCenter.y + sphereRadius)
- return false;
- if (sphereCenter.y - sphereRadius > boxMax.y)
- return false;
- if (boxMin.z > sphereCenter.z + sphereRadius)
- return false;
- if (sphereCenter.z - sphereRadius > boxMax.z)
- return false;
- return true;
- };
- var getLowestRoot = function (a, b, c, maxR) {
- var determinant = b * b - 4.0 * a * c;
- var result = { root: 0, found: false };
- if (determinant < 0)
- return result;
- var sqrtD = Math.sqrt(determinant);
- var r1 = (-b - sqrtD) / (2.0 * a);
- var r2 = (-b + sqrtD) / (2.0 * a);
- if (r1 > r2) {
- var temp = r2;
- r2 = r1;
- r1 = temp;
- }
- if (r1 > 0 && r1 < maxR) {
- result.root = r1;
- result.found = true;
- return result;
- }
- if (r2 > 0 && r2 < maxR) {
- result.root = r2;
- result.found = true;
- return result;
- }
- return result;
- };
- var Collider = (function () {
- function Collider() {
- this.radius = new BABYLON.Vector3(1, 1, 1);
- this.retry = 0;
- this.basePointWorld = BABYLON.Vector3.Zero();
- this.velocityWorld = BABYLON.Vector3.Zero();
- this.normalizedVelocity = BABYLON.Vector3.Zero();
- this._collisionPoint = BABYLON.Vector3.Zero();
- this._planeIntersectionPoint = BABYLON.Vector3.Zero();
- this._tempVector = BABYLON.Vector3.Zero();
- this._tempVector2 = BABYLON.Vector3.Zero();
- this._tempVector3 = BABYLON.Vector3.Zero();
- this._tempVector4 = BABYLON.Vector3.Zero();
- this._edge = BABYLON.Vector3.Zero();
- this._baseToVertex = BABYLON.Vector3.Zero();
- this._destinationPoint = BABYLON.Vector3.Zero();
- this._slidePlaneNormal = BABYLON.Vector3.Zero();
- this._displacementVector = BABYLON.Vector3.Zero();
- }
- // Methods
- Collider.prototype._initialize = function (source, dir, e) {
- this.velocity = dir;
- BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
- this.basePoint = source;
- source.multiplyToRef(this.radius, this.basePointWorld);
- dir.multiplyToRef(this.radius, this.velocityWorld);
- this.velocityWorldLength = this.velocityWorld.length();
- this.epsilon = e;
- this.collisionFound = false;
- };
- Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
- pa.subtractToRef(point, this._tempVector);
- pb.subtractToRef(point, this._tempVector2);
- BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
- var d = BABYLON.Vector3.Dot(this._tempVector4, n);
- if (d < 0)
- return false;
- pc.subtractToRef(point, this._tempVector3);
- BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
- d = BABYLON.Vector3.Dot(this._tempVector4, n);
- if (d < 0)
- return false;
- BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
- d = BABYLON.Vector3.Dot(this._tempVector4, n);
- return d >= 0;
- };
- Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
- var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
- var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
- if (distance > this.velocityWorldLength + max + sphereRadius) {
- return false;
- }
- if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
- return false;
- return true;
- };
- Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
- var t0;
- var embeddedInPlane = false;
- //defensive programming, actually not needed.
- if (!trianglePlaneArray) {
- trianglePlaneArray = [];
- }
- if (!trianglePlaneArray[faceIndex]) {
- trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
- trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
- }
- var trianglePlane = trianglePlaneArray[faceIndex];
- if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
- return;
- var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
- var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
- if (normalDotVelocity == 0) {
- if (Math.abs(signedDistToTrianglePlane) >= 1.0)
- return;
- embeddedInPlane = true;
- t0 = 0;
- }
- else {
- t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
- var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
- if (t0 > t1) {
- var temp = t1;
- t1 = t0;
- t0 = temp;
- }
- if (t0 > 1.0 || t1 < 0.0)
- return;
- if (t0 < 0)
- t0 = 0;
- if (t0 > 1.0)
- t0 = 1.0;
- }
- this._collisionPoint.copyFromFloats(0, 0, 0);
- var found = false;
- var t = 1.0;
- if (!embeddedInPlane) {
- this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
- this.velocity.scaleToRef(t0, this._tempVector);
- this._planeIntersectionPoint.addInPlace(this._tempVector);
- if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
- found = true;
- t = t0;
- this._collisionPoint.copyFrom(this._planeIntersectionPoint);
- }
- }
- if (!found) {
- var velocitySquaredLength = this.velocity.lengthSquared();
- var a = velocitySquaredLength;
- this.basePoint.subtractToRef(p1, this._tempVector);
- var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
- var c = this._tempVector.lengthSquared() - 1.0;
- var lowestRoot = getLowestRoot(a, b, c, t);
- if (lowestRoot.found) {
- t = lowestRoot.root;
- found = true;
- this._collisionPoint.copyFrom(p1);
- }
- this.basePoint.subtractToRef(p2, this._tempVector);
- b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
- c = this._tempVector.lengthSquared() - 1.0;
- lowestRoot = getLowestRoot(a, b, c, t);
- if (lowestRoot.found) {
- t = lowestRoot.root;
- found = true;
- this._collisionPoint.copyFrom(p2);
- }
- this.basePoint.subtractToRef(p3, this._tempVector);
- b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
- c = this._tempVector.lengthSquared() - 1.0;
- lowestRoot = getLowestRoot(a, b, c, t);
- if (lowestRoot.found) {
- t = lowestRoot.root;
- found = true;
- this._collisionPoint.copyFrom(p3);
- }
- p2.subtractToRef(p1, this._edge);
- p1.subtractToRef(this.basePoint, this._baseToVertex);
- var edgeSquaredLength = this._edge.lengthSquared();
- var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
- var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
- a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
- b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
- c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
- lowestRoot = getLowestRoot(a, b, c, t);
- if (lowestRoot.found) {
- var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
- if (f >= 0.0 && f <= 1.0) {
- t = lowestRoot.root;
- found = true;
- this._edge.scaleInPlace(f);
- p1.addToRef(this._edge, this._collisionPoint);
- }
- }
- p3.subtractToRef(p2, this._edge);
- p2.subtractToRef(this.basePoint, this._baseToVertex);
- edgeSquaredLength = this._edge.lengthSquared();
- edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
- edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
- a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
- b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
- c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
- lowestRoot = getLowestRoot(a, b, c, t);
- if (lowestRoot.found) {
- f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
- if (f >= 0.0 && f <= 1.0) {
- t = lowestRoot.root;
- found = true;
- this._edge.scaleInPlace(f);
- p2.addToRef(this._edge, this._collisionPoint);
- }
- }
- p1.subtractToRef(p3, this._edge);
- p3.subtractToRef(this.basePoint, this._baseToVertex);
- edgeSquaredLength = this._edge.lengthSquared();
- edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
- edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
- a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
- b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
- c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
- lowestRoot = getLowestRoot(a, b, c, t);
- if (lowestRoot.found) {
- f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
- if (f >= 0.0 && f <= 1.0) {
- t = lowestRoot.root;
- found = true;
- this._edge.scaleInPlace(f);
- p3.addToRef(this._edge, this._collisionPoint);
- }
- }
- }
- if (found) {
- var distToCollision = t * this.velocity.length();
- if (!this.collisionFound || distToCollision < this.nearestDistance) {
- if (!this.intersectionPoint) {
- this.intersectionPoint = this._collisionPoint.clone();
- }
- else {
- this.intersectionPoint.copyFrom(this._collisionPoint);
- }
- this.nearestDistance = distToCollision;
- this.collisionFound = true;
- }
- }
- };
- Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
- for (var i = indexStart; i < indexEnd; i += 3) {
- var p1 = pts[indices[i] - decal];
- var p2 = pts[indices[i + 1] - decal];
- var p3 = pts[indices[i + 2] - decal];
- this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
- }
- };
- Collider.prototype._getResponse = function (pos, vel) {
- pos.addToRef(vel, this._destinationPoint);
- vel.scaleInPlace((this.nearestDistance / vel.length()));
- this.basePoint.addToRef(vel, pos);
- pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
- this._slidePlaneNormal.normalize();
- this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
- pos.addInPlace(this._displacementVector);
- this.intersectionPoint.addInPlace(this._displacementVector);
- this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
- this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
- this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
- };
- return Collider;
- })();
- BABYLON.Collider = Collider;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- //WebWorker code will be inserted to this variable.
- BABYLON.CollisionWorker = "";
- (function (WorkerTaskType) {
- WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
- WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
- WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
- })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
- var WorkerTaskType = BABYLON.WorkerTaskType;
- (function (WorkerReplyType) {
- WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
- WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
- })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
- var WorkerReplyType = BABYLON.WorkerReplyType;
- var CollisionCoordinatorWorker = (function () {
- function CollisionCoordinatorWorker() {
- var _this = this;
- this._scaledPosition = BABYLON.Vector3.Zero();
- this._scaledVelocity = BABYLON.Vector3.Zero();
- this.onMeshUpdated = function (mesh) {
- _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
- };
- this.onGeometryUpdated = function (geometry) {
- _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
- };
- this._afterRender = function () {
- if (!_this._init)
- return;
- if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
- return;
- }
- //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
- //TODO make sure update runs as fast as possible to be able to update 60 FPS.
- if (_this._runningUpdated > 4) {
- return;
- }
- ++_this._runningUpdated;
- var payload = {
- updatedMeshes: _this._addUpdateMeshesList,
- updatedGeometries: _this._addUpdateGeometriesList,
- removedGeometries: _this._toRemoveGeometryArray,
- removedMeshes: _this._toRemoveMeshesArray
- };
- var message = {
- payload: payload,
- taskType: WorkerTaskType.UPDATE
- };
- var serializable = [];
- for (var id in payload.updatedGeometries) {
- if (payload.updatedGeometries.hasOwnProperty(id)) {
- //prepare transferables
- serializable.push(message.payload.updatedGeometries[id].indices.buffer);
- serializable.push(message.payload.updatedGeometries[id].normals.buffer);
- serializable.push(message.payload.updatedGeometries[id].positions.buffer);
- }
- }
- _this._worker.postMessage(message, serializable);
- _this._addUpdateMeshesList = {};
- _this._addUpdateGeometriesList = {};
- _this._toRemoveGeometryArray = [];
- _this._toRemoveMeshesArray = [];
- };
- this._onMessageFromWorker = function (e) {
- var returnData = e.data;
- if (returnData.error != WorkerReplyType.SUCCESS) {
- //TODO what errors can be returned from the worker?
- BABYLON.Tools.Warn("error returned from worker!");
- return;
- }
- switch (returnData.taskType) {
- case WorkerTaskType.INIT:
- _this._init = true;
- //Update the worked with ALL of the scene's current state
- _this._scene.meshes.forEach(function (mesh) {
- _this.onMeshAdded(mesh);
- });
- _this._scene.getGeometries().forEach(function (geometry) {
- _this.onGeometryAdded(geometry);
- });
- break;
- case WorkerTaskType.UPDATE:
- _this._runningUpdated--;
- break;
- case WorkerTaskType.COLLIDE:
- _this._runningCollisionTask = false;
- var returnPayload = returnData.payload;
- if (!_this._collisionsCallbackArray[returnPayload.collisionId])
- return;
- _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
- //cleanup
- _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
- break;
- }
- };
- this._collisionsCallbackArray = [];
- this._init = false;
- this._runningUpdated = 0;
- this._runningCollisionTask = false;
- this._addUpdateMeshesList = {};
- this._addUpdateGeometriesList = {};
- this._toRemoveGeometryArray = [];
- this._toRemoveMeshesArray = [];
- }
- CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
- if (!this._init)
- return;
- if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
- return;
- position.divideToRef(collider.radius, this._scaledPosition);
- velocity.divideToRef(collider.radius, this._scaledVelocity);
- this._collisionsCallbackArray[collisionIndex] = onNewPosition;
- var payload = {
- collider: {
- position: this._scaledPosition.asArray(),
- velocity: this._scaledVelocity.asArray(),
- radius: collider.radius.asArray()
- },
- collisionId: collisionIndex,
- excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
- maximumRetry: maximumRetry
- };
- var message = {
- payload: payload,
- taskType: WorkerTaskType.COLLIDE
- };
- this._worker.postMessage(message);
- };
- CollisionCoordinatorWorker.prototype.init = function (scene) {
- this._scene = scene;
- this._scene.registerAfterRender(this._afterRender);
- var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
- this._worker = new Worker(workerUrl);
- this._worker.onmessage = this._onMessageFromWorker;
- var message = {
- payload: {},
- taskType: WorkerTaskType.INIT
- };
- this._worker.postMessage(message);
- };
- CollisionCoordinatorWorker.prototype.destroy = function () {
- this._scene.unregisterAfterRender(this._afterRender);
- this._worker.terminate();
- };
- CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
- mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
- this.onMeshUpdated(mesh);
- };
- CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
- this._toRemoveMeshesArray.push(mesh.uniqueId);
- };
- CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
- //TODO this will break if the user uses his own function. This should be an array of callbacks!
- geometry.onGeometryUpdated = this.onGeometryUpdated;
- this.onGeometryUpdated(geometry);
- };
- CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
- this._toRemoveGeometryArray.push(geometry.id);
- };
- CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
- var submeshes = [];
- if (mesh.subMeshes) {
- submeshes = mesh.subMeshes.map(function (sm, idx) {
- return {
- position: idx,
- verticesStart: sm.verticesStart,
- verticesCount: sm.verticesCount,
- indexStart: sm.indexStart,
- indexCount: sm.indexCount,
- hasMaterial: !!sm.getMaterial(),
- sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
- sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
- boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
- boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
- };
- });
- }
- var geometryId = null;
- if (mesh instanceof BABYLON.Mesh) {
- geometryId = mesh.geometry ? mesh.geometry.id : null;
- }
- else if (mesh instanceof BABYLON.InstancedMesh) {
- geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
- }
- return {
- uniqueId: mesh.uniqueId,
- id: mesh.id,
- name: mesh.name,
- geometryId: geometryId,
- sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
- sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
- boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
- boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
- worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
- subMeshes: submeshes,
- checkCollisions: mesh.checkCollisions
- };
- };
- CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
- return {
- id: geometry.id,
- positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
- normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
- indices: new Int32Array(geometry.getIndices() || []),
- };
- };
- return CollisionCoordinatorWorker;
- })();
- BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
- var CollisionCoordinatorLegacy = (function () {
- function CollisionCoordinatorLegacy() {
- this._scaledPosition = BABYLON.Vector3.Zero();
- this._scaledVelocity = BABYLON.Vector3.Zero();
- this._finalPosition = BABYLON.Vector3.Zero();
- }
- CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
- position.divideToRef(collider.radius, this._scaledPosition);
- velocity.divideToRef(collider.radius, this._scaledVelocity);
- collider.collidedMesh = null;
- collider.retry = 0;
- collider.initialVelocity = this._scaledVelocity;
- collider.initialPosition = this._scaledPosition;
- this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
- this._finalPosition.multiplyInPlace(collider.radius);
- //run the callback
- onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
- };
- CollisionCoordinatorLegacy.prototype.init = function (scene) {
- this._scene = scene;
- };
- CollisionCoordinatorLegacy.prototype.destroy = function () {
- //Legacy need no destruction method.
- };
- //No update in legacy mode
- CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
- CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
- CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
- CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
- CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
- CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
- CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
- if (excludedMesh === void 0) { excludedMesh = null; }
- var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
- if (collider.retry >= maximumRetry) {
- finalPosition.copyFrom(position);
- return;
- }
- collider._initialize(position, velocity, closeDistance);
- // Check all meshes
- for (var index = 0; index < this._scene.meshes.length; index++) {
- var mesh = this._scene.meshes[index];
- if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
- mesh._checkCollision(collider);
- }
- }
- if (!collider.collisionFound) {
- position.addToRef(velocity, finalPosition);
- return;
- }
- if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
- collider._getResponse(position, velocity);
- }
- if (velocity.length() <= closeDistance) {
- finalPosition.copyFrom(position);
- return;
- }
- collider.retry++;
- this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
- };
- return CollisionCoordinatorLegacy;
- })();
- BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Camera = (function (_super) {
- __extends(Camera, _super);
- function Camera(name, position, scene) {
- _super.call(this, name, scene);
- this.upVector = BABYLON.Vector3.Up();
- this.orthoLeft = null;
- this.orthoRight = null;
- this.orthoBottom = null;
- this.orthoTop = null;
- this.fov = 0.8;
- this.minZ = 1.0;
- this.maxZ = 10000.0;
- this.inertia = 0.9;
- this.mode = Camera.PERSPECTIVE_CAMERA;
- this.isIntermediate = false;
- this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
- this.layerMask = 0x0FFFFFFF;
- this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
- // Camera rig members
- this.cameraRigMode = Camera.RIG_MODE_NONE;
- this._rigCameras = new Array();
- // Cache
- this._computedViewMatrix = BABYLON.Matrix.Identity();
- this._projectionMatrix = new BABYLON.Matrix();
- this._postProcesses = new Array();
- this._postProcessesTakenIndices = [];
- this._activeMeshes = new BABYLON.SmartArray(256);
- this._globalPosition = BABYLON.Vector3.Zero();
- scene.addCamera(this);
- if (!scene.activeCamera) {
- scene.activeCamera = this;
- }
- this.position = position;
- }
- Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
- get: function () {
- return Camera._PERSPECTIVE_CAMERA;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
- get: function () {
- return Camera._ORTHOGRAPHIC_CAMERA;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
- get: function () {
- return Camera._FOVMODE_VERTICAL_FIXED;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
- get: function () {
- return Camera._FOVMODE_HORIZONTAL_FIXED;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Camera, "RIG_MODE_NONE", {
- get: function () {
- return Camera._RIG_MODE_NONE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
- get: function () {
- return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
- get: function () {
- return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
- get: function () {
- return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
- get: function () {
- return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Camera, "RIG_MODE_VR", {
- get: function () {
- return Camera._RIG_MODE_VR;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
- */
- Camera.prototype.toString = function (fullDetails) {
- var ret = "Name: " + this.name;
- ret += ", type: " + this.getTypeName();
- if (this.animations) {
- for (var i = 0; i < this.animations.length; i++) {
- ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
- }
- }
- if (fullDetails) {
- }
- return ret;
- };
- Object.defineProperty(Camera.prototype, "globalPosition", {
- get: function () {
- return this._globalPosition;
- },
- enumerable: true,
- configurable: true
- });
- Camera.prototype.getActiveMeshes = function () {
- return this._activeMeshes;
- };
- Camera.prototype.isActiveMesh = function (mesh) {
- return (this._activeMeshes.indexOf(mesh) !== -1);
- };
- //Cache
- Camera.prototype._initCache = function () {
- _super.prototype._initCache.call(this);
- this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
- this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
- this._cache.mode = undefined;
- this._cache.minZ = undefined;
- this._cache.maxZ = undefined;
- this._cache.fov = undefined;
- this._cache.aspectRatio = undefined;
- this._cache.orthoLeft = undefined;
- this._cache.orthoRight = undefined;
- this._cache.orthoBottom = undefined;
- this._cache.orthoTop = undefined;
- this._cache.renderWidth = undefined;
- this._cache.renderHeight = undefined;
- };
- Camera.prototype._updateCache = function (ignoreParentClass) {
- if (!ignoreParentClass) {
- _super.prototype._updateCache.call(this);
- }
- var engine = this.getEngine();
- this._cache.position.copyFrom(this.position);
- this._cache.upVector.copyFrom(this.upVector);
- this._cache.mode = this.mode;
- this._cache.minZ = this.minZ;
- this._cache.maxZ = this.maxZ;
- this._cache.fov = this.fov;
- this._cache.aspectRatio = engine.getAspectRatio(this);
- this._cache.orthoLeft = this.orthoLeft;
- this._cache.orthoRight = this.orthoRight;
- this._cache.orthoBottom = this.orthoBottom;
- this._cache.orthoTop = this.orthoTop;
- this._cache.renderWidth = engine.getRenderWidth();
- this._cache.renderHeight = engine.getRenderHeight();
- };
- Camera.prototype._updateFromScene = function () {
- this.updateCache();
- this._update();
- };
- // Synchronized
- Camera.prototype._isSynchronized = function () {
- return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
- };
- Camera.prototype._isSynchronizedViewMatrix = function () {
- if (!_super.prototype._isSynchronized.call(this))
- return false;
- return this._cache.position.equals(this.position)
- && this._cache.upVector.equals(this.upVector)
- && this.isSynchronizedWithParent();
- };
- Camera.prototype._isSynchronizedProjectionMatrix = function () {
- var check = this._cache.mode === this.mode
- && this._cache.minZ === this.minZ
- && this._cache.maxZ === this.maxZ;
- if (!check) {
- return false;
- }
- var engine = this.getEngine();
- if (this.mode === Camera.PERSPECTIVE_CAMERA) {
- check = this._cache.fov === this.fov
- && this._cache.aspectRatio === engine.getAspectRatio(this);
- }
- else {
- check = this._cache.orthoLeft === this.orthoLeft
- && this._cache.orthoRight === this.orthoRight
- && this._cache.orthoBottom === this.orthoBottom
- && this._cache.orthoTop === this.orthoTop
- && this._cache.renderWidth === engine.getRenderWidth()
- && this._cache.renderHeight === engine.getRenderHeight();
- }
- return check;
- };
- // Controls
- Camera.prototype.attachControl = function (element, noPreventDefault) {
- };
- Camera.prototype.detachControl = function (element) {
- };
- Camera.prototype._update = function () {
- if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
- this._updateRigCameras();
- }
- this._checkInputs();
- };
- Camera.prototype._checkInputs = function () {
- };
- Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
- if (insertAt === void 0) { insertAt = null; }
- if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
- BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
- return 0;
- }
- if (insertAt == null || insertAt < 0) {
- this._postProcesses.push(postProcess);
- this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
- return this._postProcesses.length - 1;
- }
- var add = 0;
- var i;
- var start;
- if (this._postProcesses[insertAt]) {
- start = this._postProcesses.length - 1;
- for (i = start; i >= insertAt + 1; --i) {
- this._postProcesses[i + 1] = this._postProcesses[i];
- }
- add = 1;
- }
- for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
- if (this._postProcessesTakenIndices[i] < insertAt) {
- continue;
- }
- start = this._postProcessesTakenIndices.length - 1;
- for (var j = start; j >= i; --j) {
- this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
- }
- this._postProcessesTakenIndices[i] = insertAt;
- break;
- }
- if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
- this._postProcessesTakenIndices.push(insertAt);
- }
- var result = insertAt + add;
- this._postProcesses[result] = postProcess;
- return result;
- };
- Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
- if (atIndices === void 0) { atIndices = null; }
- var result = [];
- var i;
- var index;
- if (!atIndices) {
- var length = this._postProcesses.length;
- for (i = 0; i < length; i++) {
- if (this._postProcesses[i] !== postProcess) {
- continue;
- }
- delete this._postProcesses[i];
- index = this._postProcessesTakenIndices.indexOf(i);
- this._postProcessesTakenIndices.splice(index, 1);
- }
- }
- else {
- atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
- for (i = 0; i < atIndices.length; i++) {
- var foundPostProcess = this._postProcesses[atIndices[i]];
- if (foundPostProcess !== postProcess) {
- result.push(i);
- continue;
- }
- delete this._postProcesses[atIndices[i]];
- index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
- this._postProcessesTakenIndices.splice(index, 1);
- }
- }
- return result;
- };
- Camera.prototype.getWorldMatrix = function () {
- if (!this._worldMatrix) {
- this._worldMatrix = BABYLON.Matrix.Identity();
- }
- var viewMatrix = this.getViewMatrix();
- viewMatrix.invertToRef(this._worldMatrix);
- return this._worldMatrix;
- };
- Camera.prototype._getViewMatrix = function () {
- return BABYLON.Matrix.Identity();
- };
- Camera.prototype.getViewMatrix = function (force) {
- this._computedViewMatrix = this._computeViewMatrix(force);
- if (!force && this._isSynchronizedViewMatrix()) {
- return this._computedViewMatrix;
- }
- if (!this.parent || !this.parent.getWorldMatrix) {
- this._globalPosition.copyFrom(this.position);
- }
- else {
- if (!this._worldMatrix) {
- this._worldMatrix = BABYLON.Matrix.Identity();
- }
- this._computedViewMatrix.invertToRef(this._worldMatrix);
- this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
- this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
- this._computedViewMatrix.invert();
- this._markSyncedWithParent();
- }
- this._currentRenderId = this.getScene().getRenderId();
- return this._computedViewMatrix;
- };
- Camera.prototype._computeViewMatrix = function (force) {
- if (!force && this._isSynchronizedViewMatrix()) {
- return this._computedViewMatrix;
- }
- this._computedViewMatrix = this._getViewMatrix();
- this._currentRenderId = this.getScene().getRenderId();
- return this._computedViewMatrix;
- };
- Camera.prototype.getProjectionMatrix = function (force) {
- if (!force && this._isSynchronizedProjectionMatrix()) {
- return this._projectionMatrix;
- }
- var engine = this.getEngine();
- if (this.mode === Camera.PERSPECTIVE_CAMERA) {
- if (this.minZ <= 0) {
- this.minZ = 0.1;
- }
- BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
- return this._projectionMatrix;
- }
- var halfWidth = engine.getRenderWidth() / 2.0;
- var halfHeight = engine.getRenderHeight() / 2.0;
- BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
- return this._projectionMatrix;
- };
- Camera.prototype.dispose = function () {
- // Animations
- this.getScene().stopAnimation(this);
- // Remove from scene
- this.getScene().removeCamera(this);
- while (this._rigCameras.length > 0) {
- this._rigCameras.pop().dispose();
- }
- // Postprocesses
- for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
- this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
- }
- _super.prototype.dispose.call(this);
- };
- // ---- Camera rigs section ----
- Camera.prototype.setCameraRigMode = function (mode, rigParams) {
- while (this._rigCameras.length > 0) {
- this._rigCameras.pop().dispose();
- }
- this.cameraRigMode = mode;
- this._cameraRigParams = {};
- switch (this.cameraRigMode) {
- case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
- case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
- case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
- case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
- this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
- //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
- //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
- this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
- this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
- this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
- break;
- }
- var postProcesses = new Array();
- switch (this.cameraRigMode) {
- case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
- postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
- this._rigCameras[0].isIntermediate = true;
- postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
- postProcesses[1].onApply = function (effect) {
- effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
- };
- break;
- case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
- case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
- case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
- var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
- var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
- var secondCamIndex = 1 - firstCamIndex;
- postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
- this._rigCameras[firstCamIndex].isIntermediate = true;
- postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
- break;
- case Camera.RIG_MODE_VR:
- this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
- this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
- this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
- this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
- var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
- this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
- this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
- this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
- this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
- this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
- this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
- if (metrics.compensateDistortion) {
- postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
- }
- this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
- this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
- this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
- this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
- this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
- this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
- if (metrics.compensateDistortion) {
- postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
- }
- break;
- }
- this._update();
- };
- Camera.prototype._getVRProjectionMatrix = function () {
- BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
- this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
- return this._projectionMatrix;
- };
- Camera.prototype.setCameraRigParameter = function (name, value) {
- this._cameraRigParams[name] = value;
- //provisionnally:
- if (name === "interaxialDistance") {
- this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
- }
- };
- /**
- * May needs to be overridden by children so sub has required properties to be copied
- */
- Camera.prototype.createRigCamera = function (name, cameraIndex) {
- return null;
- };
- /**
- * May needs to be overridden by children
- */
- Camera.prototype._updateRigCameras = function () {
- for (var i = 0; i < this._rigCameras.length; i++) {
- this._rigCameras[i].minZ = this.minZ;
- this._rigCameras[i].maxZ = this.maxZ;
- this._rigCameras[i].fov = this.fov;
- }
- // only update viewport when ANAGLYPH
- if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
- this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
- }
- };
- Camera.prototype._setupInputs = function () {
- };
- Camera.prototype.serialize = function () {
- var serializationObject = BABYLON.SerializationHelper.Serialize(this);
- // Type
- serializationObject.type = this.getTypeName();
- // Parent
- if (this.parent) {
- serializationObject.parentId = this.parent.id;
- }
- if (this.inputs) {
- this.inputs.serialize(serializationObject);
- }
- // Animations
- BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
- serializationObject.ranges = this.serializeAnimationRanges();
- return serializationObject;
- };
- Camera.prototype.getTypeName = function () {
- return "Camera";
- };
- Camera.prototype.clone = function (name) {
- return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
- };
- Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
- if (interaxial_distance === void 0) { interaxial_distance = 0; }
- if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
- switch (type) {
- case "ArcRotateCamera":
- return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
- case "DeviceOrientationCamera":
- return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
- case "FollowCamera":
- return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
- case "ArcFollowCamera":
- return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
- case "GamepadCamera":
- return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
- case "TouchCamera":
- return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
- case "VirtualJoysticksCamera":
- return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
- case "WebVRFreeCamera":
- return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
- case "VRDeviceOrientationFreeCamera":
- return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
- case "AnaglyphArcRotateCamera":
- return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
- case "AnaglyphFreeCamera":
- return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
- case "AnaglyphGamepadCamera":
- return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
- case "AnaglyphUniversalCamera":
- return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
- case "StereoscopicArcRotateCamera":
- return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
- case "StereoscopicFreeCamera":
- return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
- case "StereoscopicGamepadCamera":
- return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
- case "StereoscopicUniversalCamera":
- return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
- case "FreeCamera":
- return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
- default:
- return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
- }
- };
- Camera.Parse = function (parsedCamera, scene) {
- var type = parsedCamera.type;
- var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
- var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
- // Parent
- if (parsedCamera.parentId) {
- camera._waitingParentId = parsedCamera.parentId;
- }
- //If camera has an input manager, let it parse inputs settings
- if (camera.inputs) {
- camera.inputs.parse(parsedCamera);
- camera._setupInputs();
- }
- // Target
- if (parsedCamera.target) {
- if (camera.setTarget) {
- camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
- }
- }
- // Apply 3d rig, when found
- if (parsedCamera.cameraRigMode) {
- var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
- camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
- }
- // Animations
- if (parsedCamera.animations) {
- for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
- var parsedAnimation = parsedCamera.animations[animationIndex];
- camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
- }
- BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
- }
- if (parsedCamera.autoAnimate) {
- scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
- }
- return camera;
- };
- // Statics
- Camera._PERSPECTIVE_CAMERA = 0;
- Camera._ORTHOGRAPHIC_CAMERA = 1;
- Camera._FOVMODE_VERTICAL_FIXED = 0;
- Camera._FOVMODE_HORIZONTAL_FIXED = 1;
- Camera._RIG_MODE_NONE = 0;
- Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
- Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
- Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
- Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
- Camera._RIG_MODE_VR = 20;
- Camera.ForceAttachControlToAlwaysPreventDefault = false;
- __decorate([
- BABYLON.serializeAsVector3()
- ], Camera.prototype, "position", void 0);
- __decorate([
- BABYLON.serializeAsVector3()
- ], Camera.prototype, "upVector", void 0);
- __decorate([
- BABYLON.serialize()
- ], Camera.prototype, "orthoLeft", void 0);
- __decorate([
- BABYLON.serialize()
- ], Camera.prototype, "orthoRight", void 0);
- __decorate([
- BABYLON.serialize()
- ], Camera.prototype, "orthoBottom", void 0);
- __decorate([
- BABYLON.serialize()
- ], Camera.prototype, "orthoTop", void 0);
- __decorate([
- BABYLON.serialize()
- ], Camera.prototype, "fov", void 0);
- __decorate([
- BABYLON.serialize()
- ], Camera.prototype, "minZ", void 0);
- __decorate([
- BABYLON.serialize()
- ], Camera.prototype, "maxZ", void 0);
- __decorate([
- BABYLON.serialize()
- ], Camera.prototype, "inertia", void 0);
- __decorate([
- BABYLON.serialize()
- ], Camera.prototype, "mode", void 0);
- __decorate([
- BABYLON.serialize()
- ], Camera.prototype, "layerMask", void 0);
- __decorate([
- BABYLON.serialize()
- ], Camera.prototype, "fovMode", void 0);
- __decorate([
- BABYLON.serialize()
- ], Camera.prototype, "cameraRigMode", void 0);
- __decorate([
- BABYLON.serialize()
- ], Camera.prototype, "interaxialDistance", void 0);
- __decorate([
- BABYLON.serialize()
- ], Camera.prototype, "isStereoscopicSideBySide", void 0);
- return Camera;
- })(BABYLON.Node);
- BABYLON.Camera = Camera;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- BABYLON.CameraInputTypes = {};
- var CameraInputsManager = (function () {
- function CameraInputsManager(camera) {
- this.attached = {};
- this.camera = camera;
- this.checkInputs = function () { };
- }
- CameraInputsManager.prototype.add = function (input) {
- var type = input.getSimpleName();
- if (this.attached[type]) {
- BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
- return;
- }
- this.attached[type] = input;
- input.camera = this.camera;
- //for checkInputs, we are dynamically creating a function
- //the goal is to avoid the performance penalty of looping for inputs in the render loop
- if (input.checkInputs) {
- this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
- }
- if (this.attachedElement) {
- input.attachControl(this.attachedElement);
- }
- };
- CameraInputsManager.prototype.remove = function (inputToRemove) {
- for (var cam in this.attached) {
- var input = this.attached[cam];
- if (input === inputToRemove) {
- input.detachControl(this.attachedElement);
- delete this.attached[cam];
- this.rebuildInputCheck();
- }
- }
- };
- CameraInputsManager.prototype.removeByType = function (inputType) {
- for (var cam in this.attached) {
- var input = this.attached[cam];
- if (input.getTypeName() === inputType) {
- input.detachControl(this.attachedElement);
- delete this.attached[cam];
- this.rebuildInputCheck();
- }
- }
- };
- CameraInputsManager.prototype._addCheckInputs = function (fn) {
- var current = this.checkInputs;
- return function () {
- current();
- fn();
- };
- };
- CameraInputsManager.prototype.attachInput = function (input) {
- input.attachControl(this.attachedElement, this.noPreventDefault);
- };
- CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
- if (this.attachedElement) {
- return;
- }
- noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
- this.attachedElement = element;
- this.noPreventDefault = noPreventDefault;
- for (var cam in this.attached) {
- var input = this.attached[cam];
- this.attached[cam].attachControl(element, noPreventDefault);
- }
- };
- CameraInputsManager.prototype.detachElement = function (element) {
- if (this.attachedElement !== element) {
- return;
- }
- for (var cam in this.attached) {
- var input = this.attached[cam];
- this.attached[cam].detachControl(element);
- }
- this.attachedElement = null;
- };
- CameraInputsManager.prototype.rebuildInputCheck = function () {
- this.checkInputs = function () { };
- for (var cam in this.attached) {
- var input = this.attached[cam];
- if (input.checkInputs) {
- this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
- }
- }
- };
- CameraInputsManager.prototype.clear = function () {
- if (this.attachedElement) {
- this.detachElement(this.attachedElement);
- }
- this.attached = {};
- this.attachedElement = null;
- this.checkInputs = function () { };
- };
- CameraInputsManager.prototype.serialize = function (serializedCamera) {
- var inputs = {};
- for (var cam in this.attached) {
- var input = this.attached[cam];
- var res = BABYLON.SerializationHelper.Serialize(input);
- inputs[input.getTypeName()] = res;
- }
- serializedCamera.inputsmgr = inputs;
- };
- CameraInputsManager.prototype.parse = function (parsedCamera) {
- var parsedInputs = parsedCamera.inputsmgr;
- if (parsedInputs) {
- this.clear();
- for (var n in parsedInputs) {
- var construct = BABYLON.CameraInputTypes[n];
- if (construct) {
- var parsedinput = parsedInputs[n];
- var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
- this.add(input);
- }
- }
- }
- else {
- //2016-03-08 this part is for managing backward compatibility
- for (var n in this.attached) {
- var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
- if (construct) {
- var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
- this.remove(this.attached[n]);
- this.add(input);
- }
- }
- }
- };
- return CameraInputsManager;
- })();
- BABYLON.CameraInputsManager = CameraInputsManager;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var FreeCameraMouseInput = (function () {
- function FreeCameraMouseInput(touchEnabled) {
- if (touchEnabled === void 0) { touchEnabled = true; }
- this.touchEnabled = touchEnabled;
- this.angularSensibility = 2000.0;
- }
- FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
- var _this = this;
- if (!this._pointerInput) {
- var camera = this.camera;
- var engine = this.camera.getEngine();
- this._pointerInput = function (p, s) {
- var evt = p.event;
- if (!_this.touchEnabled && evt.pointerType === "touch") {
- return;
- }
- if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
- try {
- evt.srcElement.setPointerCapture(evt.pointerId);
- }
- catch (e) {
- }
- _this.previousPosition = {
- x: evt.clientX,
- y: evt.clientY
- };
- if (!noPreventDefault) {
- evt.preventDefault();
- }
- }
- else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
- try {
- evt.srcElement.releasePointerCapture(evt.pointerId);
- }
- catch (e) {
- }
- _this.previousPosition = null;
- if (!noPreventDefault) {
- evt.preventDefault();
- }
- }
- else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
- if (!_this.previousPosition && !engine.isPointerLock) {
- return;
- }
- var offsetX;
- var offsetY;
- if (!engine.isPointerLock) {
- offsetX = evt.clientX - _this.previousPosition.x;
- offsetY = evt.clientY - _this.previousPosition.y;
- }
- else {
- offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
- offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
- }
- camera.cameraRotation.y += offsetX / _this.angularSensibility;
- camera.cameraRotation.x += offsetY / _this.angularSensibility;
- _this.previousPosition = {
- x: evt.clientX,
- y: evt.clientY
- };
- if (!noPreventDefault) {
- evt.preventDefault();
- }
- }
- };
- }
- this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
- };
- FreeCameraMouseInput.prototype.detachControl = function (element) {
- if (this._observer && element) {
- this.camera.getScene().onPointerObservable.remove(this._observer);
- this._observer = null;
- this.previousPosition = null;
- }
- };
- FreeCameraMouseInput.prototype.getTypeName = function () {
- return "FreeCameraMouseInput";
- };
- FreeCameraMouseInput.prototype.getSimpleName = function () {
- return "mouse";
- };
- __decorate([
- BABYLON.serialize()
- ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
- return FreeCameraMouseInput;
- })();
- BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
- BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var FreeCameraKeyboardMoveInput = (function () {
- function FreeCameraKeyboardMoveInput() {
- this._keys = [];
- this.keysUp = [38];
- this.keysDown = [40];
- this.keysLeft = [37];
- this.keysRight = [39];
- }
- FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
- var _this = this;
- if (!this._onKeyDown) {
- this._onKeyDown = function (evt) {
- if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
- _this.keysDown.indexOf(evt.keyCode) !== -1 ||
- _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
- _this.keysRight.indexOf(evt.keyCode) !== -1) {
- var index = _this._keys.indexOf(evt.keyCode);
- if (index === -1) {
- _this._keys.push(evt.keyCode);
- }
- if (!noPreventDefault) {
- evt.preventDefault();
- }
- }
- };
- this._onKeyUp = function (evt) {
- if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
- _this.keysDown.indexOf(evt.keyCode) !== -1 ||
- _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
- _this.keysRight.indexOf(evt.keyCode) !== -1) {
- var index = _this._keys.indexOf(evt.keyCode);
- if (index >= 0) {
- _this._keys.splice(index, 1);
- }
- if (!noPreventDefault) {
- evt.preventDefault();
- }
- }
- };
- BABYLON.Tools.RegisterTopRootEvents([
- { name: "keydown", handler: this._onKeyDown },
- { name: "keyup", handler: this._onKeyUp },
- { name: "blur", handler: this._onLostFocus }
- ]);
- }
- };
- FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
- if (this._onKeyDown) {
- BABYLON.Tools.UnregisterTopRootEvents([
- { name: "keydown", handler: this._onKeyDown },
- { name: "keyup", handler: this._onKeyUp },
- { name: "blur", handler: this._onLostFocus }
- ]);
- this._keys = [];
- this._onKeyDown = null;
- this._onKeyUp = null;
- }
- };
- FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
- if (this._onKeyDown) {
- var camera = this.camera;
- // Keyboard
- for (var index = 0; index < this._keys.length; index++) {
- var keyCode = this._keys[index];
- var speed = camera._computeLocalCameraSpeed();
- if (this.keysLeft.indexOf(keyCode) !== -1) {
- camera._localDirection.copyFromFloats(-speed, 0, 0);
- }
- else if (this.keysUp.indexOf(keyCode) !== -1) {
- camera._localDirection.copyFromFloats(0, 0, speed);
- }
- else if (this.keysRight.indexOf(keyCode) !== -1) {
- camera._localDirection.copyFromFloats(speed, 0, 0);
- }
- else if (this.keysDown.indexOf(keyCode) !== -1) {
- camera._localDirection.copyFromFloats(0, 0, -speed);
- }
- camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
- BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
- camera.cameraDirection.addInPlace(camera._transformedDirection);
- }
- }
- };
- FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
- return "FreeCameraKeyboardMoveInput";
- };
- FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
- this._keys = [];
- };
- FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
- return "keyboard";
- };
- __decorate([
- BABYLON.serialize()
- ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
- __decorate([
- BABYLON.serialize()
- ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
- __decorate([
- BABYLON.serialize()
- ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
- __decorate([
- BABYLON.serialize()
- ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
- return FreeCameraKeyboardMoveInput;
- })();
- BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
- BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var FreeCameraTouchInput = (function () {
- function FreeCameraTouchInput() {
- this._offsetX = null;
- this._offsetY = null;
- this._pointerCount = 0;
- this._pointerPressed = [];
- this.touchAngularSensibility = 200000.0;
- this.touchMoveSensibility = 250.0;
- }
- FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
- var _this = this;
- var previousPosition;
- if (this._pointerInput === undefined) {
- this._onLostFocus = function (evt) {
- _this._offsetX = null;
- _this._offsetY = null;
- };
- this._pointerInput = function (p, s) {
- var evt = p.event;
- if (evt.pointerType === "mouse") {
- return;
- }
- if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
- if (!noPreventDefault) {
- evt.preventDefault();
- }
- _this._pointerPressed.push(evt.pointerId);
- if (_this._pointerPressed.length !== 1) {
- return;
- }
- previousPosition = {
- x: evt.clientX,
- y: evt.clientY
- };
- }
- else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
- if (!noPreventDefault) {
- evt.preventDefault();
- }
- var index = _this._pointerPressed.indexOf(evt.pointerId);
- if (index === -1) {
- return;
- }
- _this._pointerPressed.splice(index, 1);
- if (index != 0) {
- return;
- }
- previousPosition = null;
- _this._offsetX = null;
- _this._offsetY = null;
- }
- else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
- if (!noPreventDefault) {
- evt.preventDefault();
- }
- if (!previousPosition) {
- return;
- }
- var index = _this._pointerPressed.indexOf(evt.pointerId);
- if (index != 0) {
- return;
- }
- _this._offsetX = evt.clientX - previousPosition.x;
- _this._offsetY = -(evt.clientY - previousPosition.y);
- }
- };
- }
- this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
- element.addEventListener("blur", this._onLostFocus);
- };
- FreeCameraTouchInput.prototype.detachControl = function (element) {
- if (this._pointerInput && element) {
- this.camera.getScene().onPointerObservable.remove(this._observer);
- this._observer = null;
- element.removeEventListener("blur", this._onLostFocus);
- this._onLostFocus = null;
- this._pointerPressed = [];
- this._offsetX = null;
- this._offsetY = null;
- this._pointerCount = 0;
- }
- };
- FreeCameraTouchInput.prototype.checkInputs = function () {
- if (this._offsetX) {
- var camera = this.camera;
- camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
- if (this._pointerPressed.length > 1) {
- camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
- }
- else {
- var speed = camera._computeLocalCameraSpeed();
- var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
- BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
- camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
- }
- }
- };
- FreeCameraTouchInput.prototype.getTypeName = function () {
- return "FreeCameraTouchInput";
- };
- FreeCameraTouchInput.prototype.getSimpleName = function () {
- return "touch";
- };
- __decorate([
- BABYLON.serialize()
- ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
- __decorate([
- BABYLON.serialize()
- ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
- return FreeCameraTouchInput;
- })();
- BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
- BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var FreeCameraDeviceOrientationInput = (function () {
- function FreeCameraDeviceOrientationInput() {
- this._offsetX = null;
- this._offsetY = null;
- this._orientationGamma = 0;
- this._orientationBeta = 0;
- this._initialOrientationGamma = 0;
- this._initialOrientationBeta = 0;
- this.angularSensibility = 10000.0;
- this.moveSensibility = 50.0;
- this._resetOrientationGamma = this.resetOrientationGamma.bind(this);
- this._orientationChanged = this.orientationChanged.bind(this);
- }
- FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
- window.addEventListener("resize", this._resetOrientationGamma, false);
- window.addEventListener("deviceorientation", this._orientationChanged);
- };
- FreeCameraDeviceOrientationInput.prototype.resetOrientationGamma = function () {
- this._initialOrientationGamma = null;
- };
- FreeCameraDeviceOrientationInput.prototype.orientationChanged = function (evt) {
- if (!this._initialOrientationGamma) {
- this._initialOrientationGamma = evt.gamma;
- this._initialOrientationBeta = evt.beta;
- }
- this._orientationGamma = evt.gamma;
- this._orientationBeta = evt.beta;
- this._offsetY = (this._initialOrientationBeta - this._orientationBeta);
- this._offsetX = (this._initialOrientationGamma - this._orientationGamma);
- };
- FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
- window.removeEventListener("resize", this._resetOrientationGamma);
- window.removeEventListener("deviceorientation", this._orientationChanged);
- this._orientationGamma = 0;
- this._orientationBeta = 0;
- this._initialOrientationGamma = 0;
- this._initialOrientationBeta = 0;
- this._offsetX = null;
- this._offsetY = null;
- };
- FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
- if (!this._offsetX) {
- return;
- }
- var camera = this.camera;
- camera.cameraRotation.y -= this._offsetX / this.angularSensibility;
- var speed = camera._computeLocalCameraSpeed();
- var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
- BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
- camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
- };
- FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
- return "FreeCameraDeviceOrientationInput";
- };
- FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
- return "deviceOrientation";
- };
- __decorate([
- BABYLON.serialize()
- ], FreeCameraDeviceOrientationInput.prototype, "angularSensibility", void 0);
- __decorate([
- BABYLON.serialize()
- ], FreeCameraDeviceOrientationInput.prototype, "moveSensibility", void 0);
- return FreeCameraDeviceOrientationInput;
- })();
- BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
- BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var FreeCameraVRDeviceOrientationInput = (function () {
- function FreeCameraVRDeviceOrientationInput() {
- this.alphaCorrection = 1;
- this.betaCorrection = 1;
- this.gammaCorrection = 1;
- this._alpha = 0;
- this._beta = 0;
- this._gamma = 0;
- this._dirty = false;
- this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
- }
- FreeCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
- window.addEventListener("deviceorientation", this._deviceOrientationHandler);
- };
- FreeCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
- var camera = this.camera;
- this._alpha = +evt.alpha | 0;
- this._beta = +evt.beta | 0;
- this._gamma = +evt.gamma | 0;
- this._dirty = true;
- };
- FreeCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
- if (this._dirty) {
- this._dirty = false;
- var rotationX = this._gamma;
- if (rotationX < 0) {
- rotationX = 90 + rotationX;
- }
- else {
- // Incline it in the correct angle.
- rotationX = 270 - rotationX;
- }
- this.camera.rotation.x = this.gammaCorrection * rotationX / 180.0 * Math.PI;
- this.camera.rotation.y = this.alphaCorrection * -this._alpha / 180.0 * Math.PI;
- this.camera.rotation.z = this.betaCorrection * this._beta / 180.0 * Math.PI;
- }
- };
- FreeCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
- window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
- };
- FreeCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
- return "FreeCameraVRDeviceOrientationInput";
- };
- FreeCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
- return "VRDeviceOrientation";
- };
- return FreeCameraVRDeviceOrientationInput;
- })();
- BABYLON.FreeCameraVRDeviceOrientationInput = FreeCameraVRDeviceOrientationInput;
- BABYLON.CameraInputTypes["FreeCameraVRDeviceOrientationInput"] = FreeCameraVRDeviceOrientationInput;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var FreeCameraGamepadInput = (function () {
- function FreeCameraGamepadInput() {
- this.gamepadAngularSensibility = 200;
- this.gamepadMoveSensibility = 40;
- }
- FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
- var _this = this;
- this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
- };
- FreeCameraGamepadInput.prototype.detachControl = function (element) {
- if (this._gamepads) {
- this._gamepads.dispose();
- }
- this.gamepad = null;
- };
- FreeCameraGamepadInput.prototype.checkInputs = function () {
- if (this.gamepad) {
- var camera = this.camera;
- var LSValues = this.gamepad.leftStick;
- var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
- var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
- LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
- LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
- var RSValues = this.gamepad.rightStick;
- var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
- var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
- RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
- RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
- var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
- var speed = camera._computeLocalCameraSpeed() * 50.0;
- var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
- camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
- camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
- }
- };
- FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
- // Only the first gamepad can control the camera
- if (gamepad.index === 0) {
- this.gamepad = gamepad;
- }
- };
- FreeCameraGamepadInput.prototype.getTypeName = function () {
- return "FreeCameraGamepadInput";
- };
- FreeCameraGamepadInput.prototype.getSimpleName = function () {
- return "gamepad";
- };
- __decorate([
- BABYLON.serialize()
- ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
- __decorate([
- BABYLON.serialize()
- ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
- return FreeCameraGamepadInput;
- })();
- BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
- BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var FreeCameraVirtualJoystickInput = (function () {
- function FreeCameraVirtualJoystickInput() {
- }
- FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
- return this._leftjoystick;
- };
- FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
- return this._rightjoystick;
- };
- FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
- if (this._leftjoystick) {
- var camera = this.camera;
- var speed = camera._computeLocalCameraSpeed() * 50;
- var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
- var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
- camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
- camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
- if (!this._leftjoystick.pressed) {
- this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
- }
- if (!this._rightjoystick.pressed) {
- this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
- }
- }
- };
- FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
- this._leftjoystick = new BABYLON.VirtualJoystick(true);
- this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
- this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
- this._leftjoystick.setJoystickSensibility(0.15);
- this._rightjoystick = new BABYLON.VirtualJoystick(false);
- this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
- this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
- this._rightjoystick.reverseUpDown = true;
- this._rightjoystick.setJoystickSensibility(0.05);
- this._rightjoystick.setJoystickColor("yellow");
- };
- FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
- this._leftjoystick.releaseCanvas();
- this._rightjoystick.releaseCanvas();
- };
- FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
- return "FreeCameraVirtualJoystickInput";
- };
- FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
- return "virtualJoystick";
- };
- return FreeCameraVirtualJoystickInput;
- })();
- BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
- BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var ArcRotateCameraKeyboardMoveInput = (function () {
- function ArcRotateCameraKeyboardMoveInput() {
- this._keys = [];
- this.keysUp = [38];
- this.keysDown = [40];
- this.keysLeft = [37];
- this.keysRight = [39];
- }
- ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
- var _this = this;
- this._onKeyDown = function (evt) {
- if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
- _this.keysDown.indexOf(evt.keyCode) !== -1 ||
- _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
- _this.keysRight.indexOf(evt.keyCode) !== -1) {
- var index = _this._keys.indexOf(evt.keyCode);
- if (index === -1) {
- _this._keys.push(evt.keyCode);
- }
- if (evt.preventDefault) {
- if (!noPreventDefault) {
- evt.preventDefault();
- }
- }
- }
- };
- this._onKeyUp = function (evt) {
- if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
- _this.keysDown.indexOf(evt.keyCode) !== -1 ||
- _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
- _this.keysRight.indexOf(evt.keyCode) !== -1) {
- var index = _this._keys.indexOf(evt.keyCode);
- if (index >= 0) {
- _this._keys.splice(index, 1);
- }
- if (evt.preventDefault) {
- if (!noPreventDefault) {
- evt.preventDefault();
- }
- }
- }
- };
- this._onLostFocus = function () {
- _this._keys = [];
- };
- BABYLON.Tools.RegisterTopRootEvents([
- { name: "keydown", handler: this._onKeyDown },
- { name: "keyup", handler: this._onKeyUp },
- { name: "blur", handler: this._onLostFocus }
- ]);
- };
- ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
- BABYLON.Tools.UnregisterTopRootEvents([
- { name: "keydown", handler: this._onKeyDown },
- { name: "keyup", handler: this._onKeyUp },
- { name: "blur", handler: this._onLostFocus }
- ]);
- this._keys = [];
- this._onKeyDown = null;
- this._onKeyUp = null;
- this._onLostFocus = null;
- };
- ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
- if (this._onKeyDown) {
- var camera = this.camera;
- for (var index = 0; index < this._keys.length; index++) {
- var keyCode = this._keys[index];
- if (this.keysLeft.indexOf(keyCode) !== -1) {
- camera.inertialAlphaOffset -= 0.01;
- }
- else if (this.keysUp.indexOf(keyCode) !== -1) {
- camera.inertialBetaOffset -= 0.01;
- }
- else if (this.keysRight.indexOf(keyCode) !== -1) {
- camera.inertialAlphaOffset += 0.01;
- }
- else if (this.keysDown.indexOf(keyCode) !== -1) {
- camera.inertialBetaOffset += 0.01;
- }
- }
- }
- };
- ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
- return "ArcRotateCameraKeyboardMoveInput";
- };
- ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
- return "keyboard";
- };
- __decorate([
- BABYLON.serialize()
- ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
- __decorate([
- BABYLON.serialize()
- ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
- __decorate([
- BABYLON.serialize()
- ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
- __decorate([
- BABYLON.serialize()
- ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
- return ArcRotateCameraKeyboardMoveInput;
- })();
- BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
- BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var ArcRotateCameraMouseWheelInput = (function () {
- function ArcRotateCameraMouseWheelInput() {
- this.wheelPrecision = 3.0;
- }
- ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
- var _this = this;
- this._wheel = function (p, s) {
- //sanity check - this should be a PointerWheel event.
- if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
- return;
- var event = p.event;
- var delta = 0;
- if (event.wheelDelta) {
- delta = event.wheelDelta / (_this.wheelPrecision * 40);
- }
- else if (event.detail) {
- delta = -event.detail / _this.wheelPrecision;
- }
- if (delta)
- _this.camera.inertialRadiusOffset += delta;
- if (event.preventDefault) {
- if (!noPreventDefault) {
- event.preventDefault();
- }
- }
- };
- this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
- };
- ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
- if (this._observer && element) {
- this.camera.getScene().onPointerObservable.remove(this._observer);
- this._observer = null;
- this._wheel = null;
- }
- };
- ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
- return "ArcRotateCameraMouseWheelInput";
- };
- ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
- return "mousewheel";
- };
- __decorate([
- BABYLON.serialize()
- ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
- return ArcRotateCameraMouseWheelInput;
- })();
- BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
- BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var eventPrefix = BABYLON.Tools.GetPointerPrefix();
- var ArcRotateCameraPointersInput = (function () {
- function ArcRotateCameraPointersInput() {
- this.angularSensibilityX = 1000.0;
- this.angularSensibilityY = 1000.0;
- this.pinchPrecision = 6.0;
- this.panningSensibility = 50.0;
- this._isRightClick = false;
- this._isCtrlPushed = false;
- this.pinchInwards = true;
- }
- ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
- var _this = this;
- var engine = this.camera.getEngine();
- var cacheSoloPointer; // cache pointer object for better perf on camera rotation
- var pointA, pointB;
- var previousPinchDistance = 0;
- this._pointerInput = function (p, s) {
- var evt = p.event;
- if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
- try {
- evt.srcElement.setPointerCapture(evt.pointerId);
- }
- catch (e) {
- }
- // Manage panning with right click
- _this._isRightClick = evt.button === 2;
- // manage pointers
- cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
- if (pointA === undefined) {
- pointA = cacheSoloPointer;
- }
- else if (pointB === undefined) {
- pointB = cacheSoloPointer;
- }
- if (!noPreventDefault) {
- evt.preventDefault();
- }
- }
- else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
- try {
- evt.srcElement.releasePointerCapture(evt.pointerId);
- }
- catch (e) {
- }
- cacheSoloPointer = null;
- previousPinchDistance = 0;
- //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
- //but emptying completly pointers collection is required to fix a bug on iPhone :
- //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
- //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
- pointA = pointB = undefined;
- if (!noPreventDefault) {
- evt.preventDefault();
- }
- }
- else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
- if (!noPreventDefault) {
- evt.preventDefault();
- }
- // One button down
- if (pointA && pointB === undefined) {
- if (_this.panningSensibility !== 0 &&
- ((_this._isCtrlPushed && _this.camera._useCtrlForPanning) ||
- (!_this.camera._useCtrlForPanning && _this._isRightClick))) {
- _this.camera
- .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
- _this.camera
- .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
- }
- else {
- var offsetX = evt.clientX - cacheSoloPointer.x;
- var offsetY = evt.clientY - cacheSoloPointer.y;
- _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
- _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
- }
- cacheSoloPointer.x = evt.clientX;
- cacheSoloPointer.y = evt.clientY;
- }
- else if (pointA && pointB) {
- //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
- var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
- ed.x = evt.clientX;
- ed.y = evt.clientY;
- var direction = _this.pinchInwards ? 1 : -1;
- var distX = pointA.x - pointB.x;
- var distY = pointA.y - pointB.y;
- var pinchSquaredDistance = (distX * distX) + (distY * distY);
- if (previousPinchDistance === 0) {
- previousPinchDistance = pinchSquaredDistance;
- return;
- }
- if (pinchSquaredDistance !== previousPinchDistance) {
- _this.camera
- .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
- (_this.pinchPrecision *
- ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
- direction);
- previousPinchDistance = pinchSquaredDistance;
- }
- }
- }
- };
- this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
- this._onContextMenu = function (evt) {
- evt.preventDefault();
- };
- if (!this.camera._useCtrlForPanning) {
- element.addEventListener("contextmenu", this._onContextMenu, false);
- }
- this._onLostFocus = function () {
- //this._keys = [];
- pointA = pointB = undefined;
- previousPinchDistance = 0;
- cacheSoloPointer = null;
- };
- this._onKeyDown = function (evt) {
- _this._isCtrlPushed = evt.ctrlKey;
- };
- this._onKeyUp = function (evt) {
- _this._isCtrlPushed = evt.ctrlKey;
- };
- this._onMouseMove = function (evt) {
- if (!engine.isPointerLock) {
- return;
- }
- var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
- var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
- _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
- _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
- if (!noPreventDefault) {
- evt.preventDefault();
- }
- };
- this._onGestureStart = function (e) {
- if (window.MSGesture === undefined) {
- return;
- }
- if (!_this._MSGestureHandler) {
- _this._MSGestureHandler = new MSGesture();
- _this._MSGestureHandler.target = element;
- }
- _this._MSGestureHandler.addPointer(e.pointerId);
- };
- this._onGesture = function (e) {
- _this.camera.radius *= e.scale;
- if (e.preventDefault) {
- if (!noPreventDefault) {
- e.stopPropagation();
- e.preventDefault();
- }
- }
- };
- element.addEventListener("mousemove", this._onMouseMove, false);
- element.addEventListener("MSPointerDown", this._onGestureStart, false);
- element.addEventListener("MSGestureChange", this._onGesture, false);
- BABYLON.Tools.RegisterTopRootEvents([
- { name: "keydown", handler: this._onKeyDown },
- { name: "keyup", handler: this._onKeyUp },
- { name: "blur", handler: this._onLostFocus }
- ]);
- };
- ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
- if (element && this._observer) {
- this.camera.getScene().onPointerObservable.remove(this._observer);
- this._observer = null;
- element.removeEventListener("contextmenu", this._onContextMenu);
- element.removeEventListener("mousemove", this._onMouseMove);
- element.removeEventListener("MSPointerDown", this._onGestureStart);
- element.removeEventListener("MSGestureChange", this._onGesture);
- this._isRightClick = false;
- this._isCtrlPushed = false;
- this.pinchInwards = true;
- this._onKeyDown = null;
- this._onKeyUp = null;
- this._onMouseMove = null;
- this._onGestureStart = null;
- this._onGesture = null;
- this._MSGestureHandler = null;
- this._onLostFocus = null;
- this._onContextMenu = null;
- }
- BABYLON.Tools.UnregisterTopRootEvents([
- { name: "keydown", handler: this._onKeyDown },
- { name: "keyup", handler: this._onKeyUp },
- { name: "blur", handler: this._onLostFocus }
- ]);
- };
- ArcRotateCameraPointersInput.prototype.getTypeName = function () {
- return "ArcRotateCameraPointersInput";
- };
- ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
- return "pointers";
- };
- __decorate([
- BABYLON.serialize()
- ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
- __decorate([
- BABYLON.serialize()
- ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
- __decorate([
- BABYLON.serialize()
- ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
- __decorate([
- BABYLON.serialize()
- ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
- return ArcRotateCameraPointersInput;
- })();
- BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
- BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var ArcRotateCameraGamepadInput = (function () {
- function ArcRotateCameraGamepadInput() {
- this.gamepadRotationSensibility = 80;
- this.gamepadMoveSensibility = 40;
- }
- ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
- var _this = this;
- this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
- };
- ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
- if (this._gamepads) {
- this._gamepads.dispose();
- }
- this.gamepad = null;
- };
- ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
- if (this.gamepad) {
- var camera = this.camera;
- var RSValues = this.gamepad.rightStick;
- if (RSValues.x != 0) {
- var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
- if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
- camera.inertialAlphaOffset += normalizedRX;
- }
- }
- if (RSValues.y != 0) {
- var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
- if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
- camera.inertialBetaOffset += normalizedRY;
- }
- }
- var LSValues = this.gamepad.leftStick;
- if (LSValues.y != 0) {
- var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
- if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
- this.camera.inertialRadiusOffset -= normalizedLY;
- }
- }
- }
- };
- ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
- // Only the first gamepad can control the camera
- if (gamepad.index === 0) {
- this.gamepad = gamepad;
- }
- };
- ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
- return "ArcRotateCameraGamepadInput";
- };
- ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
- return "gamepad";
- };
- __decorate([
- BABYLON.serialize()
- ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
- __decorate([
- BABYLON.serialize()
- ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
- return ArcRotateCameraGamepadInput;
- })();
- BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
- BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var ArcRotateCameraVRDeviceOrientationInput = (function () {
- function ArcRotateCameraVRDeviceOrientationInput() {
- this.alphaCorrection = 1;
- this.betaCorrection = 1;
- this.gammaCorrection = 1;
- this._alpha = 0;
- this._beta = 0;
- this._gamma = 0;
- this._dirty = false;
- this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
- }
- ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
- this.camera.attachControl(element, noPreventDefault);
- window.addEventListener("deviceorientation", this._deviceOrientationHandler);
- };
- ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
- var camera = this.camera;
- this._alpha = +evt.alpha | 0;
- this._beta = +evt.beta | 0;
- this._gamma = +evt.gamma | 0;
- this._dirty = true;
- };
- ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
- if (this._dirty) {
- this._dirty = false;
- if (this._gamma < 0) {
- this._gamma = 180 + this._gamma;
- }
- this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
- this.camera.beta = (this._gamma / 180.0 * Math.PI);
- }
- };
- ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
- window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
- };
- ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
- return "ArcRotateCameraVRDeviceOrientationInput";
- };
- ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
- return "VRDeviceOrientation";
- };
- return ArcRotateCameraVRDeviceOrientationInput;
- })();
- BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
- BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var TargetCamera = (function (_super) {
- __extends(TargetCamera, _super);
- function TargetCamera(name, position, scene) {
- _super.call(this, name, position, scene);
- this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
- this.cameraRotation = new BABYLON.Vector2(0, 0);
- this.rotation = new BABYLON.Vector3(0, 0, 0);
- this.speed = 2.0;
- this.noRotationConstraint = false;
- this.lockedTarget = null;
- this._currentTarget = BABYLON.Vector3.Zero();
- this._viewMatrix = BABYLON.Matrix.Zero();
- this._camMatrix = BABYLON.Matrix.Zero();
- this._cameraTransformMatrix = BABYLON.Matrix.Zero();
- this._cameraRotationMatrix = BABYLON.Matrix.Zero();
- this._referencePoint = new BABYLON.Vector3(0, 0, 1);
- this._transformedReferencePoint = BABYLON.Vector3.Zero();
- this._lookAtTemp = BABYLON.Matrix.Zero();
- this._tempMatrix = BABYLON.Matrix.Zero();
- }
- TargetCamera.prototype.getFrontPosition = function (distance) {
- var direction = this.getTarget().subtract(this.position);
- direction.normalize();
- direction.scaleInPlace(distance);
- return this.globalPosition.add(direction);
- };
- TargetCamera.prototype._getLockedTargetPosition = function () {
- if (!this.lockedTarget) {
- return null;
- }
- return this.lockedTarget.position || this.lockedTarget;
- };
- // Cache
- TargetCamera.prototype._initCache = function () {
- _super.prototype._initCache.call(this);
- this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
- this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
- };
- TargetCamera.prototype._updateCache = function (ignoreParentClass) {
- if (!ignoreParentClass) {
- _super.prototype._updateCache.call(this);
- }
- var lockedTargetPosition = this._getLockedTargetPosition();
- if (!lockedTargetPosition) {
- this._cache.lockedTarget = null;
- }
- else {
- if (!this._cache.lockedTarget) {
- this._cache.lockedTarget = lockedTargetPosition.clone();
- }
- else {
- this._cache.lockedTarget.copyFrom(lockedTargetPosition);
- }
- }
- this._cache.rotation.copyFrom(this.rotation);
- };
- // Synchronized
- TargetCamera.prototype._isSynchronizedViewMatrix = function () {
- if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
- return false;
- }
- var lockedTargetPosition = this._getLockedTargetPosition();
- return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
- && this._cache.rotation.equals(this.rotation);
- };
- // Methods
- TargetCamera.prototype._computeLocalCameraSpeed = function () {
- var engine = this.getEngine();
- return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
- };
- // Target
- TargetCamera.prototype.setTarget = function (target) {
- this.upVector.normalize();
- BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
- this._camMatrix.invert();
- this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
- var vDir = target.subtract(this.position);
- if (vDir.x >= 0.0) {
- this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
- }
- else {
- this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
- }
- this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
- if (isNaN(this.rotation.x)) {
- this.rotation.x = 0;
- }
- if (isNaN(this.rotation.y)) {
- this.rotation.y = 0;
- }
- if (isNaN(this.rotation.z)) {
- this.rotation.z = 0;
- }
- };
- TargetCamera.prototype.getTarget = function () {
- return this._currentTarget;
- };
- TargetCamera.prototype._decideIfNeedsToMove = function () {
- return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
- };
- TargetCamera.prototype._updatePosition = function () {
- this.position.addInPlace(this.cameraDirection);
- };
- TargetCamera.prototype._checkInputs = function () {
- var needToMove = this._decideIfNeedsToMove();
- var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
- // Move
- if (needToMove) {
- this._updatePosition();
- }
- // Rotate
- if (needToRotate) {
- this.rotation.x += this.cameraRotation.x;
- this.rotation.y += this.cameraRotation.y;
- if (!this.noRotationConstraint) {
- var limit = (Math.PI / 2) * 0.95;
- if (this.rotation.x > limit)
- this.rotation.x = limit;
- if (this.rotation.x < -limit)
- this.rotation.x = -limit;
- }
- }
- // Inertia
- if (needToMove) {
- if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
- this.cameraDirection.x = 0;
- }
- if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
- this.cameraDirection.y = 0;
- }
- if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
- this.cameraDirection.z = 0;
- }
- this.cameraDirection.scaleInPlace(this.inertia);
- }
- if (needToRotate) {
- if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
- this.cameraRotation.x = 0;
- }
- if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
- this.cameraRotation.y = 0;
- }
- this.cameraRotation.scaleInPlace(this.inertia);
- }
- _super.prototype._checkInputs.call(this);
- };
- TargetCamera.prototype._getViewMatrix = function () {
- if (!this.lockedTarget) {
- // Compute
- if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
- BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
- BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
- this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
- this._lookAtTemp.invert();
- this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
- }
- else {
- BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
- }
- BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
- // Computing target and final matrix
- this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
- }
- else {
- this._currentTarget.copyFrom(this._getLockedTargetPosition());
- }
- BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
- return this._viewMatrix;
- };
- TargetCamera.prototype._getVRViewMatrix = function () {
- BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
- BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
- BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
- // Computing target and final matrix
- this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
- BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
- this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
- return this._viewMatrix;
- };
- /**
- * @override
- * Override Camera.createRigCamera
- */
- TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
- if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
- var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
- if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
- rigCamera._cameraRigParams = {};
- rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
- rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
- }
- return rigCamera;
- }
- return null;
- };
- /**
- * @override
- * Override Camera._updateRigCameras
- */
- TargetCamera.prototype._updateRigCameras = function () {
- switch (this.cameraRigMode) {
- case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
- case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
- case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
- case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
- case BABYLON.Camera.RIG_MODE_VR:
- var camLeft = this._rigCameras[0];
- var camRight = this._rigCameras[1];
- if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
- camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
- camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
- camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
- camLeft.position.copyFrom(this.position);
- camRight.position.copyFrom(this.position);
- }
- else {
- //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
- this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
- this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
- camLeft.setTarget(this.getTarget());
- camRight.setTarget(this.getTarget());
- }
- break;
- }
- _super.prototype._updateRigCameras.call(this);
- };
- TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
- if (!this._rigCamTransformMatrix) {
- this._rigCamTransformMatrix = new BABYLON.Matrix();
- }
- var target = this.getTarget();
- BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
- this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
- BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
- };
- TargetCamera.prototype.getTypeName = function () {
- return "TargetCamera";
- };
- __decorate([
- BABYLON.serializeAsVector3()
- ], TargetCamera.prototype, "rotation", void 0);
- __decorate([
- BABYLON.serialize()
- ], TargetCamera.prototype, "speed", void 0);
- __decorate([
- BABYLON.serializeAsMeshReference("lockedTargetId")
- ], TargetCamera.prototype, "lockedTarget", void 0);
- return TargetCamera;
- })(BABYLON.Camera);
- BABYLON.TargetCamera = TargetCamera;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var FreeCamera = (function (_super) {
- __extends(FreeCamera, _super);
- function FreeCamera(name, position, scene) {
- var _this = this;
- _super.call(this, name, position, scene);
- this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
- this.checkCollisions = false;
- this.applyGravity = false;
- this._collider = new BABYLON.Collider();
- this._needMoveForGravity = false;
- this._oldPosition = BABYLON.Vector3.Zero();
- this._diffPosition = BABYLON.Vector3.Zero();
- this._newPosition = BABYLON.Vector3.Zero();
- this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
- if (collidedMesh === void 0) { collidedMesh = null; }
- //TODO move this to the collision coordinator!
- if (_this.getScene().workerCollisions)
- newPosition.multiplyInPlace(_this._collider.radius);
- var updatePosition = function (newPos) {
- _this._newPosition.copyFrom(newPos);
- _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
- var oldPosition = _this.position.clone();
- if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
- _this.position.addInPlace(_this._diffPosition);
- if (_this.onCollide && collidedMesh) {
- _this.onCollide(collidedMesh);
- }
- }
- };
- updatePosition(newPosition);
- };
- this.inputs = new BABYLON.FreeCameraInputsManager(this);
- this.inputs.addKeyboard().addMouse();
- }
- Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
- //-- begin properties for backward compatibility for inputs
- get: function () {
- var mouse = this.inputs.attached["mouse"];
- if (mouse)
- return mouse.angularSensibility;
- },
- set: function (value) {
- var mouse = this.inputs.attached["mouse"];
- if (mouse)
- mouse.angularSensibility = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(FreeCamera.prototype, "keysUp", {
- get: function () {
- var keyboard = this.inputs.attached["keyboard"];
- if (keyboard)
- return keyboard.keysUp;
- },
- set: function (value) {
- var keyboard = this.inputs.attached["keyboard"];
- if (keyboard)
- keyboard.keysUp = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(FreeCamera.prototype, "keysDown", {
- get: function () {
- var keyboard = this.inputs.attached["keyboard"];
- if (keyboard)
- return keyboard.keysDown;
- },
- set: function (value) {
- var keyboard = this.inputs.attached["keyboard"];
- if (keyboard)
- keyboard.keysDown = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(FreeCamera.prototype, "keysLeft", {
- get: function () {
- var keyboard = this.inputs.attached["keyboard"];
- if (keyboard)
- return keyboard.keysLeft;
- },
- set: function (value) {
- var keyboard = this.inputs.attached["keyboard"];
- if (keyboard)
- keyboard.keysLeft = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(FreeCamera.prototype, "keysRight", {
- get: function () {
- var keyboard = this.inputs.attached["keyboard"];
- if (keyboard)
- return keyboard.keysRight;
- },
- set: function (value) {
- var keyboard = this.inputs.attached["keyboard"];
- if (keyboard)
- keyboard.keysRight = value;
- },
- enumerable: true,
- configurable: true
- });
- // Controls
- FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
- this.inputs.attachElement(element, noPreventDefault);
- };
- FreeCamera.prototype.detachControl = function (element) {
- this.inputs.detachElement(element);
- this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
- this.cameraRotation = new BABYLON.Vector2(0, 0);
- };
- FreeCamera.prototype._collideWithWorld = function (velocity) {
- var globalPosition;
- if (this.parent) {
- globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
- }
- else {
- globalPosition = this.position;
- }
- globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
- this._collider.radius = this.ellipsoid;
- //no need for clone, as long as gravity is not on.
- var actualVelocity = velocity;
- //add gravity to the velocity to prevent the dual-collision checking
- if (this.applyGravity) {
- //this prevents mending with cameraDirection, a global variable of the free camera class.
- actualVelocity = velocity.add(this.getScene().gravity);
- }
- this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
- };
- FreeCamera.prototype._checkInputs = function () {
- if (!this._localDirection) {
- this._localDirection = BABYLON.Vector3.Zero();
- this._transformedDirection = BABYLON.Vector3.Zero();
- }
- this.inputs.checkInputs();
- _super.prototype._checkInputs.call(this);
- };
- FreeCamera.prototype._decideIfNeedsToMove = function () {
- return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
- };
- FreeCamera.prototype._updatePosition = function () {
- if (this.checkCollisions && this.getScene().collisionsEnabled) {
- this._collideWithWorld(this.cameraDirection);
- }
- else {
- this.position.addInPlace(this.cameraDirection);
- }
- };
- FreeCamera.prototype.dispose = function () {
- this.inputs.clear();
- _super.prototype.dispose.call(this);
- };
- FreeCamera.prototype.getTypeName = function () {
- return "FreeCamera";
- };
- __decorate([
- BABYLON.serializeAsVector3()
- ], FreeCamera.prototype, "ellipsoid", void 0);
- __decorate([
- BABYLON.serialize()
- ], FreeCamera.prototype, "checkCollisions", void 0);
- __decorate([
- BABYLON.serialize()
- ], FreeCamera.prototype, "applyGravity", void 0);
- return FreeCamera;
- })(BABYLON.TargetCamera);
- BABYLON.FreeCamera = FreeCamera;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var FreeCameraInputsManager = (function (_super) {
- __extends(FreeCameraInputsManager, _super);
- function FreeCameraInputsManager(camera) {
- _super.call(this, camera);
- }
- FreeCameraInputsManager.prototype.addKeyboard = function () {
- this.add(new BABYLON.FreeCameraKeyboardMoveInput());
- return this;
- };
- FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
- if (touchEnabled === void 0) { touchEnabled = true; }
- this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
- return this;
- };
- FreeCameraInputsManager.prototype.addGamepad = function () {
- this.add(new BABYLON.FreeCameraGamepadInput());
- return this;
- };
- FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
- this.add(new BABYLON.FreeCameraDeviceOrientationInput());
- return this;
- };
- FreeCameraInputsManager.prototype.addVRDeviceOrientation = function () {
- this.add(new BABYLON.FreeCameraVRDeviceOrientationInput());
- return this;
- };
- FreeCameraInputsManager.prototype.addTouch = function () {
- this.add(new BABYLON.FreeCameraTouchInput());
- return this;
- };
- FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
- this.add(new BABYLON.FreeCameraVirtualJoystickInput());
- return this;
- };
- return FreeCameraInputsManager;
- })(BABYLON.CameraInputsManager);
- BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var FollowCamera = (function (_super) {
- __extends(FollowCamera, _super);
- function FollowCamera(name, position, scene, target) {
- _super.call(this, name, position, scene);
- this.radius = 12;
- this.rotationOffset = 0;
- this.heightOffset = 4;
- this.cameraAcceleration = 0.05;
- this.maxCameraSpeed = 20;
- this.target = target;
- }
- FollowCamera.prototype.getRadians = function (degrees) {
- return degrees * Math.PI / 180;
- };
- FollowCamera.prototype.follow = function (cameraTarget) {
- if (!cameraTarget)
- return;
- var yRotation;
- if (cameraTarget.rotationQuaternion) {
- var rotMatrix = new BABYLON.Matrix();
- cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
- yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
- }
- else {
- yRotation = cameraTarget.rotation.y;
- }
- var radians = this.getRadians(this.rotationOffset) + yRotation;
- var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
- var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
- var dx = targetX - this.position.x;
- var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
- var dz = (targetZ) - this.position.z;
- var vx = dx * this.cameraAcceleration * 2; //this is set to .05
- var vy = dy * this.cameraAcceleration;
- var vz = dz * this.cameraAcceleration * 2;
- if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
- vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
- }
- if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
- vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
- }
- if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
- vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
- }
- this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
- this.setTarget(cameraTarget.position);
- };
- FollowCamera.prototype._checkInputs = function () {
- _super.prototype._checkInputs.call(this);
- this.follow(this.target);
- };
- FollowCamera.prototype.getTypeName = function () {
- return "FollowCamera";
- };
- __decorate([
- BABYLON.serialize()
- ], FollowCamera.prototype, "radius", void 0);
- __decorate([
- BABYLON.serialize()
- ], FollowCamera.prototype, "rotationOffset", void 0);
- __decorate([
- BABYLON.serialize()
- ], FollowCamera.prototype, "heightOffset", void 0);
- __decorate([
- BABYLON.serialize()
- ], FollowCamera.prototype, "cameraAcceleration", void 0);
- __decorate([
- BABYLON.serialize()
- ], FollowCamera.prototype, "maxCameraSpeed", void 0);
- __decorate([
- BABYLON.serializeAsMeshReference("lockedTargetId")
- ], FollowCamera.prototype, "target", void 0);
- return FollowCamera;
- })(BABYLON.TargetCamera);
- BABYLON.FollowCamera = FollowCamera;
- var ArcFollowCamera = (function (_super) {
- __extends(ArcFollowCamera, _super);
- function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
- _super.call(this, name, BABYLON.Vector3.Zero(), scene);
- this.alpha = alpha;
- this.beta = beta;
- this.radius = radius;
- this.target = target;
- this._cartesianCoordinates = BABYLON.Vector3.Zero();
- this.follow();
- }
- ArcFollowCamera.prototype.follow = function () {
- this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
- this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
- this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
- this.position = this.target.position.add(this._cartesianCoordinates);
- this.setTarget(this.target.position);
- };
- ArcFollowCamera.prototype._checkInputs = function () {
- _super.prototype._checkInputs.call(this);
- this.follow();
- };
- ArcFollowCamera.prototype.getTypeName = function () {
- return "ArcFollowCamera";
- };
- return ArcFollowCamera;
- })(BABYLON.TargetCamera);
- BABYLON.ArcFollowCamera = ArcFollowCamera;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- // We're mainly based on the logic defined into the FreeCamera code
- var TouchCamera = (function (_super) {
- __extends(TouchCamera, _super);
- //-- end properties for backward compatibility for inputs
- function TouchCamera(name, position, scene) {
- _super.call(this, name, position, scene);
- this.inputs.addTouch();
- this._setupInputs();
- }
- Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
- //-- Begin properties for backward compatibility for inputs
- get: function () {
- var touch = this.inputs.attached["touch"];
- if (touch)
- return touch.touchAngularSensibility;
- },
- set: function (value) {
- var touch = this.inputs.attached["touch"];
- if (touch)
- touch.touchAngularSensibility = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
- get: function () {
- var touch = this.inputs.attached["touch"];
- if (touch)
- return touch.touchMoveSensibility;
- },
- set: function (value) {
- var touch = this.inputs.attached["touch"];
- if (touch)
- touch.touchMoveSensibility = value;
- },
- enumerable: true,
- configurable: true
- });
- TouchCamera.prototype.getTypeName = function () {
- return "TouchCamera";
- };
- TouchCamera.prototype._setupInputs = function () {
- var mouse = this.inputs.attached["mouse"];
- if (mouse) {
- mouse.touchEnabled = false;
- }
- };
- return TouchCamera;
- })(BABYLON.FreeCamera);
- BABYLON.TouchCamera = TouchCamera;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var ArcRotateCamera = (function (_super) {
- __extends(ArcRotateCamera, _super);
- function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
- var _this = this;
- _super.call(this, name, BABYLON.Vector3.Zero(), scene);
- this.inertialAlphaOffset = 0;
- this.inertialBetaOffset = 0;
- this.inertialRadiusOffset = 0;
- this.lowerAlphaLimit = null;
- this.upperAlphaLimit = null;
- this.lowerBetaLimit = 0.01;
- this.upperBetaLimit = Math.PI;
- this.lowerRadiusLimit = null;
- this.upperRadiusLimit = null;
- this.inertialPanningX = 0;
- this.inertialPanningY = 0;
- //-- end properties for backward compatibility for inputs
- this.zoomOnFactor = 1;
- this.targetScreenOffset = BABYLON.Vector2.Zero();
- this.allowUpsideDown = true;
- this._viewMatrix = new BABYLON.Matrix();
- // Panning
- this.panningAxis = new BABYLON.Vector3(1, 1, 0);
- this.checkCollisions = false;
- this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
- this._collider = new BABYLON.Collider();
- this._previousPosition = BABYLON.Vector3.Zero();
- this._collisionVelocity = BABYLON.Vector3.Zero();
- this._newPosition = BABYLON.Vector3.Zero();
- this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
- if (collidedMesh === void 0) { collidedMesh = null; }
- if (_this.getScene().workerCollisions && _this.checkCollisions) {
- newPosition.multiplyInPlace(_this._collider.radius);
- }
- if (!collidedMesh) {
- _this._previousPosition.copyFrom(_this.position);
- }
- else {
- _this.setPosition(newPosition);
- if (_this.onCollide) {
- _this.onCollide(collidedMesh);
- }
- }
- // Recompute because of constraints
- var cosa = Math.cos(_this.alpha);
- var sina = Math.sin(_this.alpha);
- var cosb = Math.cos(_this.beta);
- var sinb = Math.sin(_this.beta);
- if (sinb === 0) {
- sinb = 0.0001;
- }
- var target = _this._getTargetPosition();
- target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
- _this.position.copyFrom(_this._newPosition);
- var up = _this.upVector;
- if (_this.allowUpsideDown && _this.beta < 0) {
- up = up.clone();
- up = up.negate();
- }
- BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
- _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
- _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
- _this._collisionTriggered = false;
- };
- if (!target) {
- this.target = BABYLON.Vector3.Zero();
- }
- else {
- this.target = target;
- }
- this.alpha = alpha;
- this.beta = beta;
- this.radius = radius;
- this.getViewMatrix();
- this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
- this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
- }
- Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
- //-- begin properties for backward compatibility for inputs
- get: function () {
- var pointers = this.inputs.attached["pointers"];
- if (pointers)
- return pointers.angularSensibilityX;
- },
- set: function (value) {
- var pointers = this.inputs.attached["pointers"];
- if (pointers) {
- pointers.angularSensibilityX = value;
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
- get: function () {
- var pointers = this.inputs.attached["pointers"];
- if (pointers)
- return pointers.angularSensibilityY;
- },
- set: function (value) {
- var pointers = this.inputs.attached["pointers"];
- if (pointers) {
- pointers.angularSensibilityY = value;
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
- get: function () {
- var pointers = this.inputs.attached["pointers"];
- if (pointers)
- return pointers.pinchPrecision;
- },
- set: function (value) {
- var pointers = this.inputs.attached["pointers"];
- if (pointers) {
- pointers.pinchPrecision = value;
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
- get: function () {
- var pointers = this.inputs.attached["pointers"];
- if (pointers)
- return pointers.panningSensibility;
- },
- set: function (value) {
- var pointers = this.inputs.attached["pointers"];
- if (pointers) {
- pointers.panningSensibility = value;
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
- get: function () {
- var keyboard = this.inputs.attached["keyboard"];
- if (keyboard)
- return keyboard.keysUp;
- },
- set: function (value) {
- var keyboard = this.inputs.attached["keyboard"];
- if (keyboard)
- keyboard.keysUp = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
- get: function () {
- var keyboard = this.inputs.attached["keyboard"];
- if (keyboard)
- return keyboard.keysDown;
- },
- set: function (value) {
- var keyboard = this.inputs.attached["keyboard"];
- if (keyboard)
- keyboard.keysDown = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
- get: function () {
- var keyboard = this.inputs.attached["keyboard"];
- if (keyboard)
- return keyboard.keysLeft;
- },
- set: function (value) {
- var keyboard = this.inputs.attached["keyboard"];
- if (keyboard)
- keyboard.keysLeft = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
- get: function () {
- var keyboard = this.inputs.attached["keyboard"];
- if (keyboard)
- return keyboard.keysRight;
- },
- set: function (value) {
- var keyboard = this.inputs.attached["keyboard"];
- if (keyboard)
- keyboard.keysRight = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
- get: function () {
- var mousewheel = this.inputs.attached["mousewheel"];
- if (mousewheel)
- return mousewheel.wheelPrecision;
- },
- set: function (value) {
- var mousewheel = this.inputs.attached["mousewheel"];
- if (mousewheel)
- mousewheel.wheelPrecision = value;
- },
- enumerable: true,
- configurable: true
- });
- // Cache
- ArcRotateCamera.prototype._initCache = function () {
- _super.prototype._initCache.call(this);
- this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
- this._cache.alpha = undefined;
- this._cache.beta = undefined;
- this._cache.radius = undefined;
- this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
- };
- ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
- if (!ignoreParentClass) {
- _super.prototype._updateCache.call(this);
- }
- this._cache.target.copyFrom(this._getTargetPosition());
- this._cache.alpha = this.alpha;
- this._cache.beta = this.beta;
- this._cache.radius = this.radius;
- this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
- };
- ArcRotateCamera.prototype._getTargetPosition = function () {
- if (this.target.getAbsolutePosition) {
- return this.target.getAbsolutePosition();
- }
- return this.target;
- };
- // Synchronized
- ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
- if (!_super.prototype._isSynchronizedViewMatrix.call(this))
- return false;
- return this._cache.target.equals(this.target)
- && this._cache.alpha === this.alpha
- && this._cache.beta === this.beta
- && this._cache.radius === this.radius
- && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
- };
- // Methods
- ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
- var _this = this;
- if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
- this._useCtrlForPanning = useCtrlForPanning;
- this.inputs.attachElement(element, noPreventDefault);
- this._reset = function () {
- _this.inertialAlphaOffset = 0;
- _this.inertialBetaOffset = 0;
- _this.inertialRadiusOffset = 0;
- };
- };
- ArcRotateCamera.prototype.detachControl = function (element) {
- this.inputs.detachElement(element);
- if (this._reset) {
- this._reset();
- }
- };
- ArcRotateCamera.prototype._checkInputs = function () {
- //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
- if (this._collisionTriggered) {
- return;
- }
- this.inputs.checkInputs();
- // Inertia
- if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
- this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
- this.beta += this.inertialBetaOffset;
- this.radius -= this.inertialRadiusOffset;
- this.inertialAlphaOffset *= this.inertia;
- this.inertialBetaOffset *= this.inertia;
- this.inertialRadiusOffset *= this.inertia;
- if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
- this.inertialAlphaOffset = 0;
- if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
- this.inertialBetaOffset = 0;
- if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
- this.inertialRadiusOffset = 0;
- }
- // Panning inertia
- if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
- if (!this._localDirection) {
- this._localDirection = BABYLON.Vector3.Zero();
- this._transformedDirection = BABYLON.Vector3.Zero();
- }
- this.inertialPanningX *= this.inertia;
- this.inertialPanningY *= this.inertia;
- if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
- this.inertialPanningX = 0;
- if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
- this.inertialPanningY = 0;
- this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
- this._localDirection.multiplyInPlace(this.panningAxis);
- this._viewMatrix.invertToRef(this._cameraTransformMatrix);
- BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
- //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
- if (!this.panningAxis.y) {
- this._transformedDirection.y = 0;
- }
- this.target.addInPlace(this._transformedDirection);
- }
- // Limits
- this._checkLimits();
- _super.prototype._checkInputs.call(this);
- };
- ArcRotateCamera.prototype._checkLimits = function () {
- if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
- if (this.allowUpsideDown && this.beta > Math.PI) {
- this.beta = this.beta - (2 * Math.PI);
- }
- }
- else {
- if (this.beta < this.lowerBetaLimit) {
- this.beta = this.lowerBetaLimit;
- }
- }
- if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
- if (this.allowUpsideDown && this.beta < -Math.PI) {
- this.beta = this.beta + (2 * Math.PI);
- }
- }
- else {
- if (this.beta > this.upperBetaLimit) {
- this.beta = this.upperBetaLimit;
- }
- }
- if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
- this.alpha = this.lowerAlphaLimit;
- }
- if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
- this.alpha = this.upperAlphaLimit;
- }
- if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
- this.radius = this.lowerRadiusLimit;
- }
- if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
- this.radius = this.upperRadiusLimit;
- }
- };
- ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
- var radiusv3 = this.position.subtract(this._getTargetPosition());
- this.radius = radiusv3.length();
- // Alpha
- this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
- if (radiusv3.z < 0) {
- this.alpha = 2 * Math.PI - this.alpha;
- }
- // Beta
- this.beta = Math.acos(radiusv3.y / this.radius);
- this._checkLimits();
- };
- ArcRotateCamera.prototype.setPosition = function (position) {
- if (this.position.equals(position)) {
- return;
- }
- this.position = position;
- this.rebuildAnglesAndRadius();
- };
- ArcRotateCamera.prototype.setTarget = function (target) {
- if (this._getTargetPosition().equals(target)) {
- return;
- }
- this.target = target;
- this.rebuildAnglesAndRadius();
- };
- ArcRotateCamera.prototype._getViewMatrix = function () {
- // Compute
- var cosa = Math.cos(this.alpha);
- var sina = Math.sin(this.alpha);
- var cosb = Math.cos(this.beta);
- var sinb = Math.sin(this.beta);
- if (sinb === 0) {
- sinb = 0.0001;
- }
- var target = this._getTargetPosition();
- target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
- if (this.getScene().collisionsEnabled && this.checkCollisions) {
- this._collider.radius = this.collisionRadius;
- this._newPosition.subtractToRef(this.position, this._collisionVelocity);
- this._collisionTriggered = true;
- this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
- }
- else {
- this.position.copyFrom(this._newPosition);
- var up = this.upVector;
- if (this.allowUpsideDown && this.beta < 0) {
- up = up.clone();
- up = up.negate();
- }
- BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
- this._viewMatrix.m[12] += this.targetScreenOffset.x;
- this._viewMatrix.m[13] += this.targetScreenOffset.y;
- }
- return this._viewMatrix;
- };
- ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
- if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
- meshes = meshes || this.getScene().meshes;
- var minMaxVector = BABYLON.Mesh.MinMax(meshes);
- var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
- this.radius = distance * this.zoomOnFactor;
- this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
- };
- ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
- if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
- var meshesOrMinMaxVector;
- var distance;
- if (meshesOrMinMaxVectorAndDistance.min === undefined) {
- meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
- meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
- distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
- }
- else {
- meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
- distance = meshesOrMinMaxVectorAndDistance.distance;
- }
- this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
- if (!doNotUpdateMaxZ) {
- this.maxZ = distance * 2;
- }
- };
- /**
- * @override
- * Override Camera.createRigCamera
- */
- ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
- switch (this.cameraRigMode) {
- case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
- case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
- case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
- case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
- case BABYLON.Camera.RIG_MODE_VR:
- var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
- var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
- rigCam._cameraRigParams = {};
- return rigCam;
- }
- return null;
- };
- /**
- * @override
- * Override Camera._updateRigCameras
- */
- ArcRotateCamera.prototype._updateRigCameras = function () {
- switch (this.cameraRigMode) {
- case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
- case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
- case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
- case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
- case BABYLON.Camera.RIG_MODE_VR:
- var camLeft = this._rigCameras[0];
- var camRight = this._rigCameras[1];
- camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
- camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
- camLeft.beta = camRight.beta = this.beta;
- camLeft.radius = camRight.radius = this.radius;
- break;
- }
- _super.prototype._updateRigCameras.call(this);
- };
- ArcRotateCamera.prototype.dispose = function () {
- this.inputs.clear();
- _super.prototype.dispose.call(this);
- };
- ArcRotateCamera.prototype.getTypeName = function () {
- return "ArcRotateCamera";
- };
- __decorate([
- BABYLON.serialize()
- ], ArcRotateCamera.prototype, "alpha", void 0);
- __decorate([
- BABYLON.serialize()
- ], ArcRotateCamera.prototype, "beta", void 0);
- __decorate([
- BABYLON.serialize()
- ], ArcRotateCamera.prototype, "radius", void 0);
- __decorate([
- BABYLON.serializeAsVector3()
- ], ArcRotateCamera.prototype, "target", void 0);
- __decorate([
- BABYLON.serialize()
- ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
- __decorate([
- BABYLON.serialize()
- ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
- __decorate([
- BABYLON.serialize()
- ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
- __decorate([
- BABYLON.serialize()
- ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
- __decorate([
- BABYLON.serialize()
- ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
- __decorate([
- BABYLON.serialize()
- ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
- __decorate([
- BABYLON.serialize()
- ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
- __decorate([
- BABYLON.serialize()
- ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
- __decorate([
- BABYLON.serialize()
- ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
- __decorate([
- BABYLON.serialize()
- ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
- __decorate([
- BABYLON.serialize()
- ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
- __decorate([
- BABYLON.serialize()
- ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
- __decorate([
- BABYLON.serialize()
- ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
- return ArcRotateCamera;
- })(BABYLON.TargetCamera);
- BABYLON.ArcRotateCamera = ArcRotateCamera;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var ArcRotateCameraInputsManager = (function (_super) {
- __extends(ArcRotateCameraInputsManager, _super);
- function ArcRotateCameraInputsManager(camera) {
- _super.call(this, camera);
- }
- ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
- this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
- return this;
- };
- ArcRotateCameraInputsManager.prototype.addPointers = function () {
- this.add(new BABYLON.ArcRotateCameraPointersInput());
- return this;
- };
- ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
- this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
- return this;
- };
- ArcRotateCameraInputsManager.prototype.addGamepad = function () {
- this.add(new BABYLON.ArcRotateCameraGamepadInput());
- return this;
- };
- ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
- this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
- return this;
- };
- return ArcRotateCameraInputsManager;
- })(BABYLON.CameraInputsManager);
- BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var RenderingManager = (function () {
- function RenderingManager(scene) {
- this._renderingGroups = new Array();
- this._scene = scene;
- }
- RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
- if (this._scene._activeParticleSystems.length === 0) {
- return;
- }
- // Particles
- var activeCamera = this._scene.activeCamera;
- var beforeParticlesDate = BABYLON.Tools.Now;
- for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
- var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
- if (particleSystem.renderingGroupId !== index) {
- continue;
- }
- if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
- continue;
- }
- this._clearDepthBuffer();
- if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
- this._scene._activeParticles += particleSystem.render();
- }
- }
- this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
- };
- RenderingManager.prototype._renderSprites = function (index) {
- if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
- return;
- }
- // Sprites
- var activeCamera = this._scene.activeCamera;
- var beforeSpritessDate = BABYLON.Tools.Now;
- for (var id = 0; id < this._scene.spriteManagers.length; id++) {
- var spriteManager = this._scene.spriteManagers[id];
- if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
- this._clearDepthBuffer();
- spriteManager.render();
- }
- }
- this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
- };
- RenderingManager.prototype._clearDepthBuffer = function () {
- if (this._depthBufferAlreadyCleaned) {
- return;
- }
- this._scene.getEngine().clear(0, false, true);
- this._depthBufferAlreadyCleaned = true;
- };
- RenderingManager.prototype._renderSpritesAndParticles = function () {
- if (this._currentRenderSprites) {
- this._renderSprites(this._currentIndex);
- }
- if (this._currentRenderParticles) {
- this._renderParticles(this._currentIndex, this._currentActiveMeshes);
- }
- };
- RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
- this._currentActiveMeshes = activeMeshes;
- this._currentRenderParticles = renderParticles;
- this._currentRenderSprites = renderSprites;
- for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
- this._depthBufferAlreadyCleaned = index == 0;
- var renderingGroup = this._renderingGroups[index];
- var needToStepBack = false;
- this._currentIndex = index;
- if (renderingGroup) {
- this._clearDepthBuffer();
- if (!renderingGroup.onBeforeTransparentRendering) {
- renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
- }
- if (!renderingGroup.render(customRenderFunction)) {
- this._renderingGroups.splice(index, 1);
- needToStepBack = true;
- this._renderSpritesAndParticles();
- }
- }
- else {
- this._renderSpritesAndParticles();
- }
- if (needToStepBack) {
- index--;
- }
- }
- };
- RenderingManager.prototype.reset = function () {
- this._renderingGroups.forEach(function (renderingGroup, index, array) {
- if (renderingGroup) {
- renderingGroup.prepare();
- }
- });
- };
- RenderingManager.prototype.dispatch = function (subMesh) {
- var mesh = subMesh.getMesh();
- var renderingGroupId = mesh.renderingGroupId || 0;
- if (!this._renderingGroups[renderingGroupId]) {
- this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
- }
- this._renderingGroups[renderingGroupId].dispatch(subMesh);
- };
- RenderingManager.MAX_RENDERINGGROUPS = 4;
- return RenderingManager;
- })();
- BABYLON.RenderingManager = RenderingManager;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var RenderingGroup = (function () {
- function RenderingGroup(index, scene) {
- this.index = index;
- this._opaqueSubMeshes = new BABYLON.SmartArray(256);
- this._transparentSubMeshes = new BABYLON.SmartArray(256);
- this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
- this._scene = scene;
- }
- RenderingGroup.prototype.render = function (customRenderFunction) {
- if (customRenderFunction) {
- customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
- return true;
- }
- if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
- if (this.onBeforeTransparentRendering) {
- this.onBeforeTransparentRendering();
- }
- return false;
- }
- var engine = this._scene.getEngine();
- // Opaque
- var subIndex;
- var submesh;
- for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
- submesh = this._opaqueSubMeshes.data[subIndex];
- submesh.render(false);
- }
- // Alpha test
- engine.setAlphaTesting(true);
- for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
- submesh = this._alphaTestSubMeshes.data[subIndex];
- submesh.render(false);
- }
- engine.setAlphaTesting(false);
- if (this.onBeforeTransparentRendering) {
- this.onBeforeTransparentRendering();
- }
- // Transparent
- if (this._transparentSubMeshes.length) {
- // Sorting
- for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
- submesh = this._transparentSubMeshes.data[subIndex];
- submesh._alphaIndex = submesh.getMesh().alphaIndex;
- submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
- }
- var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
- sortedArray.sort(function (a, b) {
- // Alpha index first
- if (a._alphaIndex > b._alphaIndex) {
- return 1;
- }
- if (a._alphaIndex < b._alphaIndex) {
- return -1;
- }
- // Then distance to camera
- if (a._distanceToCamera < b._distanceToCamera) {
- return 1;
- }
- if (a._distanceToCamera > b._distanceToCamera) {
- return -1;
- }
- return 0;
- });
- // Rendering
- for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
- submesh = sortedArray[subIndex];
- submesh.render(true);
- }
- engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
- }
- return true;
- };
- RenderingGroup.prototype.prepare = function () {
- this._opaqueSubMeshes.reset();
- this._transparentSubMeshes.reset();
- this._alphaTestSubMeshes.reset();
- };
- RenderingGroup.prototype.dispatch = function (subMesh) {
- var material = subMesh.getMaterial();
- var mesh = subMesh.getMesh();
- if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
- this._transparentSubMeshes.push(subMesh);
- }
- else if (material.needAlphaTesting()) {
- this._alphaTestSubMeshes.push(subMesh);
- }
- else {
- this._opaqueSubMeshes.push(subMesh); // Opaque
- }
- };
- return RenderingGroup;
- })();
- BABYLON.RenderingGroup = RenderingGroup;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var PointerEventTypes = (function () {
- function PointerEventTypes() {
- }
- Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
- get: function () {
- return PointerEventTypes._POINTERDOWN;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PointerEventTypes, "POINTERUP", {
- get: function () {
- return PointerEventTypes._POINTERUP;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
- get: function () {
- return PointerEventTypes._POINTERMOVE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
- get: function () {
- return PointerEventTypes._POINTERWHEEL;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PointerEventTypes, "POINTERPICK", {
- get: function () {
- return PointerEventTypes._POINTERPICK;
- },
- enumerable: true,
- configurable: true
- });
- PointerEventTypes._POINTERDOWN = 0x01;
- PointerEventTypes._POINTERUP = 0x02;
- PointerEventTypes._POINTERMOVE = 0x04;
- PointerEventTypes._POINTERWHEEL = 0x08;
- PointerEventTypes._POINTERPICK = 0x10;
- return PointerEventTypes;
- })();
- BABYLON.PointerEventTypes = PointerEventTypes;
- /**
- * This type contains all the data related to a pointer event in Babylon.js.
- * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The differents event types can be found in the PointerEventTypes class.
- */
- var PointerInfo = (function () {
- function PointerInfo(type, event, pickInfo) {
- this.type = type;
- this.event = event;
- this.pickInfo = pickInfo;
- }
- return PointerInfo;
- })();
- BABYLON.PointerInfo = PointerInfo;
- /**
- * Represents a scene to be rendered by the engine.
- * @see http://doc.babylonjs.com/page.php?p=21911
- */
- var Scene = (function () {
- /**
- * @constructor
- * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
- */
- function Scene(engine) {
- // Members
- this.autoClear = true;
- this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
- this.ambientColor = new BABYLON.Color3(0, 0, 0);
- this.forceWireframe = false;
- this.forcePointsCloud = false;
- this.forceShowBoundingBoxes = false;
- this.animationsEnabled = true;
- this.constantlyUpdateMeshUnderPointer = false;
- // Events
- /**
- * An event triggered when the scene is disposed.
- * @type {BABYLON.Observable}
- */
- this.onDisposeObservable = new BABYLON.Observable();
- /**
- * An event triggered before rendering the scene
- * @type {BABYLON.Observable}
- */
- this.onBeforeRenderObservable = new BABYLON.Observable();
- /**
- * An event triggered after rendering the scene
- * @type {BABYLON.Observable}
- */
- this.onAfterRenderObservable = new BABYLON.Observable();
- /**
- * An event triggered when the scene is ready
- * @type {BABYLON.Observable}
- */
- this.onReadyObservable = new BABYLON.Observable();
- /**
- * An event triggered before rendering a camera
- * @type {BABYLON.Observable}
- */
- this.onBeforeCameraRenderObservable = new BABYLON.Observable();
- /**
- * An event triggered after rendering a camera
- * @type {BABYLON.Observable}
- */
- this.onAfterCameraRenderObservable = new BABYLON.Observable();
- /**
- * An event triggered when a camera is created
- * @type {BABYLON.Observable}
- */
- this.onNewCameraAddedObservable = new BABYLON.Observable();
- /**
- * An event triggered when a camera is removed
- * @type {BABYLON.Observable}
- */
- this.onCameraRemovedObservable = new BABYLON.Observable();
- /**
- * An event triggered when a light is created
- * @type {BABYLON.Observable}
- */
- this.onNewLightAddedObservable = new BABYLON.Observable();
- /**
- * An event triggered when a light is removed
- * @type {BABYLON.Observable}
- */
- this.onLightRemovedObservable = new BABYLON.Observable();
- /**
- * An event triggered when a geometry is created
- * @type {BABYLON.Observable}
- */
- this.onNewGeometryAddedObservable = new BABYLON.Observable();
- /**
- * An event triggered when a geometry is removed
- * @type {BABYLON.Observable}
- */
- this.onGeometryRemovedObservable = new BABYLON.Observable();
- /**
- * An event triggered when a mesh is created
- * @type {BABYLON.Observable}
- */
- this.onNewMeshAddedObservable = new BABYLON.Observable();
- /**
- * An event triggered when a mesh is removed
- * @type {BABYLON.Observable}
- */
- this.onMeshRemovedObservable = new BABYLON.Observable();
- // Animations
- this.animations = [];
- /**
- * Observable event triggered each time an input event is received from the rendering canvas
- */
- this.onPointerObservable = new BABYLON.Observable();
- 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
- this._startingPointerPosition = new BABYLON.Vector2(0, 0);
- this._startingPointerTime = 0;
- // Fog
- /**
- * is fog enabled on this scene.
- * @type {boolean}
- */
- this.fogEnabled = true;
- this.fogMode = Scene.FOGMODE_NONE;
- this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
- this.fogDensity = 0.1;
- this.fogStart = 0;
- this.fogEnd = 1000.0;
- // Lights
- /**
- * is shadow enabled on this scene.
- * @type {boolean}
- */
- this.shadowsEnabled = true;
- /**
- * is light enabled on this scene.
- * @type {boolean}
- */
- this.lightsEnabled = true;
- /**
- * All of the lights added to this scene.
- * @see BABYLON.Light
- * @type {BABYLON.Light[]}
- */
- this.lights = new Array();
- // Cameras
- /**
- * All of the cameras added to this scene.
- * @see BABYLON.Camera
- * @type {BABYLON.Camera[]}
- */
- this.cameras = new Array();
- this.activeCameras = new Array();
- // Meshes
- /**
- * All of the (abstract) meshes added to this scene.
- * @see BABYLON.AbstractMesh
- * @type {BABYLON.AbstractMesh[]}
- */
- this.meshes = new Array();
- // Geometries
- this._geometries = new Array();
- this.materials = new Array();
- this.multiMaterials = new Array();
- this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
- // Textures
- this.texturesEnabled = true;
- this.textures = new Array();
- // Particles
- this.particlesEnabled = true;
- this.particleSystems = new Array();
- // Sprites
- this.spritesEnabled = true;
- this.spriteManagers = new Array();
- // Layers
- this.layers = new Array();
- // Skeletons
- this.skeletonsEnabled = true;
- this.skeletons = new Array();
- // Lens flares
- this.lensFlaresEnabled = true;
- this.lensFlareSystems = new Array();
- // Collisions
- this.collisionsEnabled = true;
- this.gravity = new BABYLON.Vector3(0, -9.807, 0);
- // Postprocesses
- this.postProcessesEnabled = true;
- // Customs render targets
- this.renderTargetsEnabled = true;
- this.dumpNextRenderTargets = false;
- this.customRenderTargets = new Array();
- // Imported meshes
- this.importedMeshesFiles = new Array();
- // Probes
- this.probesEnabled = true;
- this.reflectionProbes = new Array();
- this._actionManagers = new Array();
- this._meshesForIntersections = new BABYLON.SmartArray(256);
- // Procedural textures
- this.proceduralTexturesEnabled = true;
- this._proceduralTextures = new Array();
- this.soundTracks = new Array();
- this._audioEnabled = true;
- this._headphone = false;
- this._totalVertices = 0;
- this._activeIndices = 0;
- this._activeParticles = 0;
- this._lastFrameDuration = 0;
- this._evaluateActiveMeshesDuration = 0;
- this._renderTargetsDuration = 0;
- this._particlesDuration = 0;
- this._renderDuration = 0;
- this._spritesDuration = 0;
- this._animationRatio = 0;
- this._renderId = 0;
- this._executeWhenReadyTimeoutId = -1;
- this._intermediateRendering = false;
- this._toBeDisposed = new BABYLON.SmartArray(256);
- this._pendingData = []; //ANY
- this._activeMeshes = new BABYLON.SmartArray(256);
- this._processedMaterials = new BABYLON.SmartArray(256);
- this._renderTargets = new BABYLON.SmartArray(256);
- this._activeParticleSystems = new BABYLON.SmartArray(256);
- this._activeSkeletons = new BABYLON.SmartArray(32);
- this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
- this._activeBones = 0;
- this._activeAnimatables = new Array();
- this._transformMatrix = BABYLON.Matrix.Zero();
- this._edgesRenderers = new BABYLON.SmartArray(16);
- this._uniqueIdCounter = 0;
- this._engine = engine;
- engine.scenes.push(this);
- this._renderingManager = new BABYLON.RenderingManager(this);
- this.postProcessManager = new BABYLON.PostProcessManager(this);
- this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
- this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
- if (BABYLON.OutlineRenderer) {
- this._outlineRenderer = new BABYLON.OutlineRenderer(this);
- }
- this.attachControl();
- this._debugLayer = new BABYLON.DebugLayer(this);
- if (BABYLON.SoundTrack) {
- this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
- }
- //simplification queue
- if (BABYLON.SimplificationQueue) {
- this.simplificationQueue = new BABYLON.SimplificationQueue();
- }
- //collision coordinator initialization. For now legacy per default.
- this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
- }
- Object.defineProperty(Scene, "FOGMODE_NONE", {
- get: function () {
- return Scene._FOGMODE_NONE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene, "FOGMODE_EXP", {
- get: function () {
- return Scene._FOGMODE_EXP;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene, "FOGMODE_EXP2", {
- get: function () {
- return Scene._FOGMODE_EXP2;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene, "FOGMODE_LINEAR", {
- get: function () {
- return Scene._FOGMODE_LINEAR;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene.prototype, "onDispose", {
- set: function (callback) {
- if (this._onDisposeObserver) {
- this.onDisposeObservable.remove(this._onDisposeObserver);
- }
- this._onDisposeObserver = this.onDisposeObservable.add(callback);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene.prototype, "beforeRender", {
- set: function (callback) {
- if (this._onBeforeRenderObserver) {
- this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
- }
- this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene.prototype, "afterRender", {
- set: function (callback) {
- if (this._onAfterRenderObserver) {
- this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
- }
- this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene.prototype, "beforeCameraRender", {
- set: function (callback) {
- if (this._onBeforeCameraRenderObserver) {
- this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
- }
- this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene.prototype, "afterCameraRender", {
- set: function (callback) {
- if (this._onAfterCameraRenderObserver) {
- this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
- }
- this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene.prototype, "debugLayer", {
- // Properties
- get: function () {
- return this._debugLayer;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene.prototype, "workerCollisions", {
- get: function () {
- return this._workerCollisions;
- },
- set: function (enabled) {
- enabled = (enabled && !!Worker);
- this._workerCollisions = enabled;
- if (this.collisionCoordinator) {
- this.collisionCoordinator.destroy();
- }
- this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
- this.collisionCoordinator.init(this);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene.prototype, "SelectionOctree", {
- get: function () {
- return this._selectionOctree;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene.prototype, "meshUnderPointer", {
- /**
- * The mesh that is currently under the pointer.
- * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
- */
- get: function () {
- return this._pointerOverMesh;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene.prototype, "pointerX", {
- /**
- * Current on-screen X position of the pointer
- * @return {number} X position of the pointer
- */
- get: function () {
- return this._pointerX;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene.prototype, "pointerY", {
- /**
- * Current on-screen Y position of the pointer
- * @return {number} Y position of the pointer
- */
- get: function () {
- return this._pointerY;
- },
- enumerable: true,
- configurable: true
- });
- Scene.prototype.getCachedMaterial = function () {
- return this._cachedMaterial;
- };
- Scene.prototype.getBoundingBoxRenderer = function () {
- return this._boundingBoxRenderer;
- };
- Scene.prototype.getOutlineRenderer = function () {
- return this._outlineRenderer;
- };
- Scene.prototype.getEngine = function () {
- return this._engine;
- };
- Scene.prototype.getTotalVertices = function () {
- return this._totalVertices;
- };
- Scene.prototype.getActiveIndices = function () {
- return this._activeIndices;
- };
- Scene.prototype.getActiveParticles = function () {
- return this._activeParticles;
- };
- Scene.prototype.getActiveBones = function () {
- return this._activeBones;
- };
- // Stats
- Scene.prototype.getLastFrameDuration = function () {
- return this._lastFrameDuration;
- };
- Scene.prototype.getEvaluateActiveMeshesDuration = function () {
- return this._evaluateActiveMeshesDuration;
- };
- Scene.prototype.getActiveMeshes = function () {
- return this._activeMeshes;
- };
- Scene.prototype.getRenderTargetsDuration = function () {
- return this._renderTargetsDuration;
- };
- Scene.prototype.getRenderDuration = function () {
- return this._renderDuration;
- };
- Scene.prototype.getParticlesDuration = function () {
- return this._particlesDuration;
- };
- Scene.prototype.getSpritesDuration = function () {
- return this._spritesDuration;
- };
- Scene.prototype.getAnimationRatio = function () {
- return this._animationRatio;
- };
- Scene.prototype.getRenderId = function () {
- return this._renderId;
- };
- Scene.prototype.incrementRenderId = function () {
- this._renderId++;
- };
- Scene.prototype._updatePointerPosition = function (evt) {
- var canvasRect = this._engine.getRenderingCanvasClientRect();
- this._pointerX = evt.clientX - canvasRect.left;
- this._pointerY = evt.clientY - canvasRect.top;
- this._unTranslatedPointerX = this._pointerX;
- this._unTranslatedPointerY = this._pointerY;
- if (this.cameraToUseForPointers) {
- this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
- this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
- }
- };
- // Pointers handling
- /**
- * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
- * @param attachUp defines if you want to attach events to pointerup
- * @param attachDown defines if you want to attach events to pointerdown
- * @param attachMove defines if you want to attach events to pointermove
- */
- Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
- var _this = this;
- if (attachUp === void 0) { attachUp = true; }
- if (attachDown === void 0) { attachDown = true; }
- if (attachMove === void 0) { attachMove = true; }
- var spritePredicate = function (sprite) {
- return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
- };
- this._onPointerMove = function (evt) {
- if (!_this.cameraToUseForPointers && !_this.activeCamera) {
- return;
- }
- var canvas = _this._engine.getRenderingCanvas();
- _this._updatePointerPosition(evt);
- if (!_this.pointerMovePredicate) {
- _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
- }
- // Meshes
- var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
- if (pickResult.hit && pickResult.pickedMesh) {
- _this.setPointerOverSprite(null);
- _this.setPointerOverMesh(pickResult.pickedMesh);
- if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
- canvas.style.cursor = "pointer";
- }
- else {
- canvas.style.cursor = "";
- }
- }
- else {
- _this.setPointerOverMesh(null);
- // Sprites
- pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
- if (pickResult.hit && pickResult.pickedSprite) {
- canvas.style.cursor = "pointer";
- _this.setPointerOverSprite(pickResult.pickedSprite);
- }
- else {
- _this.setPointerOverSprite(null);
- // Restore pointer
- canvas.style.cursor = "";
- }
- }
- if (_this.onPointerMove) {
- _this.onPointerMove(evt, pickResult);
- }
- if (_this.onPointerObservable.hasObservers()) {
- var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
- var pi = new PointerInfo(type, evt, pickResult);
- _this.onPointerObservable.notifyObservers(pi, type);
- }
- };
- this._onPointerDown = function (evt) {
- if (!_this.cameraToUseForPointers && !_this.activeCamera) {
- return;
- }
- _this._updatePointerPosition(evt);
- _this._startingPointerPosition.x = _this._pointerX;
- _this._startingPointerPosition.y = _this._pointerY;
- _this._startingPointerTime = new Date().getTime();
- if (!_this.pointerDownPredicate) {
- _this.pointerDownPredicate = function (mesh) {
- return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
- };
- }
- // Meshes
- _this._pickedDownMesh = null;
- var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
- if (pickResult.hit && pickResult.pickedMesh) {
- if (pickResult.pickedMesh.actionManager) {
- _this._pickedDownMesh = pickResult.pickedMesh;
- if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
- switch (evt.button) {
- case 0:
- pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
- break;
- case 1:
- pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
- break;
- case 2:
- pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
- break;
- }
- pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
- }
- if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
- var that = _this;
- window.setTimeout(function () {
- 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);
- if (pickResult.hit && pickResult.pickedMesh) {
- if (pickResult.pickedMesh.actionManager) {
- 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)) {
- that._startingPointerTime = 0;
- pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
- }
- }
- }
- }, BABYLON.ActionManager.LongPressDelay);
- }
- }
- }
- if (_this.onPointerDown) {
- _this.onPointerDown(evt, pickResult);
- }
- if (_this.onPointerObservable.hasObservers()) {
- var type = PointerEventTypes.POINTERDOWN;
- var pi = new PointerInfo(type, evt, pickResult);
- _this.onPointerObservable.notifyObservers(pi, type);
- }
- // Sprites
- _this._pickedDownSprite = null;
- if (_this.spriteManagers.length > 0) {
- pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
- if (pickResult.hit && pickResult.pickedSprite) {
- if (pickResult.pickedSprite.actionManager) {
- _this._pickedDownSprite = pickResult.pickedSprite;
- switch (evt.button) {
- case 0:
- pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
- break;
- case 1:
- pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
- break;
- case 2:
- pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
- break;
- }
- pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
- }
- }
- }
- };
- this._onPointerUp = function (evt) {
- if (!_this.cameraToUseForPointers && !_this.activeCamera) {
- return;
- }
- _this._updatePointerPosition(evt);
- if (!_this.pointerUpPredicate) {
- _this.pointerUpPredicate = function (mesh) {
- return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
- };
- }
- // Meshes
- var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
- if (pickResult.hit && pickResult.pickedMesh) {
- if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
- if (_this.onPointerPick) {
- _this.onPointerPick(evt, pickResult);
- }
- if (_this.onPointerObservable.hasObservers()) {
- var type = PointerEventTypes.POINTERPICK;
- var pi = new PointerInfo(type, evt, pickResult);
- _this.onPointerObservable.notifyObservers(pi, type);
- }
- }
- if (pickResult.pickedMesh.actionManager) {
- pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
- if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
- pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
- }
- }
- }
- if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
- _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
- }
- if (_this.onPointerUp) {
- _this.onPointerUp(evt, pickResult);
- }
- if (_this.onPointerObservable.hasObservers()) {
- var type = PointerEventTypes.POINTERUP;
- var pi = new PointerInfo(type, evt, pickResult);
- _this.onPointerObservable.notifyObservers(pi, type);
- }
- _this._startingPointerTime = 0;
- // Sprites
- if (_this.spriteManagers.length > 0) {
- pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
- if (pickResult.hit && pickResult.pickedSprite) {
- if (pickResult.pickedSprite.actionManager) {
- pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
- if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
- pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
- }
- }
- }
- if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
- _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
- }
- }
- };
- this._onKeyDown = function (evt) {
- if (_this.actionManager) {
- _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
- }
- };
- this._onKeyUp = function (evt) {
- if (_this.actionManager) {
- _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
- }
- };
- var eventPrefix = BABYLON.Tools.GetPointerPrefix();
- if (attachMove) {
- this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
- // Wheel
- this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
- this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
- }
- if (attachDown) {
- this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
- }
- if (attachUp) {
- this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
- }
- BABYLON.Tools.RegisterTopRootEvents([
- { name: "keydown", handler: this._onKeyDown },
- { name: "keyup", handler: this._onKeyUp }
- ]);
- };
- Scene.prototype.detachControl = function () {
- var eventPrefix = BABYLON.Tools.GetPointerPrefix();
- this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
- this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
- this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
- // Wheel
- this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
- this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
- BABYLON.Tools.UnregisterTopRootEvents([
- { name: "keydown", handler: this._onKeyDown },
- { name: "keyup", handler: this._onKeyUp }
- ]);
- };
- // Ready
- Scene.prototype.isReady = function () {
- if (this._pendingData.length > 0) {
- return false;
- }
- var index;
- for (index = 0; index < this._geometries.length; index++) {
- var geometry = this._geometries[index];
- if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
- return false;
- }
- }
- for (index = 0; index < this.meshes.length; index++) {
- var mesh = this.meshes[index];
- if (!mesh.isReady()) {
- return false;
- }
- var mat = mesh.material;
- if (mat) {
- if (!mat.isReady(mesh)) {
- return false;
- }
- }
- }
- return true;
- };
- Scene.prototype.resetCachedMaterial = function () {
- this._cachedMaterial = null;
- };
- Scene.prototype.registerBeforeRender = function (func) {
- this.onBeforeRenderObservable.add(func);
- };
- Scene.prototype.unregisterBeforeRender = function (func) {
- this.onBeforeRenderObservable.removeCallback(func);
- };
- Scene.prototype.registerAfterRender = function (func) {
- this.onAfterRenderObservable.add(func);
- };
- Scene.prototype.unregisterAfterRender = function (func) {
- this.onAfterRenderObservable.removeCallback(func);
- };
- Scene.prototype._addPendingData = function (data) {
- this._pendingData.push(data);
- };
- Scene.prototype._removePendingData = function (data) {
- var index = this._pendingData.indexOf(data);
- if (index !== -1) {
- this._pendingData.splice(index, 1);
- }
- };
- Scene.prototype.getWaitingItemsCount = function () {
- return this._pendingData.length;
- };
- /**
- * Registers a function to be executed when the scene is ready.
- * @param {Function} func - the function to be executed.
- */
- Scene.prototype.executeWhenReady = function (func) {
- var _this = this;
- this.onReadyObservable.add(func);
- if (this._executeWhenReadyTimeoutId !== -1) {
- return;
- }
- this._executeWhenReadyTimeoutId = setTimeout(function () {
- _this._checkIsReady();
- }, 150);
- };
- Scene.prototype._checkIsReady = function () {
- var _this = this;
- if (this.isReady()) {
- this.onReadyObservable.notifyObservers(this);
- this.onReadyObservable.clear();
- this._executeWhenReadyTimeoutId = -1;
- return;
- }
- this._executeWhenReadyTimeoutId = setTimeout(function () {
- _this._checkIsReady();
- }, 150);
- };
- // Animations
- /**
- * Will start the animation sequence of a given target
- * @param target - the target
- * @param {number} from - from which frame should animation start
- * @param {number} to - till which frame should animation run.
- * @param {boolean} [loop] - should the animation loop
- * @param {number} [speedRatio] - the speed in which to run the animation
- * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
- * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
- * @return {BABYLON.Animatable} the animatable object created for this animation
- * @see BABYLON.Animatable
- * @see http://doc.babylonjs.com/page.php?p=22081
- */
- Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
- if (speedRatio === void 0) { speedRatio = 1.0; }
- this.stopAnimation(target);
- if (!animatable) {
- animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
- }
- // Local animations
- if (target.animations) {
- animatable.appendAnimations(target, target.animations);
- }
- // Children animations
- if (target.getAnimatables) {
- var animatables = target.getAnimatables();
- for (var index = 0; index < animatables.length; index++) {
- this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
- }
- }
- animatable.reset();
- return animatable;
- };
- Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
- if (speedRatio === undefined) {
- speedRatio = 1.0;
- }
- var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
- return animatable;
- };
- Scene.prototype.getAnimatableByTarget = function (target) {
- for (var index = 0; index < this._activeAnimatables.length; index++) {
- if (this._activeAnimatables[index].target === target) {
- return this._activeAnimatables[index];
- }
- }
- return null;
- };
- Object.defineProperty(Scene.prototype, "Animatables", {
- get: function () {
- return this._activeAnimatables;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Will stop the animation of the given target
- * @param target - the target
- * @see beginAnimation
- */
- Scene.prototype.stopAnimation = function (target) {
- var animatable = this.getAnimatableByTarget(target);
- if (animatable) {
- animatable.stop();
- }
- };
- Scene.prototype._animate = function () {
- if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
- return;
- }
- if (!this._animationStartDate) {
- if (this._pendingData.length > 0) {
- return;
- }
- this._animationStartDate = BABYLON.Tools.Now;
- }
- // Getting time
- var now = BABYLON.Tools.Now;
- var delay = now - this._animationStartDate;
- for (var index = 0; index < this._activeAnimatables.length; index++) {
- this._activeAnimatables[index]._animate(delay);
- }
- };
- // Matrix
- Scene.prototype.getViewMatrix = function () {
- return this._viewMatrix;
- };
- Scene.prototype.getProjectionMatrix = function () {
- return this._projectionMatrix;
- };
- Scene.prototype.getTransformMatrix = function () {
- return this._transformMatrix;
- };
- Scene.prototype.setTransformMatrix = function (view, projection) {
- this._viewMatrix = view;
- this._projectionMatrix = projection;
- this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
- };
- // Methods
- Scene.prototype.addMesh = function (newMesh) {
- newMesh.uniqueId = this._uniqueIdCounter++;
- var position = this.meshes.push(newMesh);
- //notify the collision coordinator
- this.collisionCoordinator.onMeshAdded(newMesh);
- this.onNewMeshAddedObservable.notifyObservers(newMesh);
- };
- Scene.prototype.removeMesh = function (toRemove) {
- var index = this.meshes.indexOf(toRemove);
- if (index !== -1) {
- // Remove from the scene if mesh found
- this.meshes.splice(index, 1);
- }
- //notify the collision coordinator
- this.collisionCoordinator.onMeshRemoved(toRemove);
- this.onMeshRemovedObservable.notifyObservers(toRemove);
- return index;
- };
- Scene.prototype.removeSkeleton = function (toRemove) {
- var index = this.skeletons.indexOf(toRemove);
- if (index !== -1) {
- // Remove from the scene if mesh found
- this.skeletons.splice(index, 1);
- }
- return index;
- };
- Scene.prototype.removeLight = function (toRemove) {
- var index = this.lights.indexOf(toRemove);
- if (index !== -1) {
- // Remove from the scene if mesh found
- this.lights.splice(index, 1);
- }
- this.onLightRemovedObservable.notifyObservers(toRemove);
- return index;
- };
- Scene.prototype.removeCamera = function (toRemove) {
- var index = this.cameras.indexOf(toRemove);
- if (index !== -1) {
- // Remove from the scene if mesh found
- this.cameras.splice(index, 1);
- }
- // Remove from activeCameras
- var index2 = this.activeCameras.indexOf(toRemove);
- if (index2 !== -1) {
- // Remove from the scene if mesh found
- this.activeCameras.splice(index2, 1);
- }
- // Reset the activeCamera
- if (this.activeCamera === toRemove) {
- if (this.cameras.length > 0) {
- this.activeCamera = this.cameras[0];
- }
- else {
- this.activeCamera = null;
- }
- }
- this.onCameraRemovedObservable.notifyObservers(toRemove);
- return index;
- };
- Scene.prototype.addLight = function (newLight) {
- newLight.uniqueId = this._uniqueIdCounter++;
- var position = this.lights.push(newLight);
- this.onNewLightAddedObservable.notifyObservers(newLight);
- };
- Scene.prototype.addCamera = function (newCamera) {
- newCamera.uniqueId = this._uniqueIdCounter++;
- var position = this.cameras.push(newCamera);
- this.onNewCameraAddedObservable.notifyObservers(newCamera);
- };
- /**
- * Switch active camera
- * @param {Camera} newCamera - new active camera
- * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
- */
- Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
- if (attachControl === void 0) { attachControl = true; }
- var canvas = this._engine.getRenderingCanvas();
- this.activeCamera.detachControl(canvas);
- this.activeCamera = newCamera;
- if (attachControl) {
- newCamera.attachControl(canvas);
- }
- };
- /**
- * sets the active camera of the scene using its ID
- * @param {string} id - the camera's ID
- * @return {BABYLON.Camera|null} the new active camera or null if none found.
- * @see activeCamera
- */
- Scene.prototype.setActiveCameraByID = function (id) {
- var camera = this.getCameraByID(id);
- if (camera) {
- this.activeCamera = camera;
- return camera;
- }
- return null;
- };
- /**
- * sets the active camera of the scene using its name
- * @param {string} name - the camera's name
- * @return {BABYLON.Camera|null} the new active camera or null if none found.
- * @see activeCamera
- */
- Scene.prototype.setActiveCameraByName = function (name) {
- var camera = this.getCameraByName(name);
- if (camera) {
- this.activeCamera = camera;
- return camera;
- }
- return null;
- };
- /**
- * get a material using its id
- * @param {string} the material's ID
- * @return {BABYLON.Material|null} the material or null if none found.
- */
- Scene.prototype.getMaterialByID = function (id) {
- for (var index = 0; index < this.materials.length; index++) {
- if (this.materials[index].id === id) {
- return this.materials[index];
- }
- }
- return null;
- };
- /**
- * get a material using its name
- * @param {string} the material's name
- * @return {BABYLON.Material|null} the material or null if none found.
- */
- Scene.prototype.getMaterialByName = function (name) {
- for (var index = 0; index < this.materials.length; index++) {
- if (this.materials[index].name === name) {
- return this.materials[index];
- }
- }
- return null;
- };
- Scene.prototype.getLensFlareSystemByName = function (name) {
- for (var index = 0; index < this.lensFlareSystems.length; index++) {
- if (this.lensFlareSystems[index].name === name) {
- return this.lensFlareSystems[index];
- }
- }
- return null;
- };
- Scene.prototype.getLensFlareSystemByID = function (id) {
- for (var index = 0; index < this.lensFlareSystems.length; index++) {
- if (this.lensFlareSystems[index].id === id) {
- return this.lensFlareSystems[index];
- }
- }
- return null;
- };
- Scene.prototype.getCameraByID = function (id) {
- for (var index = 0; index < this.cameras.length; index++) {
- if (this.cameras[index].id === id) {
- return this.cameras[index];
- }
- }
- return null;
- };
- Scene.prototype.getCameraByUniqueID = function (uniqueId) {
- for (var index = 0; index < this.cameras.length; index++) {
- if (this.cameras[index].uniqueId === uniqueId) {
- return this.cameras[index];
- }
- }
- return null;
- };
- /**
- * get a camera using its name
- * @param {string} the camera's name
- * @return {BABYLON.Camera|null} the camera or null if none found.
- */
- Scene.prototype.getCameraByName = function (name) {
- for (var index = 0; index < this.cameras.length; index++) {
- if (this.cameras[index].name === name) {
- return this.cameras[index];
- }
- }
- return null;
- };
- /**
- * get a bone using its id
- * @param {string} the bone's id
- * @return {BABYLON.Bone|null} the bone or null if not found
- */
- Scene.prototype.getBoneByID = function (id) {
- for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
- var skeleton = this.skeletons[skeletonIndex];
- for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
- if (skeleton.bones[boneIndex].id === id) {
- return skeleton.bones[boneIndex];
- }
- }
- }
- return null;
- };
- /**
- * get a bone using its id
- * @param {string} the bone's name
- * @return {BABYLON.Bone|null} the bone or null if not found
- */
- Scene.prototype.getBoneByName = function (name) {
- for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
- var skeleton = this.skeletons[skeletonIndex];
- for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
- if (skeleton.bones[boneIndex].name === name) {
- return skeleton.bones[boneIndex];
- }
- }
- }
- return null;
- };
- /**
- * get a light node using its name
- * @param {string} the light's name
- * @return {BABYLON.Light|null} the light or null if none found.
- */
- Scene.prototype.getLightByName = function (name) {
- for (var index = 0; index < this.lights.length; index++) {
- if (this.lights[index].name === name) {
- return this.lights[index];
- }
- }
- return null;
- };
- /**
- * get a light node using its ID
- * @param {string} the light's id
- * @return {BABYLON.Light|null} the light or null if none found.
- */
- Scene.prototype.getLightByID = function (id) {
- for (var index = 0; index < this.lights.length; index++) {
- if (this.lights[index].id === id) {
- return this.lights[index];
- }
- }
- return null;
- };
- /**
- * get a light node using its scene-generated unique ID
- * @param {number} the light's unique id
- * @return {BABYLON.Light|null} the light or null if none found.
- */
- Scene.prototype.getLightByUniqueID = function (uniqueId) {
- for (var index = 0; index < this.lights.length; index++) {
- if (this.lights[index].uniqueId === uniqueId) {
- return this.lights[index];
- }
- }
- return null;
- };
- /**
- * get a particle system by id
- * @param id {number} the particle system id
- * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
- */
- Scene.prototype.getParticleSystemByID = function (id) {
- for (var index = 0; index < this.particleSystems.length; index++) {
- if (this.particleSystems[index].id === id) {
- return this.particleSystems[index];
- }
- }
- return null;
- };
- /**
- * get a geometry using its ID
- * @param {string} the geometry's id
- * @return {BABYLON.Geometry|null} the geometry or null if none found.
- */
- Scene.prototype.getGeometryByID = function (id) {
- for (var index = 0; index < this._geometries.length; index++) {
- if (this._geometries[index].id === id) {
- return this._geometries[index];
- }
- }
- return null;
- };
- /**
- * add a new geometry to this scene.
- * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
- * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
- * @return {boolean} was the geometry added or not
- */
- Scene.prototype.pushGeometry = function (geometry, force) {
- if (!force && this.getGeometryByID(geometry.id)) {
- return false;
- }
- this._geometries.push(geometry);
- //notify the collision coordinator
- this.collisionCoordinator.onGeometryAdded(geometry);
- this.onNewGeometryAddedObservable.notifyObservers(geometry);
- return true;
- };
- /**
- * Removes an existing geometry
- * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
- * @return {boolean} was the geometry removed or not
- */
- Scene.prototype.removeGeometry = function (geometry) {
- var index = this._geometries.indexOf(geometry);
- if (index > -1) {
- this._geometries.splice(index, 1);
- //notify the collision coordinator
- this.collisionCoordinator.onGeometryDeleted(geometry);
- this.onGeometryRemovedObservable.notifyObservers(geometry);
- return true;
- }
- return false;
- };
- Scene.prototype.getGeometries = function () {
- return this._geometries;
- };
- /**
- * Get the first added mesh found of a given ID
- * @param {string} id - the id to search for
- * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
- */
- Scene.prototype.getMeshByID = function (id) {
- for (var index = 0; index < this.meshes.length; index++) {
- if (this.meshes[index].id === id) {
- return this.meshes[index];
- }
- }
- return null;
- };
- Scene.prototype.getMeshesByID = function (id) {
- return this.meshes.filter(function (m) {
- return m.id === id;
- });
- };
- /**
- * Get a mesh with its auto-generated unique id
- * @param {number} uniqueId - the unique id to search for
- * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
- */
- Scene.prototype.getMeshByUniqueID = function (uniqueId) {
- for (var index = 0; index < this.meshes.length; index++) {
- if (this.meshes[index].uniqueId === uniqueId) {
- return this.meshes[index];
- }
- }
- return null;
- };
- /**
- * Get a the last added mesh found of a given ID
- * @param {string} id - the id to search for
- * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
- */
- Scene.prototype.getLastMeshByID = function (id) {
- for (var index = this.meshes.length - 1; index >= 0; index--) {
- if (this.meshes[index].id === id) {
- return this.meshes[index];
- }
- }
- return null;
- };
- /**
- * Get a the last added node (Mesh, Camera, Light) found of a given ID
- * @param {string} id - the id to search for
- * @return {BABYLON.Node|null} the node found or null if not found at all.
- */
- Scene.prototype.getLastEntryByID = function (id) {
- var index;
- for (index = this.meshes.length - 1; index >= 0; index--) {
- if (this.meshes[index].id === id) {
- return this.meshes[index];
- }
- }
- for (index = this.cameras.length - 1; index >= 0; index--) {
- if (this.cameras[index].id === id) {
- return this.cameras[index];
- }
- }
- for (index = this.lights.length - 1; index >= 0; index--) {
- if (this.lights[index].id === id) {
- return this.lights[index];
- }
- }
- return null;
- };
- Scene.prototype.getNodeByID = function (id) {
- var mesh = this.getMeshByID(id);
- if (mesh) {
- return mesh;
- }
- var light = this.getLightByID(id);
- if (light) {
- return light;
- }
- var camera = this.getCameraByID(id);
- if (camera) {
- return camera;
- }
- var bone = this.getBoneByID(id);
- return bone;
- };
- Scene.prototype.getNodeByName = function (name) {
- var mesh = this.getMeshByName(name);
- if (mesh) {
- return mesh;
- }
- var light = this.getLightByName(name);
- if (light) {
- return light;
- }
- var camera = this.getCameraByName(name);
- if (camera) {
- return camera;
- }
- var bone = this.getBoneByName(name);
- return bone;
- };
- Scene.prototype.getMeshByName = function (name) {
- for (var index = 0; index < this.meshes.length; index++) {
- if (this.meshes[index].name === name) {
- return this.meshes[index];
- }
- }
- return null;
- };
- Scene.prototype.getSoundByName = function (name) {
- var index;
- if (BABYLON.AudioEngine) {
- for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
- if (this.mainSoundTrack.soundCollection[index].name === name) {
- return this.mainSoundTrack.soundCollection[index];
- }
- }
- for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
- for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
- if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
- return this.soundTracks[sdIndex].soundCollection[index];
- }
- }
- }
- }
- return null;
- };
- Scene.prototype.getLastSkeletonByID = function (id) {
- for (var index = this.skeletons.length - 1; index >= 0; index--) {
- if (this.skeletons[index].id === id) {
- return this.skeletons[index];
- }
- }
- return null;
- };
- Scene.prototype.getSkeletonById = function (id) {
- for (var index = 0; index < this.skeletons.length; index++) {
- if (this.skeletons[index].id === id) {
- return this.skeletons[index];
- }
- }
- return null;
- };
- Scene.prototype.getSkeletonByName = function (name) {
- for (var index = 0; index < this.skeletons.length; index++) {
- if (this.skeletons[index].name === name) {
- return this.skeletons[index];
- }
- }
- return null;
- };
- Scene.prototype.isActiveMesh = function (mesh) {
- return (this._activeMeshes.indexOf(mesh) !== -1);
- };
- Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
- if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
- var material = subMesh.getMaterial();
- if (mesh.showSubMeshesBoundingBox) {
- this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
- }
- if (material) {
- // Render targets
- if (material.getRenderTargetTextures) {
- if (this._processedMaterials.indexOf(material) === -1) {
- this._processedMaterials.push(material);
- this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
- }
- }
- // Dispatch
- this._activeIndices += subMesh.indexCount;
- this._renderingManager.dispatch(subMesh);
- }
- }
- };
- Scene.prototype._isInIntermediateRendering = function () {
- return this._intermediateRendering;
- };
- Scene.prototype._evaluateActiveMeshes = function () {
- this.activeCamera._activeMeshes.reset();
- this._activeMeshes.reset();
- this._renderingManager.reset();
- this._processedMaterials.reset();
- this._activeParticleSystems.reset();
- this._activeSkeletons.reset();
- this._softwareSkinnedMeshes.reset();
- this._boundingBoxRenderer.reset();
- this._edgesRenderers.reset();
- if (!this._frustumPlanes) {
- this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
- }
- else {
- BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
- }
- // Meshes
- var meshes;
- var len;
- if (this._selectionOctree) {
- var selection = this._selectionOctree.select(this._frustumPlanes);
- meshes = selection.data;
- len = selection.length;
- }
- else {
- len = this.meshes.length;
- meshes = this.meshes;
- }
- for (var meshIndex = 0; meshIndex < len; meshIndex++) {
- var mesh = meshes[meshIndex];
- if (mesh.isBlocked) {
- continue;
- }
- this._totalVertices += mesh.getTotalVertices();
- if (!mesh.isReady() || !mesh.isEnabled()) {
- continue;
- }
- mesh.computeWorldMatrix();
- // Intersections
- if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
- this._meshesForIntersections.pushNoDuplicate(mesh);
- }
- // Switch to current LOD
- var meshLOD = mesh.getLOD(this.activeCamera);
- if (!meshLOD) {
- continue;
- }
- mesh._preActivate();
- if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
- this._activeMeshes.push(mesh);
- this.activeCamera._activeMeshes.push(mesh);
- mesh._activate(this._renderId);
- this._activeMesh(meshLOD);
- }
- }
- // Particle systems
- var beforeParticlesDate = BABYLON.Tools.Now;
- if (this.particlesEnabled) {
- BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
- for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
- var particleSystem = this.particleSystems[particleIndex];
- if (!particleSystem.isStarted()) {
- continue;
- }
- if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
- this._activeParticleSystems.push(particleSystem);
- particleSystem.animate();
- }
- }
- BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
- }
- this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
- };
- Scene.prototype._activeMesh = function (mesh) {
- if (mesh.skeleton && this.skeletonsEnabled) {
- this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
- if (!mesh.computeBonesUsingShaders) {
- this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
- }
- }
- if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
- this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
- }
- if (mesh._edgesRenderer) {
- this._edgesRenderers.push(mesh._edgesRenderer);
- }
- if (mesh && mesh.subMeshes) {
- // Submeshes Octrees
- var len;
- var subMeshes;
- if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
- var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
- len = intersections.length;
- subMeshes = intersections.data;
- }
- else {
- subMeshes = mesh.subMeshes;
- len = subMeshes.length;
- }
- for (var subIndex = 0; subIndex < len; subIndex++) {
- var subMesh = subMeshes[subIndex];
- this._evaluateSubMesh(subMesh, mesh);
- }
- }
- };
- Scene.prototype.updateTransformMatrix = function (force) {
- this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
- };
- Scene.prototype._renderForCamera = function (camera) {
- var engine = this._engine;
- this.activeCamera = camera;
- if (!this.activeCamera)
- throw new Error("Active camera not set");
- BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
- // Viewport
- engine.setViewport(this.activeCamera.viewport);
- // Camera
- this.resetCachedMaterial();
- this._renderId++;
- this.updateTransformMatrix();
- this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
- // Meshes
- var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
- BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
- this._evaluateActiveMeshes();
- this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
- BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
- // Skeletons
- for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
- var skeleton = this._activeSkeletons.data[skeletonIndex];
- skeleton.prepare();
- }
- // Software skinning
- for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
- var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
- mesh.applySkeleton(mesh.skeleton);
- }
- // Render targets
- var beforeRenderTargetDate = BABYLON.Tools.Now;
- if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
- this._intermediateRendering = true;
- BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
- for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
- var renderTarget = this._renderTargets.data[renderIndex];
- if (renderTarget._shouldRender()) {
- this._renderId++;
- var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
- renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
- }
- }
- BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
- this._intermediateRendering = false;
- this._renderId++;
- engine.restoreDefaultFramebuffer(); // Restore back buffer
- }
- this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
- // Prepare Frame
- this.postProcessManager._prepareFrame();
- var beforeRenderDate = BABYLON.Tools.Now;
- // Backgrounds
- var layerIndex;
- var layer;
- if (this.layers.length) {
- engine.setDepthBuffer(false);
- for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
- layer = this.layers[layerIndex];
- if (layer.isBackground) {
- layer.render();
- }
- }
- engine.setDepthBuffer(true);
- }
- // Render
- BABYLON.Tools.StartPerformanceCounter("Main render");
- this._renderingManager.render(null, null, true, true);
- BABYLON.Tools.EndPerformanceCounter("Main render");
- // Bounding boxes
- this._boundingBoxRenderer.render();
- // Edges
- for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
- this._edgesRenderers.data[edgesRendererIndex].render();
- }
- // Lens flares
- if (this.lensFlaresEnabled) {
- BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
- for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
- var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
- if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
- lensFlareSystem.render();
- }
- }
- BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
- }
- // Foregrounds
- if (this.layers.length) {
- engine.setDepthBuffer(false);
- for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
- layer = this.layers[layerIndex];
- if (!layer.isBackground) {
- layer.render();
- }
- }
- engine.setDepthBuffer(true);
- }
- this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
- // Finalize frame
- this.postProcessManager._finalizeFrame(camera.isIntermediate);
- // Update camera
- this.activeCamera._updateFromScene();
- // Reset some special arrays
- this._renderTargets.reset();
- this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
- BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
- };
- Scene.prototype._processSubCameras = function (camera) {
- if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
- this._renderForCamera(camera);
- return;
- }
- // rig cameras
- for (var index = 0; index < camera._rigCameras.length; index++) {
- this._renderForCamera(camera._rigCameras[index]);
- }
- this.activeCamera = camera;
- this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
- // Update camera
- this.activeCamera._updateFromScene();
- };
- Scene.prototype._checkIntersections = function () {
- for (var index = 0; index < this._meshesForIntersections.length; index++) {
- var sourceMesh = this._meshesForIntersections.data[index];
- for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
- var action = sourceMesh.actionManager.actions[actionIndex];
- if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
- var parameters = action.getTriggerParameter();
- var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
- var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
- var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
- if (areIntersecting && currentIntersectionInProgress === -1) {
- if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
- action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
- sourceMesh._intersectionsInProgress.push(otherMesh);
- }
- else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
- sourceMesh._intersectionsInProgress.push(otherMesh);
- }
- }
- else if (!areIntersecting && currentIntersectionInProgress > -1) {
- //They intersected, and now they don't.
- //is this trigger an exit trigger? execute an event.
- if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
- action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
- }
- //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
- if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
- sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
- }
- }
- }
- }
- }
- };
- Scene.prototype.render = function () {
- var startDate = BABYLON.Tools.Now;
- this._particlesDuration = 0;
- this._spritesDuration = 0;
- this._activeParticles = 0;
- this._renderDuration = 0;
- this._renderTargetsDuration = 0;
- this._evaluateActiveMeshesDuration = 0;
- this._totalVertices = 0;
- this._activeIndices = 0;
- this._activeBones = 0;
- this.getEngine().resetDrawCalls();
- this._meshesForIntersections.reset();
- this.resetCachedMaterial();
- BABYLON.Tools.StartPerformanceCounter("Scene rendering");
- // Actions
- if (this.actionManager) {
- this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
- }
- //Simplification Queue
- if (this.simplificationQueue && !this.simplificationQueue.running) {
- this.simplificationQueue.executeNext();
- }
- // Animations
- var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
- this._animationRatio = deltaTime * (60.0 / 1000.0);
- this._animate();
- // Physics
- if (this._physicsEngine) {
- BABYLON.Tools.StartPerformanceCounter("Physics");
- this._physicsEngine._step(deltaTime / 1000.0);
- BABYLON.Tools.EndPerformanceCounter("Physics");
- }
- // Before render
- this.onBeforeRenderObservable.notifyObservers(this);
- // Customs render targets
- var beforeRenderTargetDate = BABYLON.Tools.Now;
- var engine = this.getEngine();
- var currentActiveCamera = this.activeCamera;
- if (this.renderTargetsEnabled) {
- BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
- for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
- var renderTarget = this.customRenderTargets[customIndex];
- if (renderTarget._shouldRender()) {
- this._renderId++;
- this.activeCamera = renderTarget.activeCamera || this.activeCamera;
- if (!this.activeCamera)
- throw new Error("Active camera not set");
- // Viewport
- engine.setViewport(this.activeCamera.viewport);
- // Camera
- this.updateTransformMatrix();
- renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
- }
- }
- BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
- this._renderId++;
- }
- if (this.customRenderTargets.length > 0) {
- engine.restoreDefaultFramebuffer();
- }
- this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
- this.activeCamera = currentActiveCamera;
- // Procedural textures
- if (this.proceduralTexturesEnabled) {
- BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
- for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
- var proceduralTexture = this._proceduralTextures[proceduralIndex];
- if (proceduralTexture._shouldRender()) {
- proceduralTexture.render();
- }
- }
- BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
- }
- // Clear
- this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
- // Shadows
- if (this.shadowsEnabled) {
- for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
- var light = this.lights[lightIndex];
- var shadowGenerator = light.getShadowGenerator();
- if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
- this._renderTargets.push(shadowGenerator.getShadowMap());
- }
- }
- }
- // Depth renderer
- if (this._depthRenderer) {
- this._renderTargets.push(this._depthRenderer.getDepthMap());
- }
- // RenderPipeline
- this.postProcessRenderPipelineManager.update();
- // Multi-cameras?
- if (this.activeCameras.length > 0) {
- var currentRenderId = this._renderId;
- for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
- this._renderId = currentRenderId;
- if (cameraIndex > 0) {
- this._engine.clear(0, false, true);
- }
- this._processSubCameras(this.activeCameras[cameraIndex]);
- }
- }
- else {
- if (!this.activeCamera) {
- throw new Error("No camera defined");
- }
- this._processSubCameras(this.activeCamera);
- }
- // Intersection checks
- this._checkIntersections();
- // Update the audio listener attached to the camera
- if (BABYLON.AudioEngine) {
- this._updateAudioParameters();
- }
- // After render
- if (this.afterRender) {
- this.afterRender();
- }
- this.onAfterRenderObservable.notifyObservers(this);
- // Cleaning
- for (var index = 0; index < this._toBeDisposed.length; index++) {
- this._toBeDisposed.data[index].dispose();
- this._toBeDisposed[index] = null;
- }
- this._toBeDisposed.reset();
- if (this.dumpNextRenderTargets) {
- this.dumpNextRenderTargets = false;
- }
- BABYLON.Tools.EndPerformanceCounter("Scene rendering");
- this._lastFrameDuration = BABYLON.Tools.Now - startDate;
- };
- Scene.prototype._updateAudioParameters = function () {
- if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
- return;
- }
- var listeningCamera;
- var audioEngine = BABYLON.Engine.audioEngine;
- if (this.activeCameras.length > 0) {
- listeningCamera = this.activeCameras[0];
- }
- else {
- listeningCamera = this.activeCamera;
- }
- if (listeningCamera && audioEngine.canUseWebAudio) {
- audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
- var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
- var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
- cameraDirection.normalize();
- audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
- var i;
- for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
- var sound = this.mainSoundTrack.soundCollection[i];
- if (sound.useCustomAttenuation) {
- sound.updateDistanceFromListener();
- }
- }
- for (i = 0; i < this.soundTracks.length; i++) {
- for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
- sound = this.soundTracks[i].soundCollection[j];
- if (sound.useCustomAttenuation) {
- sound.updateDistanceFromListener();
- }
- }
- }
- }
- };
- Object.defineProperty(Scene.prototype, "audioEnabled", {
- // Audio
- get: function () {
- return this._audioEnabled;
- },
- set: function (value) {
- this._audioEnabled = value;
- if (BABYLON.AudioEngine) {
- if (this._audioEnabled) {
- this._enableAudio();
- }
- else {
- this._disableAudio();
- }
- }
- },
- enumerable: true,
- configurable: true
- });
- Scene.prototype._disableAudio = function () {
- var i;
- for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
- this.mainSoundTrack.soundCollection[i].pause();
- }
- for (i = 0; i < this.soundTracks.length; i++) {
- for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
- this.soundTracks[i].soundCollection[j].pause();
- }
- }
- };
- Scene.prototype._enableAudio = function () {
- var i;
- for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
- if (this.mainSoundTrack.soundCollection[i].isPaused) {
- this.mainSoundTrack.soundCollection[i].play();
- }
- }
- for (i = 0; i < this.soundTracks.length; i++) {
- for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
- if (this.soundTracks[i].soundCollection[j].isPaused) {
- this.soundTracks[i].soundCollection[j].play();
- }
- }
- }
- };
- Object.defineProperty(Scene.prototype, "headphone", {
- get: function () {
- return this._headphone;
- },
- set: function (value) {
- this._headphone = value;
- if (BABYLON.AudioEngine) {
- if (this._headphone) {
- this._switchAudioModeForHeadphones();
- }
- else {
- this._switchAudioModeForNormalSpeakers();
- }
- }
- },
- enumerable: true,
- configurable: true
- });
- Scene.prototype._switchAudioModeForHeadphones = function () {
- this.mainSoundTrack.switchPanningModelToHRTF();
- for (var i = 0; i < this.soundTracks.length; i++) {
- this.soundTracks[i].switchPanningModelToHRTF();
- }
- };
- Scene.prototype._switchAudioModeForNormalSpeakers = function () {
- this.mainSoundTrack.switchPanningModelToEqualPower();
- for (var i = 0; i < this.soundTracks.length; i++) {
- this.soundTracks[i].switchPanningModelToEqualPower();
- }
- };
- Scene.prototype.enableDepthRenderer = function () {
- if (this._depthRenderer) {
- return this._depthRenderer;
- }
- this._depthRenderer = new BABYLON.DepthRenderer(this);
- return this._depthRenderer;
- };
- Scene.prototype.disableDepthRenderer = function () {
- if (!this._depthRenderer) {
- return;
- }
- this._depthRenderer.dispose();
- this._depthRenderer = null;
- };
- Scene.prototype.freezeMaterials = function () {
- for (var i = 0; i < this.materials.length; i++) {
- this.materials[i].freeze();
- }
- };
- Scene.prototype.unfreezeMaterials = function () {
- for (var i = 0; i < this.materials.length; i++) {
- this.materials[i].unfreeze();
- }
- };
- Scene.prototype.dispose = function () {
- this.beforeRender = null;
- this.afterRender = null;
- this.skeletons = [];
- this._boundingBoxRenderer.dispose();
- if (this._depthRenderer) {
- this._depthRenderer.dispose();
- }
- // Debug layer
- this.debugLayer.hide();
- // Events
- if (this.onDispose) {
- this.onDispose();
- }
- this.onBeforeRenderObservable.clear();
- this.onAfterRenderObservable.clear();
- this.detachControl();
- // Release sounds & sounds tracks
- if (BABYLON.AudioEngine) {
- this.disposeSounds();
- }
- // Detach cameras
- var canvas = this._engine.getRenderingCanvas();
- var index;
- for (index = 0; index < this.cameras.length; index++) {
- this.cameras[index].detachControl(canvas);
- }
- // Release lights
- while (this.lights.length) {
- this.lights[0].dispose();
- }
- // Release meshes
- while (this.meshes.length) {
- this.meshes[0].dispose(true);
- }
- // Release cameras
- while (this.cameras.length) {
- this.cameras[0].dispose();
- }
- // Release materials
- while (this.materials.length) {
- this.materials[0].dispose();
- }
- // Release particles
- while (this.particleSystems.length) {
- this.particleSystems[0].dispose();
- }
- // Release sprites
- while (this.spriteManagers.length) {
- this.spriteManagers[0].dispose();
- }
- // Release layers
- while (this.layers.length) {
- this.layers[0].dispose();
- }
- // Release textures
- while (this.textures.length) {
- this.textures[0].dispose();
- }
- // Post-processes
- this.postProcessManager.dispose();
- // Physics
- if (this._physicsEngine) {
- this.disablePhysicsEngine();
- }
- // Remove from engine
- index = this._engine.scenes.indexOf(this);
- if (index > -1) {
- this._engine.scenes.splice(index, 1);
- }
- this._engine.wipeCaches();
- };
- // Release sounds & sounds tracks
- Scene.prototype.disposeSounds = function () {
- this.mainSoundTrack.dispose();
- for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
- this.soundTracks[scIndex].dispose();
- }
- };
- // Octrees
- Scene.prototype.getWorldExtends = function () {
- var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
- var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
- for (var index = 0; index < this.meshes.length; index++) {
- var mesh = this.meshes[index];
- mesh.computeWorldMatrix(true);
- var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
- var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
- BABYLON.Tools.CheckExtends(minBox, min, max);
- BABYLON.Tools.CheckExtends(maxBox, min, max);
- }
- return {
- min: min,
- max: max
- };
- };
- Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
- if (maxCapacity === void 0) { maxCapacity = 64; }
- if (maxDepth === void 0) { maxDepth = 2; }
- if (!this._selectionOctree) {
- this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
- }
- var worldExtends = this.getWorldExtends();
- // Update octree
- this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
- return this._selectionOctree;
- };
- // Picking
- Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
- if (cameraViewSpace === void 0) { cameraViewSpace = false; }
- var engine = this._engine;
- if (!camera) {
- if (!this.activeCamera)
- throw new Error("Active camera not set");
- camera = this.activeCamera;
- }
- var cameraViewport = camera.viewport;
- var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
- // Moving coordinates to local viewport world
- x = x / this._engine.getHardwareScalingLevel() - viewport.x;
- y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
- return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
- // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
- };
- Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
- var engine = this._engine;
- if (!camera) {
- if (!this.activeCamera)
- throw new Error("Active camera not set");
- camera = this.activeCamera;
- }
- var cameraViewport = camera.viewport;
- var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
- var identity = BABYLON.Matrix.Identity();
- // Moving coordinates to local viewport world
- x = x / this._engine.getHardwareScalingLevel() - viewport.x;
- y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
- return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
- };
- Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
- var pickingInfo = null;
- for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
- var mesh = this.meshes[meshIndex];
- if (predicate) {
- if (!predicate(mesh)) {
- continue;
- }
- }
- else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
- continue;
- }
- var world = mesh.getWorldMatrix();
- var ray = rayFunction(world);
- var result = mesh.intersects(ray, fastCheck);
- if (!result || !result.hit)
- continue;
- if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
- continue;
- pickingInfo = result;
- if (fastCheck) {
- break;
- }
- }
- return pickingInfo || new BABYLON.PickingInfo();
- };
- Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
- var pickingInfo = null;
- camera = camera || this.activeCamera;
- if (this.spriteManagers.length > 0) {
- for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
- var spriteManager = this.spriteManagers[spriteIndex];
- if (!spriteManager.isPickable) {
- continue;
- }
- var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
- if (!result || !result.hit)
- continue;
- if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
- continue;
- pickingInfo = result;
- if (fastCheck) {
- break;
- }
- }
- }
- return pickingInfo || new BABYLON.PickingInfo();
- };
- Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
- var _this = this;
- /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
- /// <param name="x">X position on screen</param>
- /// <param name="y">Y position on screen</param>
- /// <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>
- /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
- /// <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>
- return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
- };
- Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
- /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
- /// <param name="x">X position on screen</param>
- /// <param name="y">Y position on screen</param>
- /// <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>
- /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
- /// <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>
- return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
- };
- Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
- var _this = this;
- return this._internalPick(function (world) {
- if (!_this._pickWithRayInverseMatrix) {
- _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
- }
- world.invertToRef(_this._pickWithRayInverseMatrix);
- return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
- }, predicate, fastCheck);
- };
- Scene.prototype.setPointerOverMesh = function (mesh) {
- if (this._pointerOverMesh === mesh) {
- return;
- }
- if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
- this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
- }
- this._pointerOverMesh = mesh;
- if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
- this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
- }
- };
- Scene.prototype.getPointerOverMesh = function () {
- return this._pointerOverMesh;
- };
- Scene.prototype.setPointerOverSprite = function (sprite) {
- if (this._pointerOverSprite === sprite) {
- return;
- }
- if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
- this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
- }
- this._pointerOverSprite = sprite;
- if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
- this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
- }
- };
- Scene.prototype.getPointerOverSprite = function () {
- return this._pointerOverSprite;
- };
- // Physics
- Scene.prototype.getPhysicsEngine = function () {
- return this._physicsEngine;
- };
- /**
- * Enables physics to the current scene
- * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
- * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
- * @return {boolean} was the physics engine initialized
- */
- Scene.prototype.enablePhysics = function (gravity, plugin) {
- if (this._physicsEngine) {
- return true;
- }
- try {
- this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
- return true;
- }
- catch (e) {
- BABYLON.Tools.Error(e.message);
- return false;
- }
- };
- Scene.prototype.disablePhysicsEngine = function () {
- if (!this._physicsEngine) {
- return;
- }
- this._physicsEngine.dispose();
- this._physicsEngine = undefined;
- };
- Scene.prototype.isPhysicsEnabled = function () {
- return this._physicsEngine !== undefined;
- };
- /**
- *
- * Sets the gravity of the physics engine (and NOT of the scene)
- * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
- */
- Scene.prototype.setGravity = function (gravity) {
- BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
- if (!this._physicsEngine) {
- return;
- }
- this._physicsEngine.setGravity(gravity);
- };
- /**
- * Legacy support, using the new API
- * @Deprecated
- */
- Scene.prototype.createCompoundImpostor = function (parts, options) {
- BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
- if (parts.parts) {
- options = parts;
- parts = parts.parts;
- }
- var mainMesh = parts[0].mesh;
- mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
- for (var index = 1; index < parts.length; index++) {
- var mesh = parts[index].mesh;
- if (mesh.parent !== mainMesh) {
- mesh.position = mesh.position.subtract(mainMesh.position);
- mesh.parent = mainMesh;
- }
- mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
- }
- mainMesh.physicsImpostor.forceUpdate();
- };
- Scene.prototype.deleteCompoundImpostor = function (compound) {
- var mesh = compound.parts[0].mesh;
- mesh.physicsImpostor.dispose();
- mesh.physicsImpostor = null;
- };
- // Misc.
- Scene.prototype.createDefaultCameraOrLight = function () {
- // Light
- if (this.lights.length === 0) {
- new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
- }
- // Camera
- if (!this.activeCamera) {
- var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
- // Compute position
- var worldExtends = this.getWorldExtends();
- var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
- camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
- camera.setTarget(worldCenter);
- this.activeCamera = camera;
- }
- };
- // Tags
- Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
- if (tagsQuery === undefined) {
- // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
- return list;
- }
- var listByTags = [];
- forEach = forEach || (function (item) { return; });
- for (var i in list) {
- var item = list[i];
- if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
- listByTags.push(item);
- forEach(item);
- }
- }
- return listByTags;
- };
- Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
- return this._getByTags(this.meshes, tagsQuery, forEach);
- };
- Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
- return this._getByTags(this.cameras, tagsQuery, forEach);
- };
- Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
- return this._getByTags(this.lights, tagsQuery, forEach);
- };
- Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
- return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
- };
- // Statics
- Scene._FOGMODE_NONE = 0;
- Scene._FOGMODE_EXP = 1;
- Scene._FOGMODE_EXP2 = 2;
- Scene._FOGMODE_LINEAR = 3;
- Scene.MinDeltaTime = 1.0;
- Scene.MaxDeltaTime = 1000.0;
- return Scene;
- })();
- BABYLON.Scene = Scene;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var VertexBuffer = (function () {
- function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
- if (engine instanceof BABYLON.Mesh) {
- this._engine = engine.getScene().getEngine();
- }
- else {
- this._engine = engine;
- }
- this._updatable = updatable;
- this._data = data;
- if (!postponeInternalCreation) {
- this.create();
- }
- this._kind = kind;
- if (stride) {
- this._strideSize = stride;
- return;
- }
- // Deduce stride from kind
- switch (kind) {
- case VertexBuffer.PositionKind:
- this._strideSize = 3;
- break;
- case VertexBuffer.NormalKind:
- this._strideSize = 3;
- break;
- case VertexBuffer.UVKind:
- case VertexBuffer.UV2Kind:
- case VertexBuffer.UV3Kind:
- case VertexBuffer.UV4Kind:
- case VertexBuffer.UV5Kind:
- case VertexBuffer.UV6Kind:
- this._strideSize = 2;
- break;
- case VertexBuffer.ColorKind:
- this._strideSize = 4;
- break;
- case VertexBuffer.MatricesIndicesKind:
- case VertexBuffer.MatricesIndicesExtraKind:
- this._strideSize = 4;
- break;
- case VertexBuffer.MatricesWeightsKind:
- case VertexBuffer.MatricesWeightsExtraKind:
- this._strideSize = 4;
- break;
- }
- }
- // Properties
- VertexBuffer.prototype.isUpdatable = function () {
- return this._updatable;
- };
- VertexBuffer.prototype.getData = function () {
- return this._data;
- };
- VertexBuffer.prototype.getBuffer = function () {
- return this._buffer;
- };
- VertexBuffer.prototype.getStrideSize = function () {
- return this._strideSize;
- };
- // Methods
- VertexBuffer.prototype.create = function (data) {
- if (!data && this._buffer) {
- return; // nothing to do
- }
- data = data || this._data;
- if (!this._buffer) {
- if (this._updatable) {
- this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
- }
- else {
- this._buffer = this._engine.createVertexBuffer(data);
- }
- }
- if (this._updatable) {
- this._engine.updateDynamicVertexBuffer(this._buffer, data);
- this._data = data;
- }
- };
- VertexBuffer.prototype.update = function (data) {
- this.create(data);
- };
- VertexBuffer.prototype.updateDirectly = function (data, offset) {
- if (!this._buffer) {
- return;
- }
- if (this._updatable) {
- this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
- this._data = null;
- }
- };
- VertexBuffer.prototype.dispose = function () {
- if (!this._buffer) {
- return;
- }
- if (this._engine._releaseBuffer(this._buffer)) {
- this._buffer = null;
- }
- };
- Object.defineProperty(VertexBuffer, "PositionKind", {
- get: function () {
- return VertexBuffer._PositionKind;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(VertexBuffer, "NormalKind", {
- get: function () {
- return VertexBuffer._NormalKind;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(VertexBuffer, "UVKind", {
- get: function () {
- return VertexBuffer._UVKind;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(VertexBuffer, "UV2Kind", {
- get: function () {
- return VertexBuffer._UV2Kind;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(VertexBuffer, "UV3Kind", {
- get: function () {
- return VertexBuffer._UV3Kind;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(VertexBuffer, "UV4Kind", {
- get: function () {
- return VertexBuffer._UV4Kind;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(VertexBuffer, "UV5Kind", {
- get: function () {
- return VertexBuffer._UV5Kind;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(VertexBuffer, "UV6Kind", {
- get: function () {
- return VertexBuffer._UV6Kind;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(VertexBuffer, "ColorKind", {
- get: function () {
- return VertexBuffer._ColorKind;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
- get: function () {
- return VertexBuffer._MatricesIndicesKind;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
- get: function () {
- return VertexBuffer._MatricesWeightsKind;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
- get: function () {
- return VertexBuffer._MatricesIndicesExtraKind;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
- get: function () {
- return VertexBuffer._MatricesWeightsExtraKind;
- },
- enumerable: true,
- configurable: true
- });
- // Enums
- VertexBuffer._PositionKind = "position";
- VertexBuffer._NormalKind = "normal";
- VertexBuffer._UVKind = "uv";
- VertexBuffer._UV2Kind = "uv2";
- VertexBuffer._UV3Kind = "uv3";
- VertexBuffer._UV4Kind = "uv4";
- VertexBuffer._UV5Kind = "uv5";
- VertexBuffer._UV6Kind = "uv6";
- VertexBuffer._ColorKind = "color";
- VertexBuffer._MatricesIndicesKind = "matricesIndices";
- VertexBuffer._MatricesWeightsKind = "matricesWeights";
- VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
- VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
- return VertexBuffer;
- })();
- BABYLON.VertexBuffer = VertexBuffer;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- /**
- * Creates an instance based on a source mesh.
- */
- var InstancedMesh = (function (_super) {
- __extends(InstancedMesh, _super);
- function InstancedMesh(name, source) {
- _super.call(this, name, source.getScene());
- source.instances.push(this);
- this._sourceMesh = source;
- this.position.copyFrom(source.position);
- this.rotation.copyFrom(source.rotation);
- this.scaling.copyFrom(source.scaling);
- if (source.rotationQuaternion) {
- this.rotationQuaternion = source.rotationQuaternion.clone();
- }
- this.infiniteDistance = source.infiniteDistance;
- this.setPivotMatrix(source.getPivotMatrix());
- this.refreshBoundingInfo();
- this._syncSubMeshes();
- }
- Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
- // Methods
- get: function () {
- return this._sourceMesh.receiveShadows;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(InstancedMesh.prototype, "material", {
- get: function () {
- return this._sourceMesh.material;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(InstancedMesh.prototype, "visibility", {
- get: function () {
- return this._sourceMesh.visibility;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(InstancedMesh.prototype, "skeleton", {
- get: function () {
- return this._sourceMesh.skeleton;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
- get: function () {
- return this._sourceMesh.renderingGroupId;
- },
- enumerable: true,
- configurable: true
- });
- InstancedMesh.prototype.getTotalVertices = function () {
- return this._sourceMesh.getTotalVertices();
- };
- Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
- get: function () {
- return this._sourceMesh;
- },
- enumerable: true,
- configurable: true
- });
- InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
- return this._sourceMesh.getVerticesData(kind, copyWhenShared);
- };
- InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
- return this._sourceMesh.isVerticesDataPresent(kind);
- };
- InstancedMesh.prototype.getIndices = function () {
- return this._sourceMesh.getIndices();
- };
- Object.defineProperty(InstancedMesh.prototype, "_positions", {
- get: function () {
- return this._sourceMesh._positions;
- },
- enumerable: true,
- configurable: true
- });
- InstancedMesh.prototype.refreshBoundingInfo = function () {
- var meshBB = this._sourceMesh.getBoundingInfo();
- this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
- this._updateBoundingInfo();
- };
- InstancedMesh.prototype._preActivate = function () {
- if (this._currentLOD) {
- this._currentLOD._preActivate();
- }
- };
- InstancedMesh.prototype._activate = function (renderId) {
- if (this._currentLOD) {
- this._currentLOD._registerInstanceForRenderId(this, renderId);
- }
- };
- InstancedMesh.prototype.getLOD = function (camera) {
- this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
- if (this._currentLOD === this.sourceMesh) {
- return this;
- }
- return this._currentLOD;
- };
- InstancedMesh.prototype._syncSubMeshes = function () {
- this.releaseSubMeshes();
- if (this._sourceMesh.subMeshes) {
- for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
- this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
- }
- }
- };
- InstancedMesh.prototype._generatePointsArray = function () {
- return this._sourceMesh._generatePointsArray();
- };
- // Clone
- InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
- var result = this._sourceMesh.createInstance(name);
- // Deep copy
- BABYLON.Tools.DeepCopy(this, result, ["name"], []);
- // Bounding info
- this.refreshBoundingInfo();
- // Parent
- if (newParent) {
- result.parent = newParent;
- }
- if (!doNotCloneChildren) {
- // Children
- for (var index = 0; index < this.getScene().meshes.length; index++) {
- var mesh = this.getScene().meshes[index];
- if (mesh.parent === this) {
- mesh.clone(mesh.name, result);
- }
- }
- }
- result.computeWorldMatrix(true);
- return result;
- };
- // Dispoe
- InstancedMesh.prototype.dispose = function (doNotRecurse) {
- // Remove from mesh
- var index = this._sourceMesh.instances.indexOf(this);
- this._sourceMesh.instances.splice(index, 1);
- _super.prototype.dispose.call(this, doNotRecurse);
- };
- return InstancedMesh;
- })(BABYLON.AbstractMesh);
- BABYLON.InstancedMesh = InstancedMesh;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var _InstancesBatch = (function () {
- function _InstancesBatch() {
- this.mustReturn = false;
- this.visibleInstances = new Array();
- this.renderSelf = new Array();
- }
- return _InstancesBatch;
- })();
- BABYLON._InstancesBatch = _InstancesBatch;
- var Mesh = (function (_super) {
- __extends(Mesh, _super);
- /**
- * @constructor
- * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
- * @param {Scene} scene - The scene to add this mesh to.
- * @param {Node} parent - The parent of this mesh, if it has one
- * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
- * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
- * When false, achieved by calling a clone(), also passing False.
- * This will make creation of children, recursive.
- */
- function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
- if (parent === void 0) { parent = null; }
- if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
- _super.call(this, name, scene);
- // Events
- /**
- * An event triggered before rendering the mesh
- * @type {BABYLON.Observable}
- */
- this.onBeforeRenderObservable = new BABYLON.Observable();
- /**
- * An event triggered after rendering the mesh
- * @type {BABYLON.Observable}
- */
- this.onAfterRenderObservable = new BABYLON.Observable();
- /**
- * An event triggered before drawing the mesh
- * @type {BABYLON.Observable}
- */
- this.onBeforeDrawObservable = new BABYLON.Observable();
- // Members
- this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
- this.instances = new Array();
- this._LODLevels = new Array();
- this._visibleInstances = {};
- this._renderIdForInstances = new Array();
- this._batchCache = new _InstancesBatch();
- this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
- this._sideOrientation = Mesh._DEFAULTSIDE;
- this._areNormalsFrozen = false; // Will be used by ribbons mainly
- if (source) {
- // Geometry
- if (source._geometry) {
- source._geometry.applyToMesh(this);
- }
- // Deep copy
- BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
- // Pivot
- this.setPivotMatrix(source.getPivotMatrix());
- this.id = name + "." + source.id;
- // Material
- this.material = source.material;
- var index;
- if (!doNotCloneChildren) {
- // Children
- for (index = 0; index < scene.meshes.length; index++) {
- var mesh = scene.meshes[index];
- if (mesh.parent === source) {
- // doNotCloneChildren is always going to be False
- var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
- }
- }
- }
- // Physics clone
- var physicsEngine = this.getScene().getPhysicsEngine();
- if (clonePhysicsImpostor && physicsEngine) {
- var impostor = physicsEngine.getImpostorForPhysicsObject(source);
- if (impostor) {
- this.physicsImpostor = impostor.clone(this);
- }
- }
- // Particles
- for (index = 0; index < scene.particleSystems.length; index++) {
- var system = scene.particleSystems[index];
- if (system.emitter === source) {
- system.clone(system.name, this);
- }
- }
- this.computeWorldMatrix(true);
- }
- // Parent
- if (parent !== null) {
- this.parent = parent;
- }
- }
- Object.defineProperty(Mesh, "FRONTSIDE", {
- /**
- * Mesh side orientation : usually the external or front surface
- */
- get: function () {
- return Mesh._FRONTSIDE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Mesh, "BACKSIDE", {
- /**
- * Mesh side orientation : usually the internal or back surface
- */
- get: function () {
- return Mesh._BACKSIDE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Mesh, "DOUBLESIDE", {
- /**
- * Mesh side orientation : both internal and external or front and back surfaces
- */
- get: function () {
- return Mesh._DOUBLESIDE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Mesh, "DEFAULTSIDE", {
- /**
- * Mesh side orientation : by default, `FRONTSIDE`
- */
- get: function () {
- return Mesh._DEFAULTSIDE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Mesh, "NO_CAP", {
- /**
- * Mesh cap setting : no cap
- */
- get: function () {
- return Mesh._NO_CAP;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Mesh, "CAP_START", {
- /**
- * Mesh cap setting : one cap at the beginning of the mesh
- */
- get: function () {
- return Mesh._CAP_START;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Mesh, "CAP_END", {
- /**
- * Mesh cap setting : one cap at the end of the mesh
- */
- get: function () {
- return Mesh._CAP_END;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Mesh, "CAP_ALL", {
- /**
- * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
- */
- get: function () {
- return Mesh._CAP_ALL;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
- set: function (callback) {
- if (this._onBeforeDrawObserver) {
- this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
- }
- this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
- },
- enumerable: true,
- configurable: true
- });
- // Methods
- /**
- * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
- */
- Mesh.prototype.toString = function (fullDetails) {
- var ret = _super.prototype.toString.call(this, fullDetails);
- ret += ", n vertices: " + this.getTotalVertices();
- ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
- if (this.animations) {
- for (var i = 0; i < this.animations.length; i++) {
- ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
- }
- }
- if (fullDetails) {
- ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
- }
- return ret;
- };
- Object.defineProperty(Mesh.prototype, "hasLODLevels", {
- get: function () {
- return this._LODLevels.length > 0;
- },
- enumerable: true,
- configurable: true
- });
- Mesh.prototype._sortLODLevels = function () {
- this._LODLevels.sort(function (a, b) {
- if (a.distance < b.distance) {
- return 1;
- }
- if (a.distance > b.distance) {
- return -1;
- }
- return 0;
- });
- };
- /**
- * Add a mesh as LOD level triggered at the given distance.
- * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
- * @param {number} distance - the distance from the center of the object to show this level
- * @param {Mesh} mesh - the mesh to be added as LOD level
- * @return {Mesh} this mesh (for chaining)
- */
- Mesh.prototype.addLODLevel = function (distance, mesh) {
- if (mesh && mesh._masterMesh) {
- BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
- return this;
- }
- var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
- this._LODLevels.push(level);
- if (mesh) {
- mesh._masterMesh = this;
- }
- this._sortLODLevels();
- return this;
- };
- /**
- * Returns the LOD level mesh at the passed distance or null if not found.
- * It is related to the method `addLODLevel(distance, mesh)`.
- * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
- */
- Mesh.prototype.getLODLevelAtDistance = function (distance) {
- for (var index = 0; index < this._LODLevels.length; index++) {
- var level = this._LODLevels[index];
- if (level.distance === distance) {
- return level.mesh;
- }
- }
- return null;
- };
- /**
- * Remove a mesh from the LOD array
- * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
- * @param {Mesh} mesh - the mesh to be removed.
- * @return {Mesh} this mesh (for chaining)
- */
- Mesh.prototype.removeLODLevel = function (mesh) {
- for (var index = 0; index < this._LODLevels.length; index++) {
- if (this._LODLevels[index].mesh === mesh) {
- this._LODLevels.splice(index, 1);
- if (mesh) {
- mesh._masterMesh = null;
- }
- }
- }
- this._sortLODLevels();
- return this;
- };
- /**
- * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
- * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
- */
- Mesh.prototype.getLOD = function (camera, boundingSphere) {
- if (!this._LODLevels || this._LODLevels.length === 0) {
- return this;
- }
- var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
- if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
- if (this.onLODLevelSelection) {
- this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
- }
- return this;
- }
- for (var index = 0; index < this._LODLevels.length; index++) {
- var level = this._LODLevels[index];
- if (level.distance < distanceToCamera) {
- if (level.mesh) {
- level.mesh._preActivate();
- level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
- }
- if (this.onLODLevelSelection) {
- this.onLODLevelSelection(distanceToCamera, this, level.mesh);
- }
- return level.mesh;
- }
- }
- if (this.onLODLevelSelection) {
- this.onLODLevelSelection(distanceToCamera, this, this);
- }
- return this;
- };
- Object.defineProperty(Mesh.prototype, "geometry", {
- /**
- * Returns the mesh internal `Geometry` object.
- */
- get: function () {
- return this._geometry;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
- */
- Mesh.prototype.getTotalVertices = function () {
- if (!this._geometry) {
- return 0;
- }
- return this._geometry.getTotalVertices();
- };
- /**
- * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
- * 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.
- * Returns null if the mesh has no geometry or no vertex buffer.
- * Possible `kind` values :
- * - BABYLON.VertexBuffer.PositionKind
- * - BABYLON.VertexBuffer.UVKind
- * - BABYLON.VertexBuffer.UV2Kind
- * - BABYLON.VertexBuffer.UV3Kind
- * - BABYLON.VertexBuffer.UV4Kind
- * - BABYLON.VertexBuffer.UV5Kind
- * - BABYLON.VertexBuffer.UV6Kind
- * - BABYLON.VertexBuffer.ColorKind
- * - BABYLON.VertexBuffer.MatricesIndicesKind
- * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
- * - BABYLON.VertexBuffer.MatricesWeightsKind
- * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
- */
- Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
- if (!this._geometry) {
- return null;
- }
- return this._geometry.getVerticesData(kind, copyWhenShared);
- };
- /**
- * Returns the mesh `VertexBuffer` object from the requested `kind` : positions, indices, normals, etc.
- * Returns `undefined` if the mesh has no geometry.
- * Possible `kind` values :
- * - BABYLON.VertexBuffer.PositionKind
- * - BABYLON.VertexBuffer.UVKind
- * - BABYLON.VertexBuffer.UV2Kind
- * - BABYLON.VertexBuffer.UV3Kind
- * - BABYLON.VertexBuffer.UV4Kind
- * - BABYLON.VertexBuffer.UV5Kind
- * - BABYLON.VertexBuffer.UV6Kind
- * - BABYLON.VertexBuffer.ColorKind
- * - BABYLON.VertexBuffer.MatricesIndicesKind
- * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
- * - BABYLON.VertexBuffer.MatricesWeightsKind
- * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
- */
- Mesh.prototype.getVertexBuffer = function (kind) {
- if (!this._geometry) {
- return undefined;
- }
- return this._geometry.getVertexBuffer(kind);
- };
- /**
- * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
- * Possible `kind` values :
- * - BABYLON.VertexBuffer.PositionKind
- * - BABYLON.VertexBuffer.UVKind
- * - BABYLON.VertexBuffer.UV2Kind
- * - BABYLON.VertexBuffer.UV3Kind
- * - BABYLON.VertexBuffer.UV4Kind
- * - BABYLON.VertexBuffer.UV5Kind
- * - BABYLON.VertexBuffer.UV6Kind
- * - BABYLON.VertexBuffer.ColorKind
- * - BABYLON.VertexBuffer.MatricesIndicesKind
- * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
- * - BABYLON.VertexBuffer.MatricesWeightsKind
- * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
- */
- Mesh.prototype.isVerticesDataPresent = function (kind) {
- if (!this._geometry) {
- if (this._delayInfo) {
- return this._delayInfo.indexOf(kind) !== -1;
- }
- return false;
- }
- return this._geometry.isVerticesDataPresent(kind);
- };
- /**
- * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
- * Possible `kind` values :
- * - BABYLON.VertexBuffer.PositionKind
- * - BABYLON.VertexBuffer.UVKind
- * - BABYLON.VertexBuffer.UV2Kind
- * - BABYLON.VertexBuffer.UV3Kind
- * - BABYLON.VertexBuffer.UV4Kind
- * - BABYLON.VertexBuffer.UV5Kind
- * - BABYLON.VertexBuffer.UV6Kind
- * - BABYLON.VertexBuffer.ColorKind
- * - BABYLON.VertexBuffer.MatricesIndicesKind
- * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
- * - BABYLON.VertexBuffer.MatricesWeightsKind
- * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
- */
- Mesh.prototype.getVerticesDataKinds = function () {
- if (!this._geometry) {
- var result = [];
- if (this._delayInfo) {
- for (var kind in this._delayInfo) {
- result.push(kind);
- }
- }
- return result;
- }
- return this._geometry.getVerticesDataKinds();
- };
- /**
- * Returns a positive integer : the total number of indices in this mesh geometry.
- * Returns zero if the mesh has no geometry.
- */
- Mesh.prototype.getTotalIndices = function () {
- if (!this._geometry) {
- return 0;
- }
- return this._geometry.getTotalIndices();
- };
- /**
- * Returns an array of integers or a Int32Array populated with the mesh indices.
- * 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.
- * Returns an empty array if the mesh has no geometry.
- */
- Mesh.prototype.getIndices = function (copyWhenShared) {
- if (!this._geometry) {
- return [];
- }
- return this._geometry.getIndices(copyWhenShared);
- };
- Object.defineProperty(Mesh.prototype, "isBlocked", {
- get: function () {
- return this._masterMesh !== null && this._masterMesh !== undefined;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
- */
- Mesh.prototype.isReady = function () {
- if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
- return false;
- }
- return _super.prototype.isReady.call(this);
- };
- /**
- * Boolean : true if the mesh has been disposed.
- */
- Mesh.prototype.isDisposed = function () {
- return this._isDisposed;
- };
- Object.defineProperty(Mesh.prototype, "sideOrientation", {
- get: function () {
- return this._sideOrientation;
- },
- /**
- * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
- * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
- */
- set: function (sideO) {
- this._sideOrientation = sideO;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
- /**
- * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
- * This property is pertinent only for updatable parametric shapes.
- */
- get: function () {
- return this._areNormalsFrozen;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
- * It has no effect at all on other shapes.
- * It prevents the mesh normals from being recomputed on next `positions` array update.
- */
- Mesh.prototype.freezeNormals = function () {
- this._areNormalsFrozen = true;
- };
- /**
- * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
- * It has no effect at all on other shapes.
- * It reactivates the mesh normals computation if it was previously frozen.
- */
- Mesh.prototype.unfreezeNormals = function () {
- this._areNormalsFrozen = false;
- };
- // Methods
- Mesh.prototype._preActivate = function () {
- var sceneRenderId = this.getScene().getRenderId();
- if (this._preActivateId === sceneRenderId) {
- return;
- }
- this._preActivateId = sceneRenderId;
- this._visibleInstances = null;
- };
- Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
- if (this._visibleInstances) {
- this._visibleInstances.intermediateDefaultRenderId = renderId;
- }
- };
- Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
- if (!this._visibleInstances) {
- this._visibleInstances = {};
- this._visibleInstances.defaultRenderId = renderId;
- this._visibleInstances.selfDefaultRenderId = this._renderId;
- }
- if (!this._visibleInstances[renderId]) {
- this._visibleInstances[renderId] = new Array();
- }
- this._visibleInstances[renderId].push(instance);
- };
- /**
- * This method recomputes and sets a new `BoundingInfo` to the mesh unless it is locked.
- * This means the mesh underlying bounding box and sphere are recomputed.
- */
- Mesh.prototype.refreshBoundingInfo = function () {
- if (this._boundingInfo.isLocked) {
- return;
- }
- var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- if (data) {
- var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
- this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
- }
- if (this.subMeshes) {
- for (var index = 0; index < this.subMeshes.length; index++) {
- this.subMeshes[index].refreshBoundingInfo();
- }
- }
- this._updateBoundingInfo();
- };
- Mesh.prototype._createGlobalSubMesh = function () {
- var totalVertices = this.getTotalVertices();
- if (!totalVertices || !this.getIndices()) {
- return null;
- }
- this.releaseSubMeshes();
- return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
- };
- Mesh.prototype.subdivide = function (count) {
- if (count < 1) {
- return;
- }
- var totalIndices = this.getTotalIndices();
- var subdivisionSize = (totalIndices / count) | 0;
- var offset = 0;
- // Ensure that subdivisionSize is a multiple of 3
- while (subdivisionSize % 3 !== 0) {
- subdivisionSize++;
- }
- this.releaseSubMeshes();
- for (var index = 0; index < count; index++) {
- if (offset >= totalIndices) {
- break;
- }
- BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
- offset += subdivisionSize;
- }
- this.synchronizeInstances();
- };
- /**
- * Sets the vertex data of the mesh geometry for the requested `kind`.
- * If the mesh has no geometry, a new `Geometry` object is set to the mesh and then passed this vertex data.
- * The `data` are either a numeric array either a Float32Array.
- * The parameter `updatable` is passed as is to the underlying `Geometry` object constructor (if initianilly none) or updater.
- * 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).
- * Note that a new underlying `VertexBuffer` object is created each call.
- * If the `kind` is the `PositionKind`, the mesh `BoundingInfo` is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
- *
- * Possible `kind` values :
- * - BABYLON.VertexBuffer.PositionKind
- * - BABYLON.VertexBuffer.UVKind
- * - BABYLON.VertexBuffer.UV2Kind
- * - BABYLON.VertexBuffer.UV3Kind
- * - BABYLON.VertexBuffer.UV4Kind
- * - BABYLON.VertexBuffer.UV5Kind
- * - BABYLON.VertexBuffer.UV6Kind
- * - BABYLON.VertexBuffer.ColorKind
- * - BABYLON.VertexBuffer.MatricesIndicesKind
- * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
- * - BABYLON.VertexBuffer.MatricesWeightsKind
- * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
- */
- Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
- if (!this._geometry) {
- var vertexData = new BABYLON.VertexData();
- vertexData.set(data, kind);
- var scene = this.getScene();
- new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
- }
- else {
- this._geometry.setVerticesData(kind, data, updatable, stride);
- }
- };
- /**
- * Updates the existing vertex data of the mesh geometry for the requested `kind`.
- * If the mesh has no geometry, it is simply returned as it is.
- * The `data` are either a numeric array either a Float32Array.
- * No new underlying `VertexBuffer` object is created.
- * 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.
- * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
- *
- * Possible `kind` values :
- * - BABYLON.VertexBuffer.PositionKind
- * - BABYLON.VertexBuffer.UVKind
- * - BABYLON.VertexBuffer.UV2Kind
- * - BABYLON.VertexBuffer.UV3Kind
- * - BABYLON.VertexBuffer.UV4Kind
- * - BABYLON.VertexBuffer.UV5Kind
- * - BABYLON.VertexBuffer.UV6Kind
- * - BABYLON.VertexBuffer.ColorKind
- * - BABYLON.VertexBuffer.MatricesIndicesKind
- * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
- * - BABYLON.VertexBuffer.MatricesWeightsKind
- * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
- */
- Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
- if (!this._geometry) {
- return;
- }
- if (!makeItUnique) {
- this._geometry.updateVerticesData(kind, data, updateExtends);
- }
- else {
- this.makeGeometryUnique();
- this.updateVerticesData(kind, data, updateExtends, false);
- }
- };
- /**
- * Deprecated since BabylonJS v2.3
- */
- Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
- BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
- if (!this._geometry) {
- return;
- }
- if (!makeItUnique) {
- this._geometry.updateVerticesDataDirectly(kind, data, offset);
- }
- else {
- this.makeGeometryUnique();
- this.updateVerticesDataDirectly(kind, data, offset, false);
- }
- };
- /**
- * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
- * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
- * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
- * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
- */
- Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
- if (computeNormals === void 0) { computeNormals = true; }
- var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- positionFunction(positions);
- this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
- if (computeNormals) {
- var indices = this.getIndices();
- var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
- BABYLON.VertexData.ComputeNormals(positions, indices, normals);
- this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
- }
- };
- Mesh.prototype.makeGeometryUnique = function () {
- if (!this._geometry) {
- return;
- }
- var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
- geometry.applyToMesh(this);
- };
- /**
- * Sets the mesh indices.
- * Expects an array populated with integers or a Int32Array.
- * If the mesh has no geometry, a new `Geometry` object is created and set to the mesh.
- * This method creates a new index buffer each call.
- */
- Mesh.prototype.setIndices = function (indices, totalVertices) {
- if (!this._geometry) {
- var vertexData = new BABYLON.VertexData();
- vertexData.indices = indices;
- var scene = this.getScene();
- new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
- }
- else {
- this._geometry.setIndices(indices, totalVertices);
- }
- };
- Mesh.prototype._bind = function (subMesh, effect, fillMode) {
- var engine = this.getScene().getEngine();
- // Wireframe
- var indexToBind;
- if (this._unIndexed) {
- indexToBind = null;
- }
- else {
- switch (fillMode) {
- case BABYLON.Material.PointFillMode:
- indexToBind = null;
- break;
- case BABYLON.Material.WireFrameFillMode:
- indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
- break;
- default:
- case BABYLON.Material.TriangleFillMode:
- indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
- break;
- }
- }
- // VBOs
- engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
- };
- Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
- if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
- return;
- }
- this.onBeforeDrawObservable.notifyObservers(this);
- var engine = this.getScene().getEngine();
- // Draw order
- switch (fillMode) {
- case BABYLON.Material.PointFillMode:
- engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
- break;
- case BABYLON.Material.WireFrameFillMode:
- if (this._unIndexed) {
- engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
- }
- else {
- engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
- }
- break;
- default:
- if (this._unIndexed) {
- engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
- }
- else {
- engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
- }
- }
- };
- /**
- * Registers for this mesh a javascript function called just before the rendering process.
- * This function is passed the current mesh and doesn't return anything.
- */
- Mesh.prototype.registerBeforeRender = function (func) {
- this.onBeforeRenderObservable.add(func);
- };
- /**
- * Disposes a previously registered javascript function called before the rendering.
- * This function is passed the current mesh and doesn't return anything.
- */
- Mesh.prototype.unregisterBeforeRender = function (func) {
- this.onBeforeRenderObservable.removeCallback(func);
- };
- /**
- * Registers for this mesh a javascript function called just after the rendering is complete.
- * This function is passed the current mesh and doesn't return anything.
- */
- Mesh.prototype.registerAfterRender = function (func) {
- this.onAfterRenderObservable.add(func);
- };
- /**
- * Disposes a previously registered javascript function called after the rendering.
- * This function is passed the current mesh and doesn't return anything.
- */
- Mesh.prototype.unregisterAfterRender = function (func) {
- this.onAfterRenderObservable.removeCallback(func);
- };
- Mesh.prototype._getInstancesRenderList = function (subMeshId) {
- var scene = this.getScene();
- this._batchCache.mustReturn = false;
- this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
- this._batchCache.visibleInstances[subMeshId] = null;
- if (this._visibleInstances) {
- var currentRenderId = scene.getRenderId();
- var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
- this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
- var selfRenderId = this._renderId;
- if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
- this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
- currentRenderId = Math.max(defaultRenderId, currentRenderId);
- selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
- }
- if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
- if (this._renderIdForInstances[subMeshId] === currentRenderId) {
- this._batchCache.mustReturn = true;
- return this._batchCache;
- }
- if (currentRenderId !== selfRenderId) {
- this._batchCache.renderSelf[subMeshId] = false;
- }
- }
- this._renderIdForInstances[subMeshId] = currentRenderId;
- }
- return this._batchCache;
- };
- Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
- var visibleInstances = batch.visibleInstances[subMesh._id];
- var matricesCount = visibleInstances.length + 1;
- var bufferSize = matricesCount * 16 * 4;
- while (this._instancesBufferSize < bufferSize) {
- this._instancesBufferSize *= 2;
- }
- if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
- if (this._worldMatricesInstancesBuffer) {
- engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
- }
- this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
- this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
- }
- var offset = 0;
- var instancesCount = 0;
- var world = this.getWorldMatrix();
- if (batch.renderSelf[subMesh._id]) {
- world.copyToArray(this._worldMatricesInstancesArray, offset);
- offset += 16;
- instancesCount++;
- }
- if (visibleInstances) {
- for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
- var instance = visibleInstances[instanceIndex];
- instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
- offset += 16;
- instancesCount++;
- }
- }
- var offsetLocation0 = effect.getAttributeLocationByName("world0");
- var offsetLocation1 = effect.getAttributeLocationByName("world1");
- var offsetLocation2 = effect.getAttributeLocationByName("world2");
- var offsetLocation3 = effect.getAttributeLocationByName("world3");
- var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
- engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
- this._draw(subMesh, fillMode, instancesCount);
- engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
- };
- Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
- var scene = this.getScene();
- var engine = scene.getEngine();
- if (hardwareInstancedRendering) {
- this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
- }
- else {
- if (batch.renderSelf[subMesh._id]) {
- // Draw
- if (onBeforeDraw) {
- onBeforeDraw(false, this.getWorldMatrix());
- }
- this._draw(subMesh, fillMode);
- }
- if (batch.visibleInstances[subMesh._id]) {
- for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
- var instance = batch.visibleInstances[subMesh._id][instanceIndex];
- // World
- var world = instance.getWorldMatrix();
- if (onBeforeDraw) {
- onBeforeDraw(true, world);
- }
- // Draw
- this._draw(subMesh, fillMode);
- }
- }
- }
- };
- /**
- * Triggers the draw call for the mesh.
- * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
- */
- Mesh.prototype.render = function (subMesh, enableAlphaMode) {
- var scene = this.getScene();
- // Managing instances
- var batch = this._getInstancesRenderList(subMesh._id);
- if (batch.mustReturn) {
- return;
- }
- // Checking geometry state
- if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
- return;
- }
- var callbackIndex;
- this.onBeforeRenderObservable.notifyObservers(this);
- var engine = scene.getEngine();
- var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
- // Material
- var effectiveMaterial = subMesh.getMaterial();
- if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
- return;
- }
- // Outline - step 1
- var savedDepthWrite = engine.getDepthWrite();
- if (this.renderOutline) {
- engine.setDepthWrite(false);
- scene.getOutlineRenderer().render(subMesh, batch);
- engine.setDepthWrite(savedDepthWrite);
- }
- effectiveMaterial._preBind();
- var effect = effectiveMaterial.getEffect();
- // Bind
- var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
- this._bind(subMesh, effect, fillMode);
- var world = this.getWorldMatrix();
- effectiveMaterial.bind(world, this);
- // Alpha mode
- if (enableAlphaMode) {
- engine.setAlphaMode(effectiveMaterial.alphaMode);
- }
- // Draw
- this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
- if (isInstance) {
- effectiveMaterial.bindOnlyWorldMatrix(world);
- }
- });
- // Unbind
- effectiveMaterial.unbind();
- // Outline - step 2
- if (this.renderOutline && savedDepthWrite) {
- engine.setDepthWrite(true);
- engine.setColorWrite(false);
- scene.getOutlineRenderer().render(subMesh, batch);
- engine.setColorWrite(true);
- }
- // Overlay
- if (this.renderOverlay) {
- var currentMode = engine.getAlphaMode();
- engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
- scene.getOutlineRenderer().render(subMesh, batch, true);
- engine.setAlphaMode(currentMode);
- }
- this.onAfterRenderObservable.notifyObservers(this);
- };
- /**
- * Returns an array populated with `ParticleSystem` objects whose the mesh is the emitter.
- */
- Mesh.prototype.getEmittedParticleSystems = function () {
- var results = new Array();
- for (var index = 0; index < this.getScene().particleSystems.length; index++) {
- var particleSystem = this.getScene().particleSystems[index];
- if (particleSystem.emitter === this) {
- results.push(particleSystem);
- }
- }
- return results;
- };
- /**
- * Returns an array populated with `ParticleSystem` objects whose the mesh or its children are the emitter.
- */
- Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
- var results = new Array();
- var descendants = this.getDescendants();
- descendants.push(this);
- for (var index = 0; index < this.getScene().particleSystems.length; index++) {
- var particleSystem = this.getScene().particleSystems[index];
- if (descendants.indexOf(particleSystem.emitter) !== -1) {
- results.push(particleSystem);
- }
- }
- return results;
- };
- Mesh.prototype._checkDelayState = function () {
- var _this = this;
- var that = this;
- var scene = this.getScene();
- if (this._geometry) {
- this._geometry.load(scene);
- }
- else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
- that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
- scene._addPendingData(that);
- var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
- BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
- if (data instanceof ArrayBuffer) {
- _this._delayLoadingFunction(data, _this);
- }
- else {
- _this._delayLoadingFunction(JSON.parse(data), _this);
- }
- _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
- scene._removePendingData(_this);
- }, function () { }, scene.database, getBinaryData);
- }
- };
- /**
- * Boolean, true is the mesh in the frustum defined by the `Plane` objects from the `frustumPlanes` array parameter.
- */
- Mesh.prototype.isInFrustum = function (frustumPlanes) {
- if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
- return false;
- }
- if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
- return false;
- }
- this._checkDelayState();
- return true;
- };
- /**
- * Sets the mesh material by the material or multiMaterial `id` property.
- * The material `id` is a string identifying the material or the multiMaterial.
- * This method returns nothing.
- */
- Mesh.prototype.setMaterialByID = function (id) {
- var materials = this.getScene().materials;
- var index;
- for (index = 0; index < materials.length; index++) {
- if (materials[index].id === id) {
- this.material = materials[index];
- return;
- }
- }
- // Multi
- var multiMaterials = this.getScene().multiMaterials;
- for (index = 0; index < multiMaterials.length; index++) {
- if (multiMaterials[index].id === id) {
- this.material = multiMaterials[index];
- return;
- }
- }
- };
- /**
- * Returns as a new array populated with the mesh material and/or skeleton, if any.
- */
- Mesh.prototype.getAnimatables = function () {
- var results = [];
- if (this.material) {
- results.push(this.material);
- }
- if (this.skeleton) {
- results.push(this.skeleton);
- }
- return results;
- };
- /**
- * Modifies the mesh geometry according to the passed transformation matrix.
- * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
- * The mesh normals are modified accordingly the same transformation.
- * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
- * Note that, under the hood, this method sets a new VertexBuffer each call.
- */
- Mesh.prototype.bakeTransformIntoVertices = function (transform) {
- // Position
- if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
- return;
- }
- this._resetPointsArrayCache();
- var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- var temp = [];
- var index;
- for (index = 0; index < data.length; index += 3) {
- BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
- }
- this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
- // Normals
- if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
- return;
- }
- data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
- temp = [];
- for (index = 0; index < data.length; index += 3) {
- BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
- }
- this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
- // flip faces?
- if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
- this.flipFaces();
- }
- };
- /**
- * Modifies the mesh geometry according to its own current World Matrix.
- * The mesh World Matrix is then reset.
- * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
- * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
- * Note that, under the hood, this method sets a new VertexBuffer each call.
- */
- Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
- this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
- this.scaling.copyFromFloats(1, 1, 1);
- this.position.copyFromFloats(0, 0, 0);
- this.rotation.copyFromFloats(0, 0, 0);
- //only if quaternion is already set
- if (this.rotationQuaternion) {
- this.rotationQuaternion = BABYLON.Quaternion.Identity();
- }
- this._worldMatrix = BABYLON.Matrix.Identity();
- };
- // Cache
- Mesh.prototype._resetPointsArrayCache = function () {
- this._positions = null;
- };
- Mesh.prototype._generatePointsArray = function () {
- if (this._positions)
- return true;
- this._positions = [];
- var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- if (!data) {
- return false;
- }
- for (var index = 0; index < data.length; index += 3) {
- this._positions.push(BABYLON.Vector3.FromArray(data, index));
- }
- return true;
- };
- /**
- * Returns a new `Mesh` object generated from the current mesh properties.
- * This method must not get confused with createInstance().
- * The parameter `name` is a string, the name given to the new mesh.
- * The optional parameter `newParent` can be any `Node` object (default `null`).
- * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
- * 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.
- */
- Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
- if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
- return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
- };
- /**
- * Disposes the mesh.
- * This also frees the memory allocated under the hood to all the buffers used by WebGL.
- */
- Mesh.prototype.dispose = function (doNotRecurse) {
- if (this._geometry) {
- this._geometry.releaseForMesh(this, true);
- }
- // Instances
- if (this._worldMatricesInstancesBuffer) {
- this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
- this._worldMatricesInstancesBuffer = null;
- }
- while (this.instances.length) {
- this.instances[0].dispose();
- }
- _super.prototype.dispose.call(this, doNotRecurse);
- };
- /**
- * Modifies the mesh geometry according to a displacement map.
- * 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.
- * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
- * This method returns nothing.
- * The parameter `url` is a string, the URL from the image file is to be downloaded.
- * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
- * 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.
- */
- Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
- var _this = this;
- var scene = this.getScene();
- var onload = function (img) {
- // Getting height map data
- var canvas = document.createElement("canvas");
- var context = canvas.getContext("2d");
- var heightMapWidth = img.width;
- var heightMapHeight = img.height;
- canvas.width = heightMapWidth;
- canvas.height = heightMapHeight;
- context.drawImage(img, 0, 0);
- // Create VertexData from map data
- //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
- var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
- _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
- //execute success callback, if set
- if (onSuccess) {
- onSuccess(_this);
- }
- };
- BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
- };
- /**
- * Modifies the mesh geometry according to a displacementMap buffer.
- * 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.
- * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
- * This method returns nothing.
- * 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.
- * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
- * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
- */
- Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
- if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
- || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
- || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
- BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
- return;
- }
- var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
- var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
- var position = BABYLON.Vector3.Zero();
- var normal = BABYLON.Vector3.Zero();
- var uv = BABYLON.Vector2.Zero();
- for (var index = 0; index < positions.length; index += 3) {
- BABYLON.Vector3.FromArrayToRef(positions, index, position);
- BABYLON.Vector3.FromArrayToRef(normals, index, normal);
- BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
- // Compute height
- var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
- var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
- var pos = (u + v * heightMapWidth) * 4;
- var r = buffer[pos] / 255.0;
- var g = buffer[pos + 1] / 255.0;
- var b = buffer[pos + 2] / 255.0;
- var gradient = r * 0.3 + g * 0.59 + b * 0.11;
- normal.normalize();
- normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
- position = position.add(normal);
- position.toArray(positions, index);
- }
- BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
- this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
- this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
- };
- /**
- * Modify the mesh to get a flat shading rendering.
- * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
- * This method returns nothing.
- * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
- */
- Mesh.prototype.convertToFlatShadedMesh = function () {
- /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
- /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
- var kinds = this.getVerticesDataKinds();
- var vbs = [];
- var data = [];
- var newdata = [];
- var updatableNormals = false;
- var kindIndex;
- var kind;
- for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
- kind = kinds[kindIndex];
- var vertexBuffer = this.getVertexBuffer(kind);
- if (kind === BABYLON.VertexBuffer.NormalKind) {
- updatableNormals = vertexBuffer.isUpdatable();
- kinds.splice(kindIndex, 1);
- kindIndex--;
- continue;
- }
- vbs[kind] = vertexBuffer;
- data[kind] = vbs[kind].getData();
- newdata[kind] = [];
- }
- // Save previous submeshes
- var previousSubmeshes = this.subMeshes.slice(0);
- var indices = this.getIndices();
- var totalIndices = this.getTotalIndices();
- // Generating unique vertices per face
- var index;
- for (index = 0; index < totalIndices; index++) {
- var vertexIndex = indices[index];
- for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
- kind = kinds[kindIndex];
- var stride = vbs[kind].getStrideSize();
- for (var offset = 0; offset < stride; offset++) {
- newdata[kind].push(data[kind][vertexIndex * stride + offset]);
- }
- }
- }
- // Updating faces & normal
- var normals = [];
- var positions = newdata[BABYLON.VertexBuffer.PositionKind];
- for (index = 0; index < totalIndices; index += 3) {
- indices[index] = index;
- indices[index + 1] = index + 1;
- indices[index + 2] = index + 2;
- var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
- var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
- var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
- var p1p2 = p1.subtract(p2);
- var p3p2 = p3.subtract(p2);
- var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
- // Store same normals for every vertex
- for (var localIndex = 0; localIndex < 3; localIndex++) {
- normals.push(normal.x);
- normals.push(normal.y);
- normals.push(normal.z);
- }
- }
- this.setIndices(indices);
- this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
- // Updating vertex buffers
- for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
- kind = kinds[kindIndex];
- this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
- }
- // Updating submeshes
- this.releaseSubMeshes();
- for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
- var previousOne = previousSubmeshes[submeshIndex];
- var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
- }
- this.synchronizeInstances();
- };
- /**
- * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
- * In other words, more vertices, no more indices and a single bigger VBO.
- * This method returns nothing.
- * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
- *
- */
- Mesh.prototype.convertToUnIndexedMesh = function () {
- /// <summary>Remove indices by unfolding faces into buffers</summary>
- /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
- var kinds = this.getVerticesDataKinds();
- var vbs = [];
- var data = [];
- var newdata = [];
- var updatableNormals = false;
- var kindIndex;
- var kind;
- for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
- kind = kinds[kindIndex];
- var vertexBuffer = this.getVertexBuffer(kind);
- vbs[kind] = vertexBuffer;
- data[kind] = vbs[kind].getData();
- newdata[kind] = [];
- }
- // Save previous submeshes
- var previousSubmeshes = this.subMeshes.slice(0);
- var indices = this.getIndices();
- var totalIndices = this.getTotalIndices();
- // Generating unique vertices per face
- var index;
- for (index = 0; index < totalIndices; index++) {
- var vertexIndex = indices[index];
- for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
- kind = kinds[kindIndex];
- var stride = vbs[kind].getStrideSize();
- for (var offset = 0; offset < stride; offset++) {
- newdata[kind].push(data[kind][vertexIndex * stride + offset]);
- }
- }
- }
- // Updating indices
- for (index = 0; index < totalIndices; index += 3) {
- indices[index] = index;
- indices[index + 1] = index + 1;
- indices[index + 2] = index + 2;
- }
- this.setIndices(indices);
- // Updating vertex buffers
- for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
- kind = kinds[kindIndex];
- this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
- }
- // Updating submeshes
- this.releaseSubMeshes();
- for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
- var previousOne = previousSubmeshes[submeshIndex];
- var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
- }
- this._unIndexed = true;
- this.synchronizeInstances();
- };
- /**
- * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
- * This method returns nothing.
- * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
- */
- Mesh.prototype.flipFaces = function (flipNormals) {
- if (flipNormals === void 0) { flipNormals = false; }
- var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
- var i;
- if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
- for (i = 0; i < vertex_data.normals.length; i++) {
- vertex_data.normals[i] *= -1;
- }
- }
- var temp;
- for (i = 0; i < vertex_data.indices.length; i += 3) {
- // reassign indices
- temp = vertex_data.indices[i + 1];
- vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
- vertex_data.indices[i + 2] = temp;
- }
- vertex_data.applyToMesh(this);
- };
- // Instances
- /**
- * Creates a new `InstancedMesh` object from the mesh model.
- * An instance shares the same properties and the same material than its model.
- * Only these properties of each instance can then be set individually :
- * - position
- * - rotation
- * - rotationQuaternion
- * - setPivotMatrix
- * - scaling
- * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
- * Warning : this method is not supported for `Line` mesh and `LineSystem`
- */
- Mesh.prototype.createInstance = function (name) {
- return new BABYLON.InstancedMesh(name, this);
- };
- /**
- * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
- * After this call, all the mesh instances have the same submeshes than the current mesh.
- * This method returns nothing.
- */
- Mesh.prototype.synchronizeInstances = function () {
- for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
- var instance = this.instances[instanceIndex];
- instance._syncSubMeshes();
- }
- };
- /**
- * Simplify the mesh according to the given array of settings.
- * Function will return immediately and will simplify async. It returns nothing.
- * @param settings a collection of simplification settings.
- * @param parallelProcessing should all levels calculate parallel or one after the other.
- * @param type the type of simplification to run.
- * @param successCallback optional success callback to be called after the simplification finished processing all settings.
- */
- Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
- if (parallelProcessing === void 0) { parallelProcessing = true; }
- if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
- this.getScene().simplificationQueue.addTask({
- settings: settings,
- parallelProcessing: parallelProcessing,
- mesh: this,
- simplificationType: simplificationType,
- successCallback: successCallback
- });
- };
- /**
- * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
- * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
- * This should be used together with the simplification to avoid disappearing triangles.
- * @param successCallback an optional success callback to be called after the optimization finished.
- */
- Mesh.prototype.optimizeIndices = function (successCallback) {
- var _this = this;
- var indices = this.getIndices();
- var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- var vectorPositions = [];
- for (var pos = 0; pos < positions.length; pos = pos + 3) {
- vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
- }
- var dupes = [];
- BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
- var realPos = vectorPositions.length - 1 - iteration;
- var testedPosition = vectorPositions[realPos];
- for (var j = 0; j < realPos; ++j) {
- var againstPosition = vectorPositions[j];
- if (testedPosition.equals(againstPosition)) {
- dupes[realPos] = j;
- break;
- }
- }
- }, function () {
- for (var i = 0; i < indices.length; ++i) {
- indices[i] = dupes[indices[i]] || indices[i];
- }
- //indices are now reordered
- var originalSubMeshes = _this.subMeshes.slice(0);
- _this.setIndices(indices);
- _this.subMeshes = originalSubMeshes;
- if (successCallback) {
- successCallback(_this);
- }
- });
- };
- // Statics
- /**
- * Returns a new `Mesh` object what is a deep copy of the passed mesh.
- * The parameter `parsedMesh` is the mesh to be copied.
- * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
- */
- Mesh.Parse = function (parsedMesh, scene, rootUrl) {
- var mesh = new Mesh(parsedMesh.name, scene);
- mesh.id = parsedMesh.id;
- BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
- mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
- if (parsedMesh.rotationQuaternion) {
- mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
- }
- else if (parsedMesh.rotation) {
- mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
- }
- mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
- if (parsedMesh.localMatrix) {
- mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
- }
- else if (parsedMesh.pivotMatrix) {
- mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
- }
- mesh.setEnabled(parsedMesh.isEnabled);
- mesh.isVisible = parsedMesh.isVisible;
- mesh.infiniteDistance = parsedMesh.infiniteDistance;
- mesh.showBoundingBox = parsedMesh.showBoundingBox;
- mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
- if (parsedMesh.applyFog !== undefined) {
- mesh.applyFog = parsedMesh.applyFog;
- }
- if (parsedMesh.pickable !== undefined) {
- mesh.isPickable = parsedMesh.pickable;
- }
- if (parsedMesh.alphaIndex !== undefined) {
- mesh.alphaIndex = parsedMesh.alphaIndex;
- }
- mesh.receiveShadows = parsedMesh.receiveShadows;
- mesh.billboardMode = parsedMesh.billboardMode;
- if (parsedMesh.visibility !== undefined) {
- mesh.visibility = parsedMesh.visibility;
- }
- mesh.checkCollisions = parsedMesh.checkCollisions;
- mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
- // freezeWorldMatrix
- if (parsedMesh.freezeWorldMatrix) {
- mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
- }
- // Parent
- if (parsedMesh.parentId) {
- mesh._waitingParentId = parsedMesh.parentId;
- }
- // Actions
- if (parsedMesh.actions !== undefined) {
- mesh._waitingActions = parsedMesh.actions;
- }
- // Geometry
- mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
- if (parsedMesh.delayLoadingFile) {
- mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
- mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
- mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
- if (parsedMesh._binaryInfo) {
- mesh._binaryInfo = parsedMesh._binaryInfo;
- }
- mesh._delayInfo = [];
- if (parsedMesh.hasUVs) {
- mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
- }
- if (parsedMesh.hasUVs2) {
- mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
- }
- if (parsedMesh.hasUVs3) {
- mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
- }
- if (parsedMesh.hasUVs4) {
- mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
- }
- if (parsedMesh.hasUVs5) {
- mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
- }
- if (parsedMesh.hasUVs6) {
- mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
- }
- if (parsedMesh.hasColors) {
- mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
- }
- if (parsedMesh.hasMatricesIndices) {
- mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
- }
- if (parsedMesh.hasMatricesWeights) {
- mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
- }
- mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
- if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
- mesh._checkDelayState();
- }
- }
- else {
- BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
- }
- // Material
- if (parsedMesh.materialId) {
- mesh.setMaterialByID(parsedMesh.materialId);
- }
- else {
- mesh.material = null;
- }
- // Skeleton
- if (parsedMesh.skeletonId > -1) {
- mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
- if (parsedMesh.numBoneInfluencers) {
- mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
- }
- }
- // Animations
- if (parsedMesh.animations) {
- for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
- var parsedAnimation = parsedMesh.animations[animationIndex];
- mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
- }
- BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
- }
- if (parsedMesh.autoAnimate) {
- scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
- }
- // Layer Mask
- if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
- mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
- }
- else {
- mesh.layerMask = 0x0FFFFFFF;
- }
- //(Deprecated) physics
- if (parsedMesh.physicsImpostor) {
- mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
- mass: parsedMesh.physicsMass,
- friction: parsedMesh.physicsFriction,
- restitution: parsedMesh.physicsRestitution
- }, scene);
- }
- // Instances
- if (parsedMesh.instances) {
- for (var index = 0; index < parsedMesh.instances.length; index++) {
- var parsedInstance = parsedMesh.instances[index];
- var instance = mesh.createInstance(parsedInstance.name);
- BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
- instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
- if (parsedInstance.rotationQuaternion) {
- instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
- }
- else if (parsedInstance.rotation) {
- instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
- }
- instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
- instance.checkCollisions = mesh.checkCollisions;
- if (parsedMesh.animations) {
- for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
- parsedAnimation = parsedMesh.animations[animationIndex];
- instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
- }
- BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
- }
- }
- }
- return mesh;
- };
- /**
- * Creates a ribbon mesh.
- * Please consider using the same method from the `MeshBuilder` class instead.
- * 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.
- *
- * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
- * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
- * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
- * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
- * 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.
- * 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.
- * 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
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
- return BABYLON.MeshBuilder.CreateRibbon(name, {
- pathArray: pathArray,
- closeArray: closeArray,
- closePath: closePath,
- offset: offset,
- updatable: updatable,
- sideOrientation: sideOrientation,
- instance: instance
- }, scene);
- };
- /**
- * Creates a plane polygonal mesh. By default, this is a disc.
- * Please consider using the same method from the `MeshBuilder` class instead.
- * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
- * 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.
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
- var options = {
- radius: radius,
- tessellation: tessellation,
- sideOrientation: sideOrientation,
- updatable: updatable
- };
- return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
- };
- /**
- * Creates a box mesh.
- * Please consider using the same method from the `MeshBuilder` class instead.
- * The parameter `size` sets the size (float) of each box side (default 1).
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
- var options = {
- size: size,
- sideOrientation: sideOrientation,
- updatable: updatable
- };
- return BABYLON.MeshBuilder.CreateBox(name, options, scene);
- };
- /**
- * Creates a sphere mesh.
- * Please consider using the same method from the `MeshBuilder` class instead.
- * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
- * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
- var options = {
- segments: segments,
- diameterX: diameter,
- diameterY: diameter,
- diameterZ: diameter,
- sideOrientation: sideOrientation,
- updatable: updatable
- };
- return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
- };
- /**
- * Creates a cylinder or a cone mesh.
- * Please consider using the same method from the `MeshBuilder` class instead.
- * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
- * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
- * 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.
- * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
- * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
- if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
- if (scene !== undefined) {
- sideOrientation = updatable || Mesh.DEFAULTSIDE;
- updatable = scene;
- }
- scene = subdivisions;
- subdivisions = 1;
- }
- var options = {
- height: height,
- diameterTop: diameterTop,
- diameterBottom: diameterBottom,
- tessellation: tessellation,
- subdivisions: subdivisions,
- sideOrientation: sideOrientation,
- updatable: updatable
- };
- return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
- };
- // Torus (Code from SharpDX.org)
- /**
- * Creates a torus mesh.
- * Please consider using the same method from the `MeshBuilder` class instead.
- * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
- * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
- * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
- var options = {
- diameter: diameter,
- thickness: thickness,
- tessellation: tessellation,
- sideOrientation: sideOrientation,
- updatable: updatable
- };
- return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
- };
- /**
- * Creates a torus knot mesh.
- * Please consider using the same method from the `MeshBuilder` class instead.
- * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
- * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
- * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
- * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
- var options = {
- radius: radius,
- tube: tube,
- radialSegments: radialSegments,
- tubularSegments: tubularSegments,
- p: p,
- q: q,
- sideOrientation: sideOrientation,
- updatable: updatable
- };
- return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
- };
- /**
- * Creates a line mesh.
- * Please consider using the same method from the `MeshBuilder` class instead.
- * 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.
- * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
- * The parameter `points` is an array successive Vector3.
- * 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
- * When updating an instance, remember that only point positions can change, not the number of points.
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- Mesh.CreateLines = function (name, points, scene, updatable, instance) {
- var options = {
- points: points,
- updatable: updatable,
- instance: instance
- };
- return BABYLON.MeshBuilder.CreateLines(name, options, scene);
- };
- /**
- * Creates a dashed line mesh.
- * Please consider using the same method from the `MeshBuilder` class instead.
- * 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.
- * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
- * The parameter `points` is an array successive Vector3.
- * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
- * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
- * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
- * 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
- * When updating an instance, remember that only point positions can change, not the number of points.
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
- var options = {
- points: points,
- dashSize: dashSize,
- gapSize: gapSize,
- dashNb: dashNb,
- updatable: updatable
- };
- return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
- };
- /**
- * Creates an extruded shape mesh.
- * 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.
- * Please consider using the same method from the `MeshBuilder` class instead.
- *
- * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
- * 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
- * extruded along the Z axis.
- * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
- * 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.
- * The parameter `scale` (float, default 1) is the value to scale the shape.
- * 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
- * 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
- * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
- var options = {
- shape: shape,
- path: path,
- scale: scale,
- rotation: rotation,
- cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
- sideOrientation: sideOrientation,
- instance: instance,
- updatable: updatable
- };
- return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
- };
- /**
- * Creates an custom extruded shape mesh.
- * 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.
- * Please consider using the same method from the `MeshBuilder` class instead.
- *
- * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
- * 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
- * extruded along the Z axis.
- * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
- * 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
- * and the distance of this point from the begining of the path :
- * ```rotationFunction = function(i, distance) {
- * // do things
- * return rotationValue; }```
- * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
- * 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
- * and the distance of this point from the begining of the path :
- * ````scaleFunction = function(i, distance) {
- * // do things
- * return scaleValue;}```
- * It must returns a float value that will be the scale value applied to the shape on each path point.
- * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
- * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
- * 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
- * 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
- * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
- var options = {
- shape: shape,
- path: path,
- scaleFunction: scaleFunction,
- rotationFunction: rotationFunction,
- ribbonCloseArray: ribbonCloseArray,
- ribbonClosePath: ribbonClosePath,
- cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
- sideOrientation: sideOrientation,
- instance: instance,
- updatable: updatable
- };
- return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
- };
- /**
- * Creates lathe mesh.
- * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
- * Please consider using the same method from the `MeshBuilder` class instead.
- *
- * 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
- * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
- * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
- * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
- var options = {
- shape: shape,
- radius: radius,
- tessellation: tessellation,
- sideOrientation: sideOrientation,
- updatable: updatable
- };
- return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
- };
- /**
- * Creates a plane mesh.
- * Please consider using the same method from the `MeshBuilder` class instead.
- * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
- var options = {
- size: size,
- width: size,
- height: size,
- sideOrientation: sideOrientation,
- updatable: updatable
- };
- return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
- };
- /**
- * Creates a ground mesh.
- * Please consider using the same method from the `MeshBuilder` class instead.
- * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
- * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
- var options = {
- width: width,
- height: height,
- subdivisions: subdivisions,
- updatable: updatable
- };
- return BABYLON.MeshBuilder.CreateGround(name, options, scene);
- };
- /**
- * Creates a tiled ground mesh.
- * Please consider using the same method from the `MeshBuilder` class instead.
- * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
- * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
- * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
- * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
- * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
- * numbers of subdivisions on the ground width and height of each tile.
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
- var options = {
- xmin: xmin,
- zmin: zmin,
- xmax: xmax,
- zmax: zmax,
- subdivisions: subdivisions,
- precision: precision,
- updatable: updatable
- };
- return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
- };
- /**
- * Creates a ground mesh from a height map.
- * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
- * Please consider using the same method from the `MeshBuilder` class instead.
- * The parameter `url` sets the URL of the height map image resource.
- * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
- * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
- * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
- * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
- * 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).
- * This function is passed the newly built mesh : ```function(mesh) { // do things
- * return; }```
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
- var options = {
- width: width,
- height: height,
- subdivisions: subdivisions,
- minHeight: minHeight,
- maxHeight: maxHeight,
- updatable: updatable,
- onReady: onReady
- };
- return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
- };
- /**
- * Creates a tube mesh.
- * 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.
- *
- * Please consider using the same method from the `MeshBuilder` class instead.
- * The parameter `path` is a required array of successive `Vector3`. It is the curve used as the axis of the tube.
- * The parameter `radius` (positive float, default 1) sets the tube radius size.
- * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
- * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
- * 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.
- * It must return a radius value (positive float) :
- * ```var radiusFunction = function(i, distance) {
- * // do things
- * return radius; }```
- * 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
- * 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
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
- var options = {
- path: path,
- radius: radius,
- tessellation: tessellation,
- radiusFunction: radiusFunction,
- arc: 1,
- cap: cap,
- updatable: updatable,
- sideOrientation: sideOrientation,
- instance: instance
- };
- return BABYLON.MeshBuilder.CreateTube(name, options, scene);
- };
- /**
- * Creates a polyhedron mesh.
- *
- * Please consider using the same method from the `MeshBuilder` class instead.
- * 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
- * to choose the wanted type.
- * The parameter `size` (positive float, default 1) sets the polygon size.
- * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
- * 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`.
- * 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
- * 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)`).
- * 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
- * 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.
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- Mesh.CreatePolyhedron = function (name, options, scene) {
- return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
- };
- /**
- * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
- * Please consider using the same method from the `MeshBuilder` class instead.
- * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
- * 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`).
- * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
- * 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.
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- Mesh.CreateIcoSphere = function (name, options, scene) {
- return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
- };
- /**
- * Creates a decal mesh.
- * Please consider using the same method from the `MeshBuilder` class instead.
- * 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.
- * The parameter `position` (`Vector3`, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
- * The parameter `normal` (`Vector3`, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
- * The parameter `size` (`Vector3`, default `(1, 1, 1)`) sets the decal scaling.
- * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
- */
- Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
- var options = {
- position: position,
- normal: normal,
- size: size,
- angle: angle
- };
- return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
- };
- // Skeletons
- /**
- * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
- */
- Mesh.prototype.setPositionsForCPUSkinning = function () {
- var source;
- if (!this._sourcePositions) {
- source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- this._sourcePositions = new Float32Array(source);
- if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
- this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
- }
- }
- return this._sourcePositions;
- };
- /**
- * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
- */
- Mesh.prototype.setNormalsForCPUSkinning = function () {
- var source;
- if (!this._sourceNormals) {
- source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
- this._sourceNormals = new Float32Array(source);
- if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
- this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
- }
- }
- return this._sourceNormals;
- };
- /**
- * Update the vertex buffers by applying transformation from the bones
- * @param {skeleton} skeleton to apply
- */
- Mesh.prototype.applySkeleton = function (skeleton) {
- if (!this.geometry) {
- return;
- }
- if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
- return;
- }
- this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
- if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
- return this;
- }
- if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
- return this;
- }
- if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
- return this;
- }
- if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
- return this;
- }
- if (!this._sourcePositions) {
- this.setPositionsForCPUSkinning();
- }
- if (!this._sourceNormals) {
- this.setNormalsForCPUSkinning();
- }
- // positionsData checks for not being Float32Array will only pass at most once
- var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- if (!(positionsData instanceof Float32Array)) {
- positionsData = new Float32Array(positionsData);
- }
- // normalsData checks for not being Float32Array will only pass at most once
- var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
- if (!(normalsData instanceof Float32Array)) {
- normalsData = new Float32Array(normalsData);
- }
- var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
- var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
- var needExtras = this.numBoneInfluencers > 4;
- var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
- var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
- var skeletonMatrices = skeleton.getTransformMatrices(this);
- var tempVector3 = BABYLON.Vector3.Zero();
- var finalMatrix = new BABYLON.Matrix();
- var tempMatrix = new BABYLON.Matrix();
- var matWeightIdx = 0;
- var inf;
- for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
- var weight;
- for (inf = 0; inf < 4; inf++) {
- weight = matricesWeightsData[matWeightIdx + inf];
- if (weight > 0) {
- BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
- finalMatrix.addToSelf(tempMatrix);
- }
- else
- break;
- }
- if (needExtras) {
- for (inf = 0; inf < 4; inf++) {
- weight = matricesWeightsExtraData[matWeightIdx + inf];
- if (weight > 0) {
- BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
- finalMatrix.addToSelf(tempMatrix);
- }
- else
- break;
- }
- }
- BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
- tempVector3.toArray(positionsData, index);
- BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
- tempVector3.toArray(normalsData, index);
- finalMatrix.reset();
- }
- this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
- this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
- return this;
- };
- // Tools
- /**
- * Returns an object `{min: Vector3, max: Vector3}`
- * This min and max `Vector3` are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
- */
- Mesh.MinMax = function (meshes) {
- var minVector = null;
- var maxVector = null;
- for (var i in meshes) {
- var mesh = meshes[i];
- var boundingBox = mesh.getBoundingInfo().boundingBox;
- if (!minVector) {
- minVector = boundingBox.minimumWorld;
- maxVector = boundingBox.maximumWorld;
- continue;
- }
- minVector.MinimizeInPlace(boundingBox.minimumWorld);
- maxVector.MaximizeInPlace(boundingBox.maximumWorld);
- }
- return {
- min: minVector,
- max: maxVector
- };
- };
- /**
- * Returns a `Vector3`, the center of the `{min: Vector3, max: Vector3}` or the center of MinMax vector3 computed from a mesh array.
- */
- Mesh.Center = function (meshesOrMinMaxVector) {
- var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
- return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
- };
- /**
- * Merge the array of meshes into a single mesh for performance reasons.
- * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
- * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
- * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
- * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
- */
- Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
- if (disposeSource === void 0) { disposeSource = true; }
- var index;
- if (!allow32BitsIndices) {
- var totalVertices = 0;
- // Counting vertices
- for (index = 0; index < meshes.length; index++) {
- if (meshes[index]) {
- totalVertices += meshes[index].getTotalVertices();
- if (totalVertices > 65536) {
- BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
- return null;
- }
- }
- }
- }
- // Merge
- var vertexData;
- var otherVertexData;
- var source;
- for (index = 0; index < meshes.length; index++) {
- if (meshes[index]) {
- meshes[index].computeWorldMatrix(true);
- otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
- otherVertexData.transform(meshes[index].getWorldMatrix());
- if (vertexData) {
- vertexData.merge(otherVertexData);
- }
- else {
- vertexData = otherVertexData;
- source = meshes[index];
- }
- }
- }
- if (!meshSubclass) {
- meshSubclass = new Mesh(source.name + "_merged", source.getScene());
- }
- vertexData.applyToMesh(meshSubclass);
- // Setting properties
- meshSubclass.material = source.material;
- meshSubclass.checkCollisions = source.checkCollisions;
- // Cleaning
- if (disposeSource) {
- for (index = 0; index < meshes.length; index++) {
- if (meshes[index]) {
- meshes[index].dispose();
- }
- }
- }
- return meshSubclass;
- };
- // Consts
- Mesh._FRONTSIDE = 0;
- Mesh._BACKSIDE = 1;
- Mesh._DOUBLESIDE = 2;
- Mesh._DEFAULTSIDE = 0;
- Mesh._NO_CAP = 0;
- Mesh._CAP_START = 1;
- Mesh._CAP_END = 2;
- Mesh._CAP_ALL = 3;
- return Mesh;
- })(BABYLON.AbstractMesh);
- BABYLON.Mesh = Mesh;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var SubMesh = (function () {
- function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
- if (createBoundingBox === void 0) { createBoundingBox = true; }
- this.materialIndex = materialIndex;
- this.verticesStart = verticesStart;
- this.verticesCount = verticesCount;
- this.indexStart = indexStart;
- this.indexCount = indexCount;
- this._renderId = 0;
- this._mesh = mesh;
- this._renderingMesh = renderingMesh || mesh;
- mesh.subMeshes.push(this);
- this._trianglePlanes = [];
- this._id = mesh.subMeshes.length - 1;
- if (createBoundingBox) {
- this.refreshBoundingInfo();
- mesh.computeWorldMatrix(true);
- }
- }
- Object.defineProperty(SubMesh.prototype, "IsGlobal", {
- get: function () {
- return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
- },
- enumerable: true,
- configurable: true
- });
- SubMesh.prototype.getBoundingInfo = function () {
- if (this.IsGlobal) {
- return this._mesh.getBoundingInfo();
- }
- return this._boundingInfo;
- };
- SubMesh.prototype.getMesh = function () {
- return this._mesh;
- };
- SubMesh.prototype.getRenderingMesh = function () {
- return this._renderingMesh;
- };
- SubMesh.prototype.getMaterial = function () {
- var rootMaterial = this._renderingMesh.material;
- if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
- var multiMaterial = rootMaterial;
- return multiMaterial.getSubMaterial(this.materialIndex);
- }
- if (!rootMaterial) {
- return this._mesh.getScene().defaultMaterial;
- }
- return rootMaterial;
- };
- // Methods
- SubMesh.prototype.refreshBoundingInfo = function () {
- this._lastColliderWorldVertices = null;
- if (this.IsGlobal) {
- return;
- }
- var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- if (!data) {
- this._boundingInfo = this._mesh._boundingInfo;
- return;
- }
- var indices = this._renderingMesh.getIndices();
- var extend;
- //is this the only submesh?
- if (this.indexStart === 0 && this.indexCount === indices.length) {
- //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
- extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
- }
- else {
- extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
- }
- this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
- };
- SubMesh.prototype._checkCollision = function (collider) {
- return this.getBoundingInfo()._checkCollision(collider);
- };
- SubMesh.prototype.updateBoundingInfo = function (world) {
- if (!this.getBoundingInfo()) {
- this.refreshBoundingInfo();
- }
- this.getBoundingInfo().update(world);
- };
- SubMesh.prototype.isInFrustum = function (frustumPlanes) {
- return this.getBoundingInfo().isInFrustum(frustumPlanes);
- };
- SubMesh.prototype.render = function (enableAlphaMode) {
- this._renderingMesh.render(this, enableAlphaMode);
- };
- SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
- if (!this._linesIndexBuffer) {
- var linesIndices = [];
- for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
- linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
- }
- this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
- this.linesIndexCount = linesIndices.length;
- }
- return this._linesIndexBuffer;
- };
- SubMesh.prototype.canIntersects = function (ray) {
- return ray.intersectsBox(this.getBoundingInfo().boundingBox);
- };
- SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
- var intersectInfo = null;
- // LineMesh first as it's also a Mesh...
- if (this._mesh instanceof BABYLON.LinesMesh) {
- var lineMesh = this._mesh;
- // Line test
- for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
- var p0 = positions[indices[index]];
- var p1 = positions[indices[index + 1]];
- var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
- if (length < 0) {
- continue;
- }
- if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
- intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
- if (fastCheck) {
- break;
- }
- }
- }
- }
- else {
- // Triangles test
- for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
- var p0 = positions[indices[index]];
- var p1 = positions[indices[index + 1]];
- var p2 = positions[indices[index + 2]];
- var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
- if (currentIntersectInfo) {
- if (currentIntersectInfo.distance < 0) {
- continue;
- }
- if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
- intersectInfo = currentIntersectInfo;
- intersectInfo.faceId = index / 3;
- if (fastCheck) {
- break;
- }
- }
- }
- }
- }
- return intersectInfo;
- };
- // Clone
- SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
- var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
- if (!this.IsGlobal) {
- result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
- }
- return result;
- };
- // Dispose
- SubMesh.prototype.dispose = function () {
- if (this._linesIndexBuffer) {
- this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
- this._linesIndexBuffer = null;
- }
- // Remove from mesh
- var index = this._mesh.subMeshes.indexOf(this);
- this._mesh.subMeshes.splice(index, 1);
- };
- // Statics
- SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
- var minVertexIndex = Number.MAX_VALUE;
- var maxVertexIndex = -Number.MAX_VALUE;
- renderingMesh = renderingMesh || mesh;
- var indices = renderingMesh.getIndices();
- for (var index = startIndex; index < startIndex + indexCount; index++) {
- var vertexIndex = indices[index];
- if (vertexIndex < minVertexIndex)
- minVertexIndex = vertexIndex;
- if (vertexIndex > maxVertexIndex)
- maxVertexIndex = vertexIndex;
- }
- return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
- };
- return SubMesh;
- })();
- BABYLON.SubMesh = SubMesh;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var MeshBuilder = (function () {
- function MeshBuilder() {
- }
- /**
- * Creates a box mesh.
- * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
- * The parameter `size` sets the size (float) of each box side (default 1).
- * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
- * 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).
- * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- MeshBuilder.CreateBox = function (name, options, scene) {
- var box = new BABYLON.Mesh(name, scene);
- var vertexData = BABYLON.VertexData.CreateBox(options);
- vertexData.applyToMesh(box, options.updatable);
- return box;
- };
- /**
- * Creates a sphere mesh.
- * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
- * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
- * 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`).
- * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
- * 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
- * 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).
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- MeshBuilder.CreateSphere = function (name, options, scene) {
- var sphere = new BABYLON.Mesh(name, scene);
- var vertexData = BABYLON.VertexData.CreateSphere(options);
- vertexData.applyToMesh(sphere, options.updatable);
- return sphere;
- };
- /**
- * Creates a plane polygonal mesh. By default, this is a disc.
- * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
- * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
- * 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.
- * 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
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- MeshBuilder.CreateDisc = function (name, options, scene) {
- var disc = new BABYLON.Mesh(name, scene);
- var vertexData = BABYLON.VertexData.CreateDisc(options);
- vertexData.applyToMesh(disc, options.updatable);
- return disc;
- };
- /**
- * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
- * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
- * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
- * 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`).
- * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
- * 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.
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- MeshBuilder.CreateIcoSphere = function (name, options, scene) {
- var sphere = new BABYLON.Mesh(name, scene);
- var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
- vertexData.applyToMesh(sphere, options.updatable);
- return sphere;
- };
- ;
- /**
- * Creates a ribbon mesh.
- * 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.
- *
- * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
- * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
- * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
- * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
- * 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.
- * 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.
- * 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
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- MeshBuilder.CreateRibbon = function (name, options, scene) {
- var pathArray = options.pathArray;
- var closeArray = options.closeArray;
- var closePath = options.closePath;
- var offset = options.offset;
- var sideOrientation = options.sideOrientation;
- var instance = options.instance;
- var updatable = options.updatable;
- if (instance) {
- // positionFunction : ribbon case
- // only pathArray and sideOrientation parameters are taken into account for positions update
- var positionFunction = function (positions) {
- var minlg = pathArray[0].length;
- var i = 0;
- var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
- for (var si = 1; si <= ns; si++) {
- for (var p = 0; p < pathArray.length; p++) {
- var path = pathArray[p];
- var l = path.length;
- minlg = (minlg < l) ? minlg : l;
- var j = 0;
- while (j < minlg) {
- positions[i] = path[j].x;
- positions[i + 1] = path[j].y;
- positions[i + 2] = path[j].z;
- j++;
- i += 3;
- }
- if (instance._closePath) {
- positions[i] = path[0].x;
- positions[i + 1] = path[0].y;
- positions[i + 2] = path[0].z;
- i += 3;
- }
- }
- }
- };
- var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- positionFunction(positions);
- instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
- if (!(instance.areNormalsFrozen)) {
- var indices = instance.getIndices();
- var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
- BABYLON.VertexData.ComputeNormals(positions, indices, normals);
- if (instance._closePath) {
- var indexFirst = 0;
- var indexLast = 0;
- for (var p = 0; p < pathArray.length; p++) {
- indexFirst = instance._idx[p] * 3;
- if (p + 1 < pathArray.length) {
- indexLast = (instance._idx[p + 1] - 1) * 3;
- }
- else {
- indexLast = normals.length - 3;
- }
- normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
- normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
- normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
- normals[indexLast] = normals[indexFirst];
- normals[indexLast + 1] = normals[indexFirst + 1];
- normals[indexLast + 2] = normals[indexFirst + 2];
- }
- }
- instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
- }
- return instance;
- }
- else {
- var ribbon = new BABYLON.Mesh(name, scene);
- ribbon.sideOrientation = sideOrientation;
- var vertexData = BABYLON.VertexData.CreateRibbon(options);
- if (closePath) {
- ribbon._idx = vertexData._idx;
- }
- ribbon._closePath = closePath;
- ribbon._closeArray = closeArray;
- vertexData.applyToMesh(ribbon, updatable);
- return ribbon;
- }
- };
- /**
- * Creates a cylinder or a cone mesh.
- * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
- * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
- * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
- * 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.
- * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
- * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
- * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
- * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
- * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
- * 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).
- * 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
- * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
- * 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
- * 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.
- * If `enclose` is false, a ring surface is one element.
- * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
- * 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
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- MeshBuilder.CreateCylinder = function (name, options, scene) {
- var cylinder = new BABYLON.Mesh(name, scene);
- var vertexData = BABYLON.VertexData.CreateCylinder(options);
- vertexData.applyToMesh(cylinder, options.updatable);
- return cylinder;
- };
- /**
- * Creates a torus mesh.
- * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
- * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
- * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
- * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- MeshBuilder.CreateTorus = function (name, options, scene) {
- var torus = new BABYLON.Mesh(name, scene);
- var vertexData = BABYLON.VertexData.CreateTorus(options);
- vertexData.applyToMesh(torus, options.updatable);
- return torus;
- };
- /**
- * Creates a torus knot mesh.
- * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
- * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
- * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
- * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
- * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- MeshBuilder.CreateTorusKnot = function (name, options, scene) {
- var torusKnot = new BABYLON.Mesh(name, scene);
- var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
- vertexData.applyToMesh(torusKnot, options.updatable);
- return torusKnot;
- };
- /**
- * Creates a line system mesh.
- * A line system is a pool of many lines gathered in a single mesh.
- * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
- * 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.
- * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
- * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
- * 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
- * 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
- * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- MeshBuilder.CreateLineSystem = function (name, options, scene) {
- var instance = options.instance;
- var lines = options.lines;
- if (instance) {
- var positionFunction = function (positions) {
- var i = 0;
- for (var l = 0; l < lines.length; l++) {
- var points = lines[l];
- for (var p = 0; p < points.length; p++) {
- positions[i] = points[p].x;
- positions[i + 1] = points[p].y;
- positions[i + 2] = points[p].z;
- i += 3;
- }
- }
- };
- instance.updateMeshPositions(positionFunction, false);
- return instance;
- }
- // line system creation
- var lineSystem = new BABYLON.LinesMesh(name, scene);
- var vertexData = BABYLON.VertexData.CreateLineSystem(options);
- vertexData.applyToMesh(lineSystem, options.updatable);
- return lineSystem;
- };
- /**
- * Creates a line mesh.
- * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
- * 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.
- * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
- * The parameter `points` is an array successive Vector3.
- * 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
- * When updating an instance, remember that only point positions can change, not the number of points.
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- MeshBuilder.CreateLines = function (name, options, scene) {
- var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
- return lines;
- };
- /**
- * Creates a dashed line mesh.
- * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
- * 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.
- * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
- * The parameter `points` is an array successive Vector3.
- * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
- * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
- * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
- * 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
- * When updating an instance, remember that only point positions can change, not the number of points.
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- MeshBuilder.CreateDashedLines = function (name, options, scene) {
- var points = options.points;
- var instance = options.instance;
- var gapSize = options.gapSize;
- var dashNb = options.dashNb;
- var dashSize = options.dashSize;
- if (instance) {
- var positionFunction = function (positions) {
- var curvect = BABYLON.Vector3.Zero();
- var nbSeg = positions.length / 6;
- var lg = 0;
- var nb = 0;
- var shft = 0;
- var dashshft = 0;
- var curshft = 0;
- var p = 0;
- var i = 0;
- var j = 0;
- for (i = 0; i < points.length - 1; i++) {
- points[i + 1].subtractToRef(points[i], curvect);
- lg += curvect.length();
- }
- shft = lg / nbSeg;
- dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
- for (i = 0; i < points.length - 1; i++) {
- points[i + 1].subtractToRef(points[i], curvect);
- nb = Math.floor(curvect.length() / shft);
- curvect.normalize();
- j = 0;
- while (j < nb && p < positions.length) {
- curshft = shft * j;
- positions[p] = points[i].x + curshft * curvect.x;
- positions[p + 1] = points[i].y + curshft * curvect.y;
- positions[p + 2] = points[i].z + curshft * curvect.z;
- positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
- positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
- positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
- p += 6;
- j++;
- }
- }
- while (p < positions.length) {
- positions[p] = points[i].x;
- positions[p + 1] = points[i].y;
- positions[p + 2] = points[i].z;
- p += 3;
- }
- };
- instance.updateMeshPositions(positionFunction, false);
- return instance;
- }
- // dashed lines creation
- var dashedLines = new BABYLON.LinesMesh(name, scene);
- var vertexData = BABYLON.VertexData.CreateDashedLines(options);
- vertexData.applyToMesh(dashedLines, options.updatable);
- dashedLines.dashSize = dashSize;
- dashedLines.gapSize = gapSize;
- return dashedLines;
- };
- /**
- * Creates an extruded shape mesh.
- * 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.
- * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
- *
- * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
- * 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
- * extruded along the Z axis.
- * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
- * 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.
- * The parameter `scale` (float, default 1) is the value to scale the shape.
- * 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
- * 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
- * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- MeshBuilder.ExtrudeShape = function (name, options, scene) {
- var path = options.path;
- var shape = options.shape;
- var scale = options.scale || 1;
- var rotation = options.rotation || 0;
- var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
- var updatable = options.updatable;
- var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
- var instance = options.instance;
- return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
- };
- /**
- * Creates an custom extruded shape mesh.
- * 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.
- * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
- *
- * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
- * 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
- * extruded along the Z axis.
- * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
- * 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
- * and the distance of this point from the begining of the path :
- * ```rotationFunction = function(i, distance) {
- * // do things
- * return rotationValue; }```
- * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
- * 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
- * and the distance of this point from the begining of the path :
- * ````scaleFunction = function(i, distance) {
- * // do things
- * return scaleValue;}```
- * It must returns a float value that will be the scale value applied to the shape on each path point.
- * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
- * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
- * 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
- * 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
- * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
- var path = options.path;
- var shape = options.shape;
- var scaleFunction = options.scaleFunction || (function () { return 1; });
- var rotationFunction = options.rotationFunction || (function () { return 0; });
- var ribbonCloseArray = options.ribbonCloseArray || false;
- var ribbonClosePath = options.ribbonClosePath || false;
- var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
- var updatable = options.updatable;
- var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
- var instance = options.instance;
- return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
- };
- /**
- * Creates lathe mesh.
- * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
- * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
- *
- * 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
- * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
- * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
- * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
- * 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.
- * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
- * 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
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- MeshBuilder.CreateLathe = function (name, options, scene) {
- var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
- var closed = (options.closed === undefined) ? true : options.closed;
- var shape = options.shape;
- var radius = options.radius || 1;
- var tessellation = options.tessellation || 64;
- var updatable = options.updatable;
- var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
- var cap = options.cap || BABYLON.Mesh.NO_CAP;
- var pi2 = Math.PI * 2;
- var paths = new Array();
- var i = 0;
- var p = 0;
- var step = pi2 / tessellation * arc;
- var rotated;
- var path = new Array();
- ;
- for (i = 0; i <= tessellation; i++) {
- var path = [];
- if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
- path.push(new BABYLON.Vector3(0, shape[0].y, 0));
- path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
- }
- for (p = 0; p < shape.length; p++) {
- rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
- path.push(rotated);
- }
- if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
- 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));
- path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
- }
- paths.push(path);
- }
- // lathe ribbon
- var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
- return lathe;
- };
- /**
- * Creates a plane mesh.
- * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
- * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
- * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
- * The parameter `sourcePlane` is a `Plane` instance. It builds a mesh plane from a Math plane.
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- MeshBuilder.CreatePlane = function (name, options, scene) {
- var plane = new BABYLON.Mesh(name, scene);
- var vertexData = BABYLON.VertexData.CreatePlane(options);
- vertexData.applyToMesh(plane, options.updatable);
- if (options.sourcePlane) {
- plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
- var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
- var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
- plane.rotate(vectorProduct, product);
- }
- return plane;
- };
- /**
- * Creates a ground mesh.
- * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
- * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
- * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- MeshBuilder.CreateGround = function (name, options, scene) {
- var ground = new BABYLON.GroundMesh(name, scene);
- ground._setReady(false);
- ground._subdivisions = options.subdivisions || 1;
- ground._width = options.width || 1;
- ground._height = options.height || 1;
- ground._maxX = ground._width / 2;
- ground._maxZ = ground._height / 2;
- ground._minX = -ground._maxX;
- ground._minZ = -ground._maxZ;
- var vertexData = BABYLON.VertexData.CreateGround(options);
- vertexData.applyToMesh(ground, options.updatable);
- ground._setReady(true);
- return ground;
- };
- /**
- * Creates a tiled ground mesh.
- * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
- * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
- * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
- * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
- * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
- * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
- * numbers of subdivisions on the ground width and height of each tile.
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- MeshBuilder.CreateTiledGround = function (name, options, scene) {
- var tiledGround = new BABYLON.Mesh(name, scene);
- var vertexData = BABYLON.VertexData.CreateTiledGround(options);
- vertexData.applyToMesh(tiledGround, options.updatable);
- return tiledGround;
- };
- /**
- * Creates a ground mesh from a height map.
- * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
- * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
- * The parameter `url` sets the URL of the height map image resource.
- * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
- * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
- * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
- * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
- * 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).
- * This function is passed the newly built mesh : ```function(mesh) { // do things
- * return; }```
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
- var width = options.width || 10;
- var height = options.height || 10;
- var subdivisions = options.subdivisions || 1;
- var minHeight = options.minHeight;
- var maxHeight = options.maxHeight || 10;
- var updatable = options.updatable;
- var onReady = options.onReady;
- var ground = new BABYLON.GroundMesh(name, scene);
- ground._subdivisions = subdivisions;
- ground._width = width;
- ground._height = height;
- ground._maxX = ground._width / 2;
- ground._maxZ = ground._height / 2;
- ground._minX = -ground._maxX;
- ground._minZ = -ground._maxZ;
- ground._setReady(false);
- var onload = function (img) {
- // Getting height map data
- var canvas = document.createElement("canvas");
- var context = canvas.getContext("2d");
- var bufferWidth = img.width;
- var bufferHeight = img.height;
- canvas.width = bufferWidth;
- canvas.height = bufferHeight;
- context.drawImage(img, 0, 0);
- // Create VertexData from map data
- // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
- var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
- var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
- width: width, height: height,
- subdivisions: subdivisions,
- minHeight: minHeight, maxHeight: maxHeight,
- buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
- });
- vertexData.applyToMesh(ground, updatable);
- ground._setReady(true);
- //execute ready callback, if set
- if (onReady) {
- onReady(ground);
- }
- };
- BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
- return ground;
- };
- /**
- * Creates a tube mesh.
- * 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.
- *
- * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
- * The parameter `path` is a required array of successive `Vector3`. It is the curve used as the axis of the tube.
- * The parameter `radius` (positive float, default 1) sets the tube radius size.
- * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
- * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
- * 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.
- * It must return a radius value (positive float) :
- * ```var radiusFunction = function(i, distance) {
- * // do things
- * return radius; }```
- * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
- * 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
- * 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
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- MeshBuilder.CreateTube = function (name, options, scene) {
- var path = options.path;
- var radius = options.radius || 1;
- var tessellation = options.tessellation || 64;
- var radiusFunction = options.radiusFunction;
- var cap = options.cap || BABYLON.Mesh.NO_CAP;
- var updatable = options.updatable;
- var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
- var instance = options.instance;
- options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
- // tube geometry
- var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
- var tangents = path3D.getTangents();
- var normals = path3D.getNormals();
- var distances = path3D.getDistances();
- var pi2 = Math.PI * 2;
- var step = pi2 / tessellation * arc;
- var returnRadius = function () { return radius; };
- var radiusFunctionFinal = radiusFunction || returnRadius;
- var circlePath;
- var rad;
- var normal;
- var rotated;
- var rotationMatrix = BABYLON.Tmp.Matrix[0];
- var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
- for (var i = 0; i < path.length; i++) {
- rad = radiusFunctionFinal(i, distances[i]); // current radius
- circlePath = Array(); // current circle array
- normal = normals[i]; // current normal
- for (var t = 0; t < tessellation; t++) {
- BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
- rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
- BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
- rotated.scaleInPlace(rad).addInPlace(path[i]);
- circlePath[t] = rotated;
- }
- circlePaths[index] = circlePath;
- index++;
- }
- // cap
- var capPath = function (nbPoints, pathIndex) {
- var pointCap = Array();
- for (var i = 0; i < nbPoints; i++) {
- pointCap.push(path[pathIndex]);
- }
- return pointCap;
- };
- switch (cap) {
- case BABYLON.Mesh.NO_CAP:
- break;
- case BABYLON.Mesh.CAP_START:
- circlePaths[0] = capPath(tessellation, 0);
- circlePaths[1] = circlePaths[2].slice(0);
- break;
- case BABYLON.Mesh.CAP_END:
- circlePaths[index] = circlePaths[index - 1].slice(0);
- circlePaths[index + 1] = capPath(tessellation, path.length - 1);
- break;
- case BABYLON.Mesh.CAP_ALL:
- circlePaths[0] = capPath(tessellation, 0);
- circlePaths[1] = circlePaths[2].slice(0);
- circlePaths[index] = circlePaths[index - 1].slice(0);
- circlePaths[index + 1] = capPath(tessellation, path.length - 1);
- break;
- default:
- break;
- }
- return circlePaths;
- };
- var path3D;
- var pathArray;
- if (instance) {
- var arc = options.arc || instance.arc;
- path3D = (instance.path3D).update(path);
- pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
- instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
- instance.path3D = path3D;
- instance.pathArray = pathArray;
- instance.arc = arc;
- return instance;
- }
- // tube creation
- path3D = new BABYLON.Path3D(path);
- var newPathArray = new Array();
- cap = (cap < 0 || cap > 3) ? 0 : cap;
- pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
- var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
- tube.pathArray = pathArray;
- tube.path3D = path3D;
- tube.tessellation = tessellation;
- tube.cap = cap;
- tube.arc = options.arc;
- return tube;
- };
- /**
- * Creates a polyhedron mesh.
- *
- * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
- * 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
- * to choose the wanted type.
- * The parameter `size` (positive float, default 1) sets the polygon size.
- * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
- * 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`.
- * 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
- * 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)`).
- * 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
- * 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.
- * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- */
- MeshBuilder.CreatePolyhedron = function (name, options, scene) {
- var polyhedron = new BABYLON.Mesh(name, scene);
- var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
- vertexData.applyToMesh(polyhedron, options.updatable);
- return polyhedron;
- };
- /**
- * Creates a decal mesh.
- * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
- * 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.
- * The parameter `position` (`Vector3`, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
- * The parameter `normal` (`Vector3`, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
- * The parameter `size` (`Vector3`, default `(1, 1, 1)`) sets the decal scaling.
- * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
- */
- MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
- var indices = sourceMesh.getIndices();
- var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
- var position = options.position || BABYLON.Vector3.Zero();
- var normal = options.normal || BABYLON.Vector3.Up();
- var size = options.size || new BABYLON.Vector3(1, 1, 1);
- var angle = options.angle || 0;
- // Getting correct rotation
- if (!normal) {
- var target = new BABYLON.Vector3(0, 0, 1);
- var camera = sourceMesh.getScene().activeCamera;
- var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
- normal = camera.globalPosition.subtract(cameraWorldTarget);
- }
- var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
- var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
- var pitch = Math.atan2(normal.y, len);
- // Matrix
- var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
- var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
- var meshWorldMatrix = sourceMesh.getWorldMatrix();
- var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
- var vertexData = new BABYLON.VertexData();
- vertexData.indices = [];
- vertexData.positions = [];
- vertexData.normals = [];
- vertexData.uvs = [];
- var currentVertexDataIndex = 0;
- var extractDecalVector3 = function (indexId) {
- var vertexId = indices[indexId];
- var result = new BABYLON.PositionNormalVertex();
- result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
- // Send vector to decal local world
- result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
- // Get normal
- result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
- return result;
- }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
- var clip = function (vertices, axis) {
- if (vertices.length === 0) {
- return vertices;
- }
- var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
- var clipVertices = function (v0, v1) {
- var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
- return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
- };
- var result = new Array();
- for (var index = 0; index < vertices.length; index += 3) {
- var v1Out;
- var v2Out;
- var v3Out;
- var total = 0;
- var nV1, nV2, nV3, nV4;
- var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
- var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
- var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
- v1Out = d1 > 0;
- v2Out = d2 > 0;
- v3Out = d3 > 0;
- total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
- switch (total) {
- case 0:
- result.push(vertices[index]);
- result.push(vertices[index + 1]);
- result.push(vertices[index + 2]);
- break;
- case 1:
- if (v1Out) {
- nV1 = vertices[index + 1];
- nV2 = vertices[index + 2];
- nV3 = clipVertices(vertices[index], nV1);
- nV4 = clipVertices(vertices[index], nV2);
- }
- if (v2Out) {
- nV1 = vertices[index];
- nV2 = vertices[index + 2];
- nV3 = clipVertices(vertices[index + 1], nV1);
- nV4 = clipVertices(vertices[index + 1], nV2);
- result.push(nV3);
- result.push(nV2.clone());
- result.push(nV1.clone());
- result.push(nV2.clone());
- result.push(nV3.clone());
- result.push(nV4);
- break;
- }
- if (v3Out) {
- nV1 = vertices[index];
- nV2 = vertices[index + 1];
- nV3 = clipVertices(vertices[index + 2], nV1);
- nV4 = clipVertices(vertices[index + 2], nV2);
- }
- result.push(nV1.clone());
- result.push(nV2.clone());
- result.push(nV3);
- result.push(nV4);
- result.push(nV3.clone());
- result.push(nV2.clone());
- break;
- case 2:
- if (!v1Out) {
- nV1 = vertices[index].clone();
- nV2 = clipVertices(nV1, vertices[index + 1]);
- nV3 = clipVertices(nV1, vertices[index + 2]);
- result.push(nV1);
- result.push(nV2);
- result.push(nV3);
- }
- if (!v2Out) {
- nV1 = vertices[index + 1].clone();
- nV2 = clipVertices(nV1, vertices[index + 2]);
- nV3 = clipVertices(nV1, vertices[index]);
- result.push(nV1);
- result.push(nV2);
- result.push(nV3);
- }
- if (!v3Out) {
- nV1 = vertices[index + 2].clone();
- nV2 = clipVertices(nV1, vertices[index]);
- nV3 = clipVertices(nV1, vertices[index + 1]);
- result.push(nV1);
- result.push(nV2);
- result.push(nV3);
- }
- break;
- case 3:
- break;
- }
- }
- return result;
- };
- for (var index = 0; index < indices.length; index += 3) {
- var faceVertices = new Array();
- faceVertices.push(extractDecalVector3(index));
- faceVertices.push(extractDecalVector3(index + 1));
- faceVertices.push(extractDecalVector3(index + 2));
- // Clip
- faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
- faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
- faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
- faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
- faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
- faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
- if (faceVertices.length === 0) {
- continue;
- }
- // Add UVs and get back to world
- for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
- var vertex = faceVertices[vIndex];
- //TODO check for Int32Array
- vertexData.indices.push(currentVertexDataIndex);
- vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
- vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
- vertexData.uvs.push(0.5 + vertex.position.x / size.x);
- vertexData.uvs.push(0.5 + vertex.position.y / size.y);
- currentVertexDataIndex++;
- }
- }
- // Return mesh
- var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
- vertexData.applyToMesh(decal);
- decal.position = position.clone();
- decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
- return decal;
- };
- // Privates
- MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
- // extrusion geometry
- var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
- var tangents = path3D.getTangents();
- var normals = path3D.getNormals();
- var binormals = path3D.getBinormals();
- var distances = path3D.getDistances();
- var angle = 0;
- var returnScale = function () { return scale; };
- var returnRotation = function () { return rotation; };
- var rotate = custom ? rotateFunction : returnRotation;
- var scl = custom ? scaleFunction : returnScale;
- var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
- var rotationMatrix = BABYLON.Tmp.Matrix[0];
- for (var i = 0; i < curve.length; i++) {
- var shapePath = new Array();
- var angleStep = rotate(i, distances[i]);
- var scaleRatio = scl(i, distances[i]);
- for (var p = 0; p < shape.length; p++) {
- BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
- var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
- var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
- BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
- rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
- shapePath[p] = rotated;
- }
- shapePaths[index] = shapePath;
- angle += angleStep;
- index++;
- }
- // cap
- var capPath = function (shapePath) {
- var pointCap = Array();
- var barycenter = BABYLON.Vector3.Zero();
- var i;
- for (i = 0; i < shapePath.length; i++) {
- barycenter.addInPlace(shapePath[i]);
- }
- barycenter.scaleInPlace(1 / shapePath.length);
- for (i = 0; i < shapePath.length; i++) {
- pointCap.push(barycenter);
- }
- return pointCap;
- };
- switch (cap) {
- case BABYLON.Mesh.NO_CAP:
- break;
- case BABYLON.Mesh.CAP_START:
- shapePaths[0] = capPath(shapePaths[2]);
- shapePaths[1] = shapePaths[2].slice(0);
- break;
- case BABYLON.Mesh.CAP_END:
- shapePaths[index] = shapePaths[index - 1];
- shapePaths[index + 1] = capPath(shapePaths[index - 1]);
- break;
- case BABYLON.Mesh.CAP_ALL:
- shapePaths[0] = capPath(shapePaths[2]);
- shapePaths[1] = shapePaths[2].slice(0);
- shapePaths[index] = shapePaths[index - 1];
- shapePaths[index + 1] = capPath(shapePaths[index - 1]);
- break;
- default:
- break;
- }
- return shapePaths;
- };
- var path3D;
- var pathArray;
- if (instance) {
- path3D = (instance.path3D).update(curve);
- pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
- instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
- return instance;
- }
- // extruded shape creation
- path3D = new BABYLON.Path3D(curve);
- var newShapePaths = new Array();
- cap = (cap < 0 || cap > 3) ? 0 : cap;
- pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
- var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
- extrudedGeneric.pathArray = pathArray;
- extrudedGeneric.path3D = path3D;
- extrudedGeneric.cap = cap;
- return extrudedGeneric;
- };
- return MeshBuilder;
- })();
- BABYLON.MeshBuilder = MeshBuilder;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var BaseTexture = (function () {
- function BaseTexture(scene) {
- this.hasAlpha = false;
- this.getAlphaFromRGB = false;
- this.level = 1;
- this.coordinatesIndex = 0;
- this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
- this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
- this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
- this.anisotropicFilteringLevel = 4;
- this.isCube = false;
- this.isRenderTarget = false;
- this.animations = new Array();
- this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
- this._scene = scene;
- this._scene.textures.push(this);
- }
- BaseTexture.prototype.getScene = function () {
- return this._scene;
- };
- BaseTexture.prototype.getTextureMatrix = function () {
- return null;
- };
- BaseTexture.prototype.getReflectionTextureMatrix = function () {
- return null;
- };
- BaseTexture.prototype.getInternalTexture = function () {
- return this._texture;
- };
- BaseTexture.prototype.isReady = function () {
- if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
- return true;
- }
- if (this._texture) {
- return this._texture.isReady;
- }
- return false;
- };
- BaseTexture.prototype.getSize = function () {
- if (this._texture._width) {
- return { width: this._texture._width, height: this._texture._height };
- }
- if (this._texture._size) {
- return { width: this._texture._size, height: this._texture._size };
- }
- return { width: 0, height: 0 };
- };
- BaseTexture.prototype.getBaseSize = function () {
- if (!this.isReady() || !this._texture)
- return { width: 0, height: 0 };
- if (this._texture._size) {
- return { width: this._texture._size, height: this._texture._size };
- }
- return { width: this._texture._baseWidth, height: this._texture._baseHeight };
- };
- BaseTexture.prototype.scale = function (ratio) {
- };
- Object.defineProperty(BaseTexture.prototype, "canRescale", {
- get: function () {
- return false;
- },
- enumerable: true,
- configurable: true
- });
- BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
- var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
- for (var index = 0; index < texturesCache.length; index++) {
- var texturesCacheEntry = texturesCache[index];
- if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
- texturesCache.splice(index, 1);
- return;
- }
- }
- };
- BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
- var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
- for (var index = 0; index < texturesCache.length; index++) {
- var texturesCacheEntry = texturesCache[index];
- if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
- if (!sampling || sampling === texturesCacheEntry.samplingMode) {
- texturesCacheEntry.references++;
- return texturesCacheEntry;
- }
- }
- }
- return null;
- };
- BaseTexture.prototype.delayLoad = function () {
- };
- BaseTexture.prototype.clone = function () {
- return null;
- };
- BaseTexture.prototype.releaseInternalTexture = function () {
- if (this._texture) {
- this._scene.getEngine().releaseInternalTexture(this._texture);
- delete this._texture;
- }
- };
- BaseTexture.prototype.dispose = function () {
- // Animations
- this.getScene().stopAnimation(this);
- // Remove from scene
- var index = this._scene.textures.indexOf(this);
- if (index >= 0) {
- this._scene.textures.splice(index, 1);
- }
- if (this._texture === undefined) {
- return;
- }
- // Release
- this.releaseInternalTexture();
- // Callback
- if (this.onDispose) {
- this.onDispose();
- }
- };
- BaseTexture.prototype.serialize = function () {
- if (!this.name) {
- return null;
- }
- var serializationObject = BABYLON.SerializationHelper.Serialize(this);
- // Animations
- BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
- return serializationObject;
- };
- __decorate([
- BABYLON.serialize()
- ], BaseTexture.prototype, "name", void 0);
- __decorate([
- BABYLON.serialize()
- ], BaseTexture.prototype, "hasAlpha", void 0);
- __decorate([
- BABYLON.serialize()
- ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
- __decorate([
- BABYLON.serialize()
- ], BaseTexture.prototype, "level", void 0);
- __decorate([
- BABYLON.serialize()
- ], BaseTexture.prototype, "coordinatesIndex", void 0);
- __decorate([
- BABYLON.serialize()
- ], BaseTexture.prototype, "coordinatesMode", void 0);
- __decorate([
- BABYLON.serialize()
- ], BaseTexture.prototype, "wrapU", void 0);
- __decorate([
- BABYLON.serialize()
- ], BaseTexture.prototype, "wrapV", void 0);
- __decorate([
- BABYLON.serialize()
- ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
- __decorate([
- BABYLON.serialize()
- ], BaseTexture.prototype, "isCube", void 0);
- __decorate([
- BABYLON.serialize()
- ], BaseTexture.prototype, "isRenderTarget", void 0);
- return BaseTexture;
- })();
- BABYLON.BaseTexture = BaseTexture;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Texture = (function (_super) {
- __extends(Texture, _super);
- function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
- if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
- if (onLoad === void 0) { onLoad = null; }
- if (onError === void 0) { onError = null; }
- if (buffer === void 0) { buffer = null; }
- if (deleteBuffer === void 0) { deleteBuffer = false; }
- _super.call(this, scene);
- this.uOffset = 0;
- this.vOffset = 0;
- this.uScale = 1.0;
- this.vScale = 1.0;
- this.uAng = 0;
- this.vAng = 0;
- this.wAng = 0;
- this.name = url;
- this.url = url;
- this._noMipmap = noMipmap;
- this._invertY = invertY;
- this._samplingMode = samplingMode;
- this._buffer = buffer;
- this._deleteBuffer = deleteBuffer;
- if (!url) {
- return;
- }
- this._texture = this._getFromCache(url, noMipmap, samplingMode);
- if (!this._texture) {
- if (!scene.useDelayedTextureLoading) {
- this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
- if (deleteBuffer) {
- delete this._buffer;
- }
- }
- else {
- this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
- this._delayedOnLoad = onLoad;
- this._delayedOnError = onError;
- }
- }
- else {
- BABYLON.Tools.SetImmediate(function () {
- if (onLoad) {
- onLoad();
- }
- });
- }
- }
- Texture.prototype.delayLoad = function () {
- if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
- return;
- }
- this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
- this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
- if (!this._texture) {
- this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
- if (this._deleteBuffer) {
- delete this._buffer;
- }
- }
- };
- Texture.prototype.updateSamplingMode = function (samplingMode) {
- if (!this._texture) {
- return;
- }
- this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
- };
- Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
- x *= this.uScale;
- y *= this.vScale;
- x -= 0.5 * this.uScale;
- y -= 0.5 * this.vScale;
- z -= 0.5;
- BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
- t.x += 0.5 * this.uScale + this.uOffset;
- t.y += 0.5 * this.vScale + this.vOffset;
- t.z += 0.5;
- };
- Texture.prototype.getTextureMatrix = function () {
- if (this.uOffset === this._cachedUOffset &&
- this.vOffset === this._cachedVOffset &&
- this.uScale === this._cachedUScale &&
- this.vScale === this._cachedVScale &&
- this.uAng === this._cachedUAng &&
- this.vAng === this._cachedVAng &&
- this.wAng === this._cachedWAng) {
- return this._cachedTextureMatrix;
- }
- this._cachedUOffset = this.uOffset;
- this._cachedVOffset = this.vOffset;
- this._cachedUScale = this.uScale;
- this._cachedVScale = this.vScale;
- this._cachedUAng = this.uAng;
- this._cachedVAng = this.vAng;
- this._cachedWAng = this.wAng;
- if (!this._cachedTextureMatrix) {
- this._cachedTextureMatrix = BABYLON.Matrix.Zero();
- this._rowGenerationMatrix = new BABYLON.Matrix();
- this._t0 = BABYLON.Vector3.Zero();
- this._t1 = BABYLON.Vector3.Zero();
- this._t2 = BABYLON.Vector3.Zero();
- }
- BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
- this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
- this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
- this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
- this._t1.subtractInPlace(this._t0);
- this._t2.subtractInPlace(this._t0);
- BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
- this._cachedTextureMatrix.m[0] = this._t1.x;
- this._cachedTextureMatrix.m[1] = this._t1.y;
- this._cachedTextureMatrix.m[2] = this._t1.z;
- this._cachedTextureMatrix.m[4] = this._t2.x;
- this._cachedTextureMatrix.m[5] = this._t2.y;
- this._cachedTextureMatrix.m[6] = this._t2.z;
- this._cachedTextureMatrix.m[8] = this._t0.x;
- this._cachedTextureMatrix.m[9] = this._t0.y;
- this._cachedTextureMatrix.m[10] = this._t0.z;
- return this._cachedTextureMatrix;
- };
- Texture.prototype.getReflectionTextureMatrix = function () {
- if (this.uOffset === this._cachedUOffset &&
- this.vOffset === this._cachedVOffset &&
- this.uScale === this._cachedUScale &&
- this.vScale === this._cachedVScale &&
- this.coordinatesMode === this._cachedCoordinatesMode) {
- return this._cachedTextureMatrix;
- }
- if (!this._cachedTextureMatrix) {
- this._cachedTextureMatrix = BABYLON.Matrix.Zero();
- this._projectionModeMatrix = BABYLON.Matrix.Zero();
- }
- this._cachedCoordinatesMode = this.coordinatesMode;
- switch (this.coordinatesMode) {
- case Texture.PLANAR_MODE:
- BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
- this._cachedTextureMatrix[0] = this.uScale;
- this._cachedTextureMatrix[5] = this.vScale;
- this._cachedTextureMatrix[12] = this.uOffset;
- this._cachedTextureMatrix[13] = this.vOffset;
- break;
- case Texture.PROJECTION_MODE:
- BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
- this._projectionModeMatrix.m[0] = 0.5;
- this._projectionModeMatrix.m[5] = -0.5;
- this._projectionModeMatrix.m[10] = 0.0;
- this._projectionModeMatrix.m[12] = 0.5;
- this._projectionModeMatrix.m[13] = 0.5;
- this._projectionModeMatrix.m[14] = 1.0;
- this._projectionModeMatrix.m[15] = 1.0;
- this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
- break;
- default:
- BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
- break;
- }
- return this._cachedTextureMatrix;
- };
- Texture.prototype.clone = function () {
- var _this = this;
- return BABYLON.SerializationHelper.Clone(function () {
- return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
- }, this);
- };
- // Statics
- Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
- if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
- if (onLoad === void 0) { onLoad = null; }
- if (onError === void 0) { onError = null; }
- return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
- };
- Texture.Parse = function (parsedTexture, scene, rootUrl) {
- if (parsedTexture.isCube) {
- return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
- }
- if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
- return null;
- }
- var texture = BABYLON.SerializationHelper.Parse(function () {
- if (parsedTexture.mirrorPlane) {
- var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
- mirrorTexture._waitingRenderList = parsedTexture.renderList;
- mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
- return mirrorTexture;
- }
- else if (parsedTexture.isRenderTarget) {
- var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
- renderTargetTexture._waitingRenderList = parsedTexture.renderList;
- return renderTargetTexture;
- }
- else {
- var texture;
- if (parsedTexture.base64String) {
- texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
- }
- else {
- texture = new Texture(rootUrl + parsedTexture.name, scene);
- }
- return texture;
- }
- }, parsedTexture, scene);
- // Animations
- if (parsedTexture.animations) {
- for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
- var parsedAnimation = parsedTexture.animations[animationIndex];
- texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
- }
- }
- return texture;
- };
- // Constants
- Texture.NEAREST_SAMPLINGMODE = 1;
- Texture.BILINEAR_SAMPLINGMODE = 2;
- Texture.TRILINEAR_SAMPLINGMODE = 3;
- Texture.EXPLICIT_MODE = 0;
- Texture.SPHERICAL_MODE = 1;
- Texture.PLANAR_MODE = 2;
- Texture.CUBIC_MODE = 3;
- Texture.PROJECTION_MODE = 4;
- Texture.SKYBOX_MODE = 5;
- Texture.INVCUBIC_MODE = 6;
- Texture.EQUIRECTANGULAR_MODE = 7;
- Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
- Texture.CLAMP_ADDRESSMODE = 0;
- Texture.WRAP_ADDRESSMODE = 1;
- Texture.MIRROR_ADDRESSMODE = 2;
- __decorate([
- BABYLON.serialize()
- ], Texture.prototype, "url", void 0);
- __decorate([
- BABYLON.serialize()
- ], Texture.prototype, "uOffset", void 0);
- __decorate([
- BABYLON.serialize()
- ], Texture.prototype, "vOffset", void 0);
- __decorate([
- BABYLON.serialize()
- ], Texture.prototype, "uScale", void 0);
- __decorate([
- BABYLON.serialize()
- ], Texture.prototype, "vScale", void 0);
- __decorate([
- BABYLON.serialize()
- ], Texture.prototype, "uAng", void 0);
- __decorate([
- BABYLON.serialize()
- ], Texture.prototype, "vAng", void 0);
- __decorate([
- BABYLON.serialize()
- ], Texture.prototype, "wAng", void 0);
- return Texture;
- })(BABYLON.BaseTexture);
- BABYLON.Texture = Texture;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var CubeTexture = (function (_super) {
- __extends(CubeTexture, _super);
- function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
- _super.call(this, scene);
- this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
- this.name = rootUrl;
- this.url = rootUrl;
- this._noMipmap = noMipmap;
- this.hasAlpha = false;
- if (!rootUrl && !files) {
- return;
- }
- this._texture = this._getFromCache(rootUrl, noMipmap);
- if (!files) {
- if (!extensions) {
- extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
- }
- files = [];
- for (var index = 0; index < extensions.length; index++) {
- files.push(rootUrl + extensions[index]);
- }
- this._extensions = extensions;
- }
- this._files = files;
- if (!this._texture) {
- if (!scene.useDelayedTextureLoading) {
- this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
- }
- else {
- this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
- }
- }
- this.isCube = true;
- this._textureMatrix = BABYLON.Matrix.Identity();
- }
- CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
- return new CubeTexture("", scene, null, noMipmap, files);
- };
- // Methods
- CubeTexture.prototype.delayLoad = function () {
- if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
- return;
- }
- this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
- this._texture = this._getFromCache(this.url, this._noMipmap);
- if (!this._texture) {
- this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
- }
- };
- CubeTexture.prototype.getReflectionTextureMatrix = function () {
- return this._textureMatrix;
- };
- CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
- var texture = BABYLON.SerializationHelper.Parse(function () {
- return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
- }, parsedTexture, scene);
- // Animations
- if (parsedTexture.animations) {
- for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
- var parsedAnimation = parsedTexture.animations[animationIndex];
- texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
- }
- }
- return texture;
- };
- CubeTexture.prototype.clone = function () {
- var _this = this;
- return BABYLON.SerializationHelper.Clone(function () {
- return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
- }, this);
- };
- return CubeTexture;
- })(BABYLON.BaseTexture);
- BABYLON.CubeTexture = CubeTexture;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var RenderTargetTexture = (function (_super) {
- __extends(RenderTargetTexture, _super);
- function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
- if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
- if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
- if (isCube === void 0) { isCube = false; }
- _super.call(this, null, scene, !generateMipMaps);
- this.isCube = isCube;
- this.renderList = new Array();
- this.renderParticles = true;
- this.renderSprites = false;
- this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
- this._currentRefreshId = -1;
- this._refreshRate = 1;
- this.name = name;
- this.isRenderTarget = true;
- this._size = size;
- this._generateMipMaps = generateMipMaps;
- this._doNotChangeAspectRatio = doNotChangeAspectRatio;
- if (isCube) {
- this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
- this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
- this._textureMatrix = BABYLON.Matrix.Identity();
- }
- else {
- this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
- }
- // Rendering groups
- this._renderingManager = new BABYLON.RenderingManager(scene);
- }
- Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
- get: function () {
- return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
- get: function () {
- return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
- get: function () {
- return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
- },
- enumerable: true,
- configurable: true
- });
- RenderTargetTexture.prototype.resetRefreshCounter = function () {
- this._currentRefreshId = -1;
- };
- Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
- get: function () {
- return this._refreshRate;
- },
- // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
- set: function (value) {
- this._refreshRate = value;
- this.resetRefreshCounter();
- },
- enumerable: true,
- configurable: true
- });
- RenderTargetTexture.prototype._shouldRender = function () {
- if (this._currentRefreshId === -1) {
- this._currentRefreshId = 1;
- return true;
- }
- if (this.refreshRate === this._currentRefreshId) {
- this._currentRefreshId = 1;
- return true;
- }
- this._currentRefreshId++;
- return false;
- };
- RenderTargetTexture.prototype.isReady = function () {
- if (!this.getScene().renderTargetsEnabled) {
- return false;
- }
- return _super.prototype.isReady.call(this);
- };
- RenderTargetTexture.prototype.getRenderSize = function () {
- return this._size;
- };
- Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
- get: function () {
- return true;
- },
- enumerable: true,
- configurable: true
- });
- RenderTargetTexture.prototype.scale = function (ratio) {
- var newSize = this._size * ratio;
- this.resize(newSize, this._generateMipMaps);
- };
- RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
- if (this.isCube) {
- return this._textureMatrix;
- }
- return _super.prototype.getReflectionTextureMatrix.call(this);
- };
- RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
- this.releaseInternalTexture();
- if (this.isCube) {
- this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
- }
- else {
- this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
- }
- };
- RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
- var scene = this.getScene();
- if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
- scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
- }
- if (this._waitingRenderList) {
- this.renderList = [];
- for (var index = 0; index < this._waitingRenderList.length; index++) {
- var id = this._waitingRenderList[index];
- this.renderList.push(scene.getMeshByID(id));
- }
- delete this._waitingRenderList;
- }
- if (this.renderList && this.renderList.length === 0) {
- return;
- }
- // Prepare renderingManager
- this._renderingManager.reset();
- var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
- var sceneRenderId = scene.getRenderId();
- for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
- var mesh = currentRenderList[meshIndex];
- if (mesh) {
- if (!mesh.isReady()) {
- // Reset _currentRefreshId
- this.resetRefreshCounter();
- continue;
- }
- mesh._preActivateForIntermediateRendering(sceneRenderId);
- if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
- mesh._activate(sceneRenderId);
- for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
- var subMesh = mesh.subMeshes[subIndex];
- scene._activeIndices += subMesh.indexCount;
- this._renderingManager.dispatch(subMesh);
- }
- }
- }
- }
- if (this.isCube) {
- for (var face = 0; face < 6; face++) {
- this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
- scene.incrementRenderId();
- scene.resetCachedMaterial();
- }
- }
- else {
- this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
- }
- if (this.onAfterUnbind) {
- this.onAfterUnbind();
- }
- if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
- scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
- }
- scene.resetCachedMaterial();
- };
- RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
- var scene = this.getScene();
- var engine = scene.getEngine();
- // Bind
- if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
- if (this.isCube) {
- engine.bindFramebuffer(this._texture, faceIndex);
- }
- else {
- engine.bindFramebuffer(this._texture);
- }
- }
- if (this.onBeforeRender) {
- this.onBeforeRender(faceIndex);
- }
- // Clear
- if (this.onClear) {
- this.onClear(engine);
- }
- else {
- engine.clear(scene.clearColor, true, true);
- }
- if (!this._doNotChangeAspectRatio) {
- scene.updateTransformMatrix(true);
- }
- // Render
- this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
- if (useCameraPostProcess) {
- scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
- }
- if (!this._doNotChangeAspectRatio) {
- scene.updateTransformMatrix(true);
- }
- if (this.onAfterRender) {
- this.onAfterRender(faceIndex);
- }
- // Dump ?
- if (dumpForDebug) {
- BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
- }
- // Unbind
- if (!this.isCube || faceIndex === 5) {
- if (this.isCube) {
- if (faceIndex === 5) {
- engine.generateMipMapsForCubemap(this._texture);
- }
- }
- engine.unBindFramebuffer(this._texture, this.isCube);
- }
- };
- RenderTargetTexture.prototype.clone = function () {
- var textureSize = this.getSize();
- var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
- // Base texture
- newTexture.hasAlpha = this.hasAlpha;
- newTexture.level = this.level;
- // RenderTarget Texture
- newTexture.coordinatesMode = this.coordinatesMode;
- newTexture.renderList = this.renderList.slice(0);
- return newTexture;
- };
- RenderTargetTexture.prototype.serialize = function () {
- if (!this.name) {
- return null;
- }
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.renderTargetSize = this.getRenderSize();
- serializationObject.renderList = [];
- for (var index = 0; index < this.renderList.length; index++) {
- serializationObject.renderList.push(this.renderList[index].id);
- }
- return serializationObject;
- };
- RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
- RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
- RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
- return RenderTargetTexture;
- })(BABYLON.Texture);
- BABYLON.RenderTargetTexture = RenderTargetTexture;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var ProceduralTexture = (function (_super) {
- __extends(ProceduralTexture, _super);
- function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
- if (generateMipMaps === void 0) { generateMipMaps = true; }
- if (isCube === void 0) { isCube = false; }
- _super.call(this, null, scene, !generateMipMaps);
- this.isCube = isCube;
- this.isEnabled = true;
- this._currentRefreshId = -1;
- this._refreshRate = 1;
- this._vertexDeclaration = [2];
- this._vertexStrideSize = 2 * 4;
- this._uniforms = new Array();
- this._samplers = new Array();
- this._textures = new Array();
- this._floats = new Array();
- this._floatsArrays = {};
- this._colors3 = new Array();
- this._colors4 = new Array();
- this._vectors2 = new Array();
- this._vectors3 = new Array();
- this._matrices = new Array();
- this._fallbackTextureUsed = false;
- scene._proceduralTextures.push(this);
- this.name = name;
- this.isRenderTarget = true;
- this._size = size;
- this._generateMipMaps = generateMipMaps;
- this.setFragment(fragment);
- this._fallbackTexture = fallbackTexture;
- if (isCube) {
- this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
- this.setFloat("face", 0);
- }
- else {
- this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
- }
- // VBO
- var vertices = [];
- vertices.push(1, 1);
- vertices.push(-1, 1);
- vertices.push(-1, -1);
- vertices.push(1, -1);
- this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
- // Indices
- var indices = [];
- indices.push(0);
- indices.push(1);
- indices.push(2);
- indices.push(0);
- indices.push(2);
- indices.push(3);
- this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
- }
- ProceduralTexture.prototype.reset = function () {
- if (this._effect === undefined) {
- return;
- }
- var engine = this.getScene().getEngine();
- engine._releaseEffect(this._effect);
- };
- ProceduralTexture.prototype.isReady = function () {
- var _this = this;
- var engine = this.getScene().getEngine();
- var shaders;
- if (!this._fragment) {
- return false;
- }
- if (this._fallbackTextureUsed) {
- return true;
- }
- if (this._fragment.fragmentElement !== undefined) {
- shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
- }
- else {
- shaders = { vertex: "procedural", fragment: this._fragment };
- }
- this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
- _this.releaseInternalTexture();
- if (_this._fallbackTexture) {
- _this._texture = _this._fallbackTexture._texture;
- _this._texture.references++;
- }
- _this._fallbackTextureUsed = true;
- });
- return this._effect.isReady();
- };
- ProceduralTexture.prototype.resetRefreshCounter = function () {
- this._currentRefreshId = -1;
- };
- ProceduralTexture.prototype.setFragment = function (fragment) {
- this._fragment = fragment;
- };
- Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
- get: function () {
- return this._refreshRate;
- },
- // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
- set: function (value) {
- this._refreshRate = value;
- this.resetRefreshCounter();
- },
- enumerable: true,
- configurable: true
- });
- ProceduralTexture.prototype._shouldRender = function () {
- if (!this.isEnabled || !this.isReady() || !this._texture) {
- return false;
- }
- if (this._fallbackTextureUsed) {
- return false;
- }
- if (this._currentRefreshId === -1) {
- this._currentRefreshId = 1;
- return true;
- }
- if (this.refreshRate === this._currentRefreshId) {
- this._currentRefreshId = 1;
- return true;
- }
- this._currentRefreshId++;
- return false;
- };
- ProceduralTexture.prototype.getRenderSize = function () {
- return this._size;
- };
- ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
- if (this._fallbackTextureUsed) {
- return;
- }
- this.releaseInternalTexture();
- this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
- };
- ProceduralTexture.prototype._checkUniform = function (uniformName) {
- if (this._uniforms.indexOf(uniformName) === -1) {
- this._uniforms.push(uniformName);
- }
- };
- ProceduralTexture.prototype.setTexture = function (name, texture) {
- if (this._samplers.indexOf(name) === -1) {
- this._samplers.push(name);
- }
- this._textures[name] = texture;
- return this;
- };
- ProceduralTexture.prototype.setFloat = function (name, value) {
- this._checkUniform(name);
- this._floats[name] = value;
- return this;
- };
- ProceduralTexture.prototype.setFloats = function (name, value) {
- this._checkUniform(name);
- this._floatsArrays[name] = value;
- return this;
- };
- ProceduralTexture.prototype.setColor3 = function (name, value) {
- this._checkUniform(name);
- this._colors3[name] = value;
- return this;
- };
- ProceduralTexture.prototype.setColor4 = function (name, value) {
- this._checkUniform(name);
- this._colors4[name] = value;
- return this;
- };
- ProceduralTexture.prototype.setVector2 = function (name, value) {
- this._checkUniform(name);
- this._vectors2[name] = value;
- return this;
- };
- ProceduralTexture.prototype.setVector3 = function (name, value) {
- this._checkUniform(name);
- this._vectors3[name] = value;
- return this;
- };
- ProceduralTexture.prototype.setMatrix = function (name, value) {
- this._checkUniform(name);
- this._matrices[name] = value;
- return this;
- };
- ProceduralTexture.prototype.render = function (useCameraPostProcess) {
- var scene = this.getScene();
- var engine = scene.getEngine();
- // Render
- engine.enableEffect(this._effect);
- engine.setState(false);
- // Texture
- for (var name in this._textures) {
- this._effect.setTexture(name, this._textures[name]);
- }
- // Float
- for (name in this._floats) {
- this._effect.setFloat(name, this._floats[name]);
- }
- // Floats
- for (name in this._floatsArrays) {
- this._effect.setArray(name, this._floatsArrays[name]);
- }
- // Color3
- for (name in this._colors3) {
- this._effect.setColor3(name, this._colors3[name]);
- }
- // Color4
- for (name in this._colors4) {
- var color = this._colors4[name];
- this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
- }
- // Vector2
- for (name in this._vectors2) {
- this._effect.setVector2(name, this._vectors2[name]);
- }
- // Vector3
- for (name in this._vectors3) {
- this._effect.setVector3(name, this._vectors3[name]);
- }
- // Matrix
- for (name in this._matrices) {
- this._effect.setMatrix(name, this._matrices[name]);
- }
- // VBOs
- engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
- if (this.isCube) {
- for (var face = 0; face < 6; face++) {
- engine.bindFramebuffer(this._texture, face);
- this._effect.setFloat("face", face);
- // Clear
- engine.clear(scene.clearColor, true, true);
- // Draw order
- engine.draw(true, 0, 6);
- // Mipmaps
- if (face === 5) {
- engine.generateMipMapsForCubemap(this._texture);
- }
- }
- }
- else {
- engine.bindFramebuffer(this._texture);
- // Clear
- engine.clear(scene.clearColor, true, true);
- // Draw order
- engine.draw(true, 0, 6);
- }
- // Unbind
- engine.unBindFramebuffer(this._texture, this.isCube);
- if (this.onGenerated) {
- this.onGenerated();
- }
- };
- ProceduralTexture.prototype.clone = function () {
- var textureSize = this.getSize();
- var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
- // Base texture
- newTexture.hasAlpha = this.hasAlpha;
- newTexture.level = this.level;
- // RenderTarget Texture
- newTexture.coordinatesMode = this.coordinatesMode;
- return newTexture;
- };
- ProceduralTexture.prototype.dispose = function () {
- var index = this.getScene()._proceduralTextures.indexOf(this);
- if (index >= 0) {
- this.getScene()._proceduralTextures.splice(index, 1);
- }
- _super.prototype.dispose.call(this);
- };
- return ProceduralTexture;
- })(BABYLON.Texture);
- BABYLON.ProceduralTexture = ProceduralTexture;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var MirrorTexture = (function (_super) {
- __extends(MirrorTexture, _super);
- function MirrorTexture(name, size, scene, generateMipMaps) {
- var _this = this;
- _super.call(this, name, size, scene, generateMipMaps, true);
- this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
- this._transformMatrix = BABYLON.Matrix.Zero();
- this._mirrorMatrix = BABYLON.Matrix.Zero();
- this.onBeforeRender = function () {
- BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
- _this._savedViewMatrix = scene.getViewMatrix();
- _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
- scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
- scene.clipPlane = _this.mirrorPlane;
- scene.getEngine().cullBackFaces = false;
- scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
- };
- this.onAfterRender = function () {
- scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
- scene.getEngine().cullBackFaces = true;
- scene._mirroredCameraPosition = null;
- delete scene.clipPlane;
- };
- }
- MirrorTexture.prototype.clone = function () {
- var textureSize = this.getSize();
- var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
- // Base texture
- newTexture.hasAlpha = this.hasAlpha;
- newTexture.level = this.level;
- // Mirror Texture
- newTexture.mirrorPlane = this.mirrorPlane.clone();
- newTexture.renderList = this.renderList.slice(0);
- return newTexture;
- };
- MirrorTexture.prototype.serialize = function () {
- if (!this.name) {
- return null;
- }
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.mirrorPlane = this.mirrorPlane.asArray();
- return serializationObject;
- };
- return MirrorTexture;
- })(BABYLON.RenderTargetTexture);
- BABYLON.MirrorTexture = MirrorTexture;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- /**
- * Creates a refraction texture used by refraction channel of the standard material.
- * @param name the texture name
- * @param size size of the underlying texture
- * @param scene root scene
- */
- var RefractionTexture = (function (_super) {
- __extends(RefractionTexture, _super);
- function RefractionTexture(name, size, scene, generateMipMaps) {
- var _this = this;
- _super.call(this, name, size, scene, generateMipMaps, true);
- this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
- this.depth = 2.0;
- this.onBeforeRender = function () {
- scene.clipPlane = _this.refractionPlane;
- };
- this.onAfterRender = function () {
- delete scene.clipPlane;
- };
- }
- RefractionTexture.prototype.clone = function () {
- var textureSize = this.getSize();
- var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
- // Base texture
- newTexture.hasAlpha = this.hasAlpha;
- newTexture.level = this.level;
- // Refraction Texture
- newTexture.refractionPlane = this.refractionPlane.clone();
- newTexture.renderList = this.renderList.slice(0);
- newTexture.depth = this.depth;
- return newTexture;
- };
- RefractionTexture.prototype.serialize = function () {
- if (!this.name) {
- return null;
- }
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.mirrorPlane = this.refractionPlane.asArray();
- serializationObject.depth = this.depth;
- return serializationObject;
- };
- return RefractionTexture;
- })(BABYLON.RenderTargetTexture);
- BABYLON.RefractionTexture = RefractionTexture;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var DynamicTexture = (function (_super) {
- __extends(DynamicTexture, _super);
- function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
- _super.call(this, null, scene, !generateMipMaps);
- this.name = name;
- this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
- this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
- this._generateMipMaps = generateMipMaps;
- if (options.getContext) {
- this._canvas = options;
- this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
- }
- else {
- this._canvas = document.createElement("canvas");
- if (options.width) {
- this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
- }
- else {
- this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
- }
- }
- var textureSize = this.getSize();
- this._canvas.width = textureSize.width;
- this._canvas.height = textureSize.height;
- this._context = this._canvas.getContext("2d");
- }
- Object.defineProperty(DynamicTexture.prototype, "canRescale", {
- get: function () {
- return true;
- },
- enumerable: true,
- configurable: true
- });
- DynamicTexture.prototype.scale = function (ratio) {
- var textureSize = this.getSize();
- textureSize.width *= ratio;
- textureSize.height *= ratio;
- this._canvas.width = textureSize.width;
- this._canvas.height = textureSize.height;
- this.releaseInternalTexture();
- this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
- };
- DynamicTexture.prototype.getContext = function () {
- return this._context;
- };
- DynamicTexture.prototype.clear = function () {
- var size = this.getSize();
- this._context.fillRect(0, 0, size.width, size.height);
- };
- DynamicTexture.prototype.update = function (invertY) {
- this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
- };
- DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
- if (update === void 0) { update = true; }
- var size = this.getSize();
- if (clearColor) {
- this._context.fillStyle = clearColor;
- this._context.fillRect(0, 0, size.width, size.height);
- }
- this._context.font = font;
- if (x === null) {
- var textSize = this._context.measureText(text);
- x = (size.width - textSize.width) / 2;
- }
- this._context.fillStyle = color;
- this._context.fillText(text, x, y);
- if (update) {
- this.update(invertY);
- }
- };
- DynamicTexture.prototype.clone = function () {
- var textureSize = this.getSize();
- var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
- // Base texture
- newTexture.hasAlpha = this.hasAlpha;
- newTexture.level = this.level;
- // Dynamic Texture
- newTexture.wrapU = this.wrapU;
- newTexture.wrapV = this.wrapV;
- return newTexture;
- };
- return DynamicTexture;
- })(BABYLON.Texture);
- BABYLON.DynamicTexture = DynamicTexture;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var VideoTexture = (function (_super) {
- __extends(VideoTexture, _super);
- /**
- * Creates a video texture.
- * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
- * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
- * @param {BABYLON.Scene} scene is obviously the current scene.
- * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
- * @param {boolean} invertY is false by default but can be used to invert video on Y axis
- * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
- */
- function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
- var _this = this;
- if (generateMipMaps === void 0) { generateMipMaps = false; }
- if (invertY === void 0) { invertY = false; }
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
- _super.call(this, null, scene, !generateMipMaps, invertY);
- this._autoLaunch = true;
- var urls;
- this.name = name;
- if (urlsOrVideo instanceof HTMLVideoElement) {
- this.video = urlsOrVideo;
- }
- else {
- urls = urlsOrVideo;
- this.video = document.createElement("video");
- this.video.autoplay = false;
- this.video.loop = true;
- }
- this._generateMipMaps = generateMipMaps;
- this._samplingMode = samplingMode;
- if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
- this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
- this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
- }
- else {
- this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
- this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
- this._generateMipMaps = false;
- }
- if (urls) {
- this.video.addEventListener("canplaythrough", function () {
- _this._createTexture();
- });
- urls.forEach(function (url) {
- var source = document.createElement("source");
- source.src = url;
- _this.video.appendChild(source);
- });
- }
- else {
- this._createTexture();
- }
- this._lastUpdate = BABYLON.Tools.Now;
- }
- VideoTexture.prototype._createTexture = function () {
- this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode, false);
- this._texture.isReady = true;
- };
- VideoTexture.prototype.update = function () {
- if (this._autoLaunch) {
- this._autoLaunch = false;
- this.video.play();
- }
- var now = BABYLON.Tools.Now;
- if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
- return false;
- }
- this._lastUpdate = now;
- this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
- return true;
- };
- return VideoTexture;
- })(BABYLON.Texture);
- BABYLON.VideoTexture = VideoTexture;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var CustomProceduralTexture = (function (_super) {
- __extends(CustomProceduralTexture, _super);
- function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
- _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
- this._animate = true;
- this._time = 0;
- this._texturePath = texturePath;
- //Try to load json
- this.loadJson(texturePath);
- this.refreshRate = 1;
- }
- CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
- var _this = this;
- var that = this;
- function noConfigFile() {
- BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
- try {
- that.setFragment(that._texturePath);
- }
- catch (ex) {
- BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
- }
- }
- var configFileUrl = jsonUrl + "/config.json";
- var xhr = new XMLHttpRequest();
- xhr.open("GET", configFileUrl, true);
- xhr.addEventListener("load", function () {
- if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
- try {
- _this._config = JSON.parse(xhr.response);
- _this.updateShaderUniforms();
- _this.updateTextures();
- _this.setFragment(_this._texturePath + "/custom");
- _this._animate = _this._config.animate;
- _this.refreshRate = _this._config.refreshrate;
- }
- catch (ex) {
- noConfigFile();
- }
- }
- else {
- noConfigFile();
- }
- }, false);
- xhr.addEventListener("error", function () {
- noConfigFile();
- }, false);
- try {
- xhr.send();
- }
- catch (ex) {
- BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
- }
- };
- CustomProceduralTexture.prototype.isReady = function () {
- if (!_super.prototype.isReady.call(this)) {
- return false;
- }
- for (var name in this._textures) {
- var texture = this._textures[name];
- if (!texture.isReady()) {
- return false;
- }
- }
- return true;
- };
- CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
- if (this._animate) {
- this._time += this.getScene().getAnimationRatio() * 0.03;
- this.updateShaderUniforms();
- }
- _super.prototype.render.call(this, useCameraPostProcess);
- };
- CustomProceduralTexture.prototype.updateTextures = function () {
- for (var i = 0; i < this._config.sampler2Ds.length; i++) {
- this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
- }
- };
- CustomProceduralTexture.prototype.updateShaderUniforms = function () {
- if (this._config) {
- for (var j = 0; j < this._config.uniforms.length; j++) {
- var uniform = this._config.uniforms[j];
- switch (uniform.type) {
- case "float":
- this.setFloat(uniform.name, uniform.value);
- break;
- case "color3":
- this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
- break;
- case "color4":
- this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
- break;
- case "vector2":
- this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
- break;
- case "vector3":
- this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
- break;
- }
- }
- }
- this.setFloat("time", this._time);
- };
- Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
- get: function () {
- return this._animate;
- },
- set: function (value) {
- this._animate = value;
- },
- enumerable: true,
- configurable: true
- });
- return CustomProceduralTexture;
- })(BABYLON.ProceduralTexture);
- BABYLON.CustomProceduralTexture = CustomProceduralTexture;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var EffectFallbacks = (function () {
- function EffectFallbacks() {
- this._defines = {};
- this._currentRank = 32;
- this._maxRank = -1;
- }
- EffectFallbacks.prototype.addFallback = function (rank, define) {
- if (!this._defines[rank]) {
- if (rank < this._currentRank) {
- this._currentRank = rank;
- }
- if (rank > this._maxRank) {
- this._maxRank = rank;
- }
- this._defines[rank] = new Array();
- }
- this._defines[rank].push(define);
- };
- EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
- this._meshRank = rank;
- this._mesh = mesh;
- if (rank > this._maxRank) {
- this._maxRank = rank;
- }
- };
- Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
- get: function () {
- return this._currentRank <= this._maxRank;
- },
- enumerable: true,
- configurable: true
- });
- EffectFallbacks.prototype.reduce = function (currentDefines) {
- var currentFallbacks = this._defines[this._currentRank];
- for (var index = 0; index < currentFallbacks.length; index++) {
- currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
- }
- if (this._mesh && this._currentRank === this._meshRank) {
- this._mesh.computeBonesUsingShaders = false;
- currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
- BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
- }
- this._currentRank++;
- return currentDefines;
- };
- return EffectFallbacks;
- })();
- BABYLON.EffectFallbacks = EffectFallbacks;
- var Effect = (function () {
- function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
- var _this = this;
- this._isReady = false;
- this._compilationError = "";
- this._valueCache = [];
- this._engine = engine;
- this.name = baseName;
- this.defines = defines;
- this._uniformsNames = uniformsNames.concat(samplers);
- this._samplers = samplers;
- this._attributesNames = attributesNames;
- this.onError = onError;
- this.onCompiled = onCompiled;
- var vertexSource;
- var fragmentSource;
- if (baseName.vertexElement) {
- vertexSource = document.getElementById(baseName.vertexElement);
- if (!vertexSource) {
- vertexSource = baseName.vertexElement;
- }
- }
- else {
- vertexSource = baseName.vertex || baseName;
- }
- if (baseName.fragmentElement) {
- fragmentSource = document.getElementById(baseName.fragmentElement);
- if (!fragmentSource) {
- fragmentSource = baseName.fragmentElement;
- }
- }
- else {
- fragmentSource = baseName.fragment || baseName;
- }
- this._loadVertexShader(vertexSource, function (vertexCode) {
- _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
- _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
- _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
- _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
- });
- });
- });
- });
- }
- // Properties
- Effect.prototype.isReady = function () {
- return this._isReady;
- };
- Effect.prototype.getProgram = function () {
- return this._program;
- };
- Effect.prototype.getAttributesNames = function () {
- return this._attributesNames;
- };
- Effect.prototype.getAttributeLocation = function (index) {
- return this._attributes[index];
- };
- Effect.prototype.getAttributeLocationByName = function (name) {
- var index = this._attributesNames.indexOf(name);
- return this._attributes[index];
- };
- Effect.prototype.getAttributesCount = function () {
- return this._attributes.length;
- };
- Effect.prototype.getUniformIndex = function (uniformName) {
- return this._uniformsNames.indexOf(uniformName);
- };
- Effect.prototype.getUniform = function (uniformName) {
- return this._uniforms[this._uniformsNames.indexOf(uniformName)];
- };
- Effect.prototype.getSamplers = function () {
- return this._samplers;
- };
- Effect.prototype.getCompilationError = function () {
- return this._compilationError;
- };
- // Methods
- Effect.prototype._loadVertexShader = function (vertex, callback) {
- // DOM element ?
- if (vertex instanceof HTMLElement) {
- var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
- callback(vertexCode);
- return;
- }
- // Is in local store ?
- if (Effect.ShadersStore[vertex + "VertexShader"]) {
- callback(Effect.ShadersStore[vertex + "VertexShader"]);
- return;
- }
- var vertexShaderUrl;
- if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
- vertexShaderUrl = vertex;
- }
- else {
- vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
- }
- // Vertex shader
- BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
- };
- Effect.prototype._loadFragmentShader = function (fragment, callback) {
- // DOM element ?
- if (fragment instanceof HTMLElement) {
- var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
- callback(fragmentCode);
- return;
- }
- // Is in local store ?
- if (Effect.ShadersStore[fragment + "PixelShader"]) {
- callback(Effect.ShadersStore[fragment + "PixelShader"]);
- return;
- }
- if (Effect.ShadersStore[fragment + "FragmentShader"]) {
- callback(Effect.ShadersStore[fragment + "FragmentShader"]);
- return;
- }
- var fragmentShaderUrl;
- if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
- fragmentShaderUrl = fragment;
- }
- else {
- fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
- }
- // Fragment shader
- BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
- };
- Effect.prototype._dumpShadersName = function () {
- if (this.name.vertexElement) {
- BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
- BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
- }
- else if (this.name.vertex) {
- BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
- BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
- }
- else {
- BABYLON.Tools.Error("Vertex shader:" + this.name);
- BABYLON.Tools.Error("Fragment shader:" + this.name);
- }
- };
- Effect.prototype._processIncludes = function (sourceCode, callback) {
- var _this = this;
- var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
- var match = regex.exec(sourceCode);
- var returnValue = new String(sourceCode);
- while (match != null) {
- var includeFile = match[1];
- if (Effect.IncludesShadersStore[includeFile]) {
- // Substitution
- var includeContent = Effect.IncludesShadersStore[includeFile];
- if (match[2]) {
- var splits = match[3].split(",");
- for (var index = 0; index < splits.length; index += 2) {
- var source = new RegExp(splits[index], "g");
- var dest = splits[index + 1];
- includeContent = includeContent.replace(source, dest);
- }
- }
- if (match[4]) {
- includeContent = includeContent.replace(/\{X\}/g, match[5]);
- }
- // Replace
- returnValue = returnValue.replace(match[0], includeContent);
- }
- else {
- var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
- BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
- Effect.IncludesShadersStore[includeFile] = fileContent;
- _this._processIncludes(returnValue, callback);
- });
- return;
- }
- match = regex.exec(sourceCode);
- }
- callback(returnValue);
- };
- Effect.prototype._processPrecision = function (source) {
- if (source.indexOf("precision highp float") === -1) {
- if (!this._engine.getCaps().highPrecisionShaderSupported) {
- source = "precision mediump float;\n" + source;
- }
- else {
- source = "precision highp float;\n" + source;
- }
- }
- else {
- if (!this._engine.getCaps().highPrecisionShaderSupported) {
- source = source.replace("precision highp float", "precision mediump float");
- }
- }
- return source;
- };
- Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
- try {
- var engine = this._engine;
- // Precision
- vertexSourceCode = this._processPrecision(vertexSourceCode);
- fragmentSourceCode = this._processPrecision(fragmentSourceCode);
- this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
- this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
- this._attributes = engine.getAttributes(this._program, attributesNames);
- for (var index = 0; index < this._samplers.length; index++) {
- var sampler = this.getUniform(this._samplers[index]);
- if (sampler == null) {
- this._samplers.splice(index, 1);
- index--;
- }
- }
- engine.bindSamplers(this);
- this._isReady = true;
- if (this.onCompiled) {
- this.onCompiled(this);
- }
- }
- catch (e) {
- // Is it a problem with precision?
- if (e.message.indexOf("highp") !== -1) {
- vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
- fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
- this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
- return;
- }
- // Let's go through fallbacks then
- if (fallbacks && fallbacks.isMoreFallbacks) {
- BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
- this._dumpShadersName();
- defines = fallbacks.reduce(defines);
- this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
- }
- else {
- BABYLON.Tools.Error("Unable to compile effect: ");
- this._dumpShadersName();
- BABYLON.Tools.Error("Defines: " + defines);
- BABYLON.Tools.Error("Error: " + e.message);
- this._compilationError = e.message;
- if (this.onError) {
- this.onError(this, this._compilationError);
- }
- }
- }
- };
- Object.defineProperty(Effect.prototype, "isSupported", {
- get: function () {
- return this._compilationError === "";
- },
- enumerable: true,
- configurable: true
- });
- Effect.prototype._bindTexture = function (channel, texture) {
- this._engine._bindTexture(this._samplers.indexOf(channel), texture);
- };
- Effect.prototype.setTexture = function (channel, texture) {
- this._engine.setTexture(this._samplers.indexOf(channel), texture);
- };
- Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
- this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
- };
- Effect.prototype._cacheMatrix = function (uniformName, matrix) {
- if (!this._valueCache[uniformName]) {
- this._valueCache[uniformName] = new BABYLON.Matrix();
- }
- for (var index = 0; index < 16; index++) {
- this._valueCache[uniformName].m[index] = matrix.m[index];
- }
- };
- Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
- if (!this._valueCache[uniformName]) {
- this._valueCache[uniformName] = [x, y];
- return;
- }
- this._valueCache[uniformName][0] = x;
- this._valueCache[uniformName][1] = y;
- };
- Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
- if (!this._valueCache[uniformName]) {
- this._valueCache[uniformName] = [x, y, z];
- return;
- }
- this._valueCache[uniformName][0] = x;
- this._valueCache[uniformName][1] = y;
- this._valueCache[uniformName][2] = z;
- };
- Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
- if (!this._valueCache[uniformName]) {
- this._valueCache[uniformName] = [x, y, z, w];
- return;
- }
- this._valueCache[uniformName][0] = x;
- this._valueCache[uniformName][1] = y;
- this._valueCache[uniformName][2] = z;
- this._valueCache[uniformName][3] = w;
- };
- Effect.prototype.setArray = function (uniformName, array) {
- this._engine.setArray(this.getUniform(uniformName), array);
- return this;
- };
- Effect.prototype.setArray2 = function (uniformName, array) {
- this._engine.setArray2(this.getUniform(uniformName), array);
- return this;
- };
- Effect.prototype.setArray3 = function (uniformName, array) {
- this._engine.setArray3(this.getUniform(uniformName), array);
- return this;
- };
- Effect.prototype.setArray4 = function (uniformName, array) {
- this._engine.setArray4(this.getUniform(uniformName), array);
- return this;
- };
- Effect.prototype.setMatrices = function (uniformName, matrices) {
- this._engine.setMatrices(this.getUniform(uniformName), matrices);
- return this;
- };
- Effect.prototype.setMatrix = function (uniformName, matrix) {
- //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
- // return this;
- // this._cacheMatrix(uniformName, matrix);
- this._engine.setMatrix(this.getUniform(uniformName), matrix);
- return this;
- };
- Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
- this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
- return this;
- };
- Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
- this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
- return this;
- };
- Effect.prototype.setFloat = function (uniformName, value) {
- if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
- return this;
- this._valueCache[uniformName] = value;
- this._engine.setFloat(this.getUniform(uniformName), value);
- return this;
- };
- Effect.prototype.setBool = function (uniformName, bool) {
- if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
- return this;
- this._valueCache[uniformName] = bool;
- this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
- return this;
- };
- Effect.prototype.setVector2 = function (uniformName, vector2) {
- if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
- return this;
- this._cacheFloat2(uniformName, vector2.x, vector2.y);
- this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
- return this;
- };
- Effect.prototype.setFloat2 = function (uniformName, x, y) {
- if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
- return this;
- this._cacheFloat2(uniformName, x, y);
- this._engine.setFloat2(this.getUniform(uniformName), x, y);
- return this;
- };
- Effect.prototype.setVector3 = function (uniformName, vector3) {
- if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
- return this;
- this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
- this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
- return this;
- };
- Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
- if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
- return this;
- this._cacheFloat3(uniformName, x, y, z);
- this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
- return this;
- };
- Effect.prototype.setVector4 = function (uniformName, vector4) {
- if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector4.x && this._valueCache[uniformName][1] === vector4.y && this._valueCache[uniformName][2] === vector4.z && this._valueCache[uniformName][3] === vector4.w)
- return this;
- this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
- this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
- return this;
- };
- Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
- if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
- return this;
- this._cacheFloat4(uniformName, x, y, z, w);
- this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
- return this;
- };
- Effect.prototype.setColor3 = function (uniformName, color3) {
- if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
- return this;
- this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
- this._engine.setColor3(this.getUniform(uniformName), color3);
- return this;
- };
- Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
- if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b && this._valueCache[uniformName][3] === alpha)
- return this;
- this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
- this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
- return this;
- };
- // Statics
- Effect.ShadersStore = {};
- Effect.IncludesShadersStore = {};
- return Effect;
- })();
- BABYLON.Effect = Effect;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var maxSimultaneousLights = 4;
- var MaterialHelper = (function () {
- function MaterialHelper() {
- }
- MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines) {
- var lightIndex = 0;
- var needNormals = false;
- for (var index = 0; index < scene.lights.length; index++) {
- var light = scene.lights[index];
- if (!light.isEnabled()) {
- continue;
- }
- // Excluded check
- if (light._excludedMeshesIds.length > 0) {
- for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
- var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
- if (excludedMesh) {
- light.excludedMeshes.push(excludedMesh);
- }
- }
- light._excludedMeshesIds = [];
- }
- // Included check
- if (light._includedOnlyMeshesIds.length > 0) {
- for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
- var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
- if (includedOnlyMesh) {
- light.includedOnlyMeshes.push(includedOnlyMesh);
- }
- }
- light._includedOnlyMeshesIds = [];
- }
- if (!light.canAffectMesh(mesh)) {
- continue;
- }
- needNormals = true;
- defines["LIGHT" + lightIndex] = true;
- var type;
- if (light instanceof BABYLON.SpotLight) {
- type = "SPOTLIGHT" + lightIndex;
- }
- else if (light instanceof BABYLON.HemisphericLight) {
- type = "HEMILIGHT" + lightIndex;
- }
- else if (light instanceof BABYLON.PointLight) {
- type = "POINTLIGHT" + lightIndex;
- }
- else {
- type = "DIRLIGHT" + lightIndex;
- }
- defines[type] = true;
- // Specular
- if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
- defines["SPECULARTERM"] = true;
- }
- // Shadows
- if (scene.shadowsEnabled) {
- var shadowGenerator = light.getShadowGenerator();
- if (mesh && mesh.receiveShadows && shadowGenerator) {
- defines["SHADOW" + lightIndex] = true;
- defines["SHADOWS"] = true;
- if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
- defines["SHADOWVSM" + lightIndex] = true;
- }
- if (shadowGenerator.usePoissonSampling) {
- defines["SHADOWPCF" + lightIndex] = true;
- }
- }
- }
- lightIndex++;
- if (lightIndex === maxSimultaneousLights)
- break;
- }
- return needNormals;
- };
- MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks) {
- for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
- if (!defines["LIGHT" + lightIndex]) {
- continue;
- }
- if (lightIndex > 0) {
- fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
- }
- if (defines["SHADOW" + lightIndex]) {
- fallbacks.addFallback(0, "SHADOW" + lightIndex);
- }
- if (defines["SHADOWPCF" + lightIndex]) {
- fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
- }
- if (defines["SHADOWVSM" + lightIndex]) {
- fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
- }
- }
- };
- MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
- if (defines["NUM_BONE_INFLUENCERS"] > 0) {
- fallbacks.addCPUSkinningFallback(0, mesh);
- attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
- attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
- if (defines["NUM_BONE_INFLUENCERS"] > 4) {
- attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
- attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
- }
- }
- };
- MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
- if (defines["INSTANCES"]) {
- attribs.push("world0");
- attribs.push("world1");
- attribs.push("world2");
- attribs.push("world3");
- }
- };
- // Bindings
- MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
- var shadowGenerator = light.getShadowGenerator();
- if (mesh.receiveShadows && shadowGenerator) {
- if (!light.needCube()) {
- effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
- }
- else {
- if (!depthValuesAlreadySet) {
- depthValuesAlreadySet = true;
- effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
- }
- }
- effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
- effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
- }
- return depthValuesAlreadySet;
- };
- MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
- if (light instanceof BABYLON.PointLight) {
- // Point Light
- light.transferToEffect(effect, "vLightData" + lightIndex);
- }
- else if (light instanceof BABYLON.DirectionalLight) {
- // Directional Light
- light.transferToEffect(effect, "vLightData" + lightIndex);
- }
- else if (light instanceof BABYLON.SpotLight) {
- // Spot Light
- light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
- }
- else if (light instanceof BABYLON.HemisphericLight) {
- // Hemispheric Light
- light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
- }
- };
- MaterialHelper.BindLights = function (scene, mesh, effect, defines) {
- var lightIndex = 0;
- var depthValuesAlreadySet = false;
- for (var index = 0; index < scene.lights.length; index++) {
- var light = scene.lights[index];
- if (!light.isEnabled()) {
- continue;
- }
- if (!light.canAffectMesh(mesh)) {
- continue;
- }
- MaterialHelper.BindLightProperties(light, effect, lightIndex);
- light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
- effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
- if (defines["SPECULARTERM"]) {
- light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
- effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
- }
- // Shadows
- if (scene.shadowsEnabled) {
- depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
- }
- lightIndex++;
- if (lightIndex === maxSimultaneousLights)
- break;
- }
- };
- MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
- if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
- effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
- effect.setColor3("vFogColor", scene.fogColor);
- }
- };
- MaterialHelper.BindBonesParameters = function (mesh, effect) {
- if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
- effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
- }
- };
- MaterialHelper.BindLogDepth = function (defines, effect, scene) {
- if (defines["LOGARITHMICDEPTH"]) {
- effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
- }
- };
- MaterialHelper.BindClipPlane = function (effect, scene) {
- if (scene.clipPlane) {
- var clipPlane = scene.clipPlane;
- effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
- }
- };
- return MaterialHelper;
- })();
- BABYLON.MaterialHelper = MaterialHelper;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var FresnelParameters = (function () {
- function FresnelParameters() {
- this.isEnabled = true;
- this.leftColor = BABYLON.Color3.White();
- this.rightColor = BABYLON.Color3.Black();
- this.bias = 0;
- this.power = 1;
- }
- FresnelParameters.prototype.clone = function () {
- var newFresnelParameters = new FresnelParameters();
- BABYLON.Tools.DeepCopy(this, newFresnelParameters);
- return new FresnelParameters;
- };
- FresnelParameters.prototype.serialize = function () {
- var serializationObject = {};
- serializationObject.isEnabled = this.isEnabled;
- serializationObject.leftColor = this.leftColor;
- serializationObject.rightColor = this.rightColor;
- serializationObject.bias = this.bias;
- serializationObject.power = this.power;
- return serializationObject;
- };
- FresnelParameters.Parse = function (parsedFresnelParameters) {
- var fresnelParameters = new FresnelParameters();
- fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
- fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
- fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
- fresnelParameters.bias = parsedFresnelParameters.bias;
- fresnelParameters.power = parsedFresnelParameters.power || 1.0;
- return fresnelParameters;
- };
- return FresnelParameters;
- })();
- BABYLON.FresnelParameters = FresnelParameters;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var MaterialDefines = (function () {
- function MaterialDefines() {
- }
- MaterialDefines.prototype.isEqual = function (other) {
- for (var index = 0; index < this._keys.length; index++) {
- var prop = this._keys[index];
- if (this[prop] !== other[prop]) {
- return false;
- }
- }
- return true;
- };
- MaterialDefines.prototype.cloneTo = function (other) {
- for (var index = 0; index < this._keys.length; index++) {
- var prop = this._keys[index];
- other[prop] = this[prop];
- }
- };
- MaterialDefines.prototype.reset = function () {
- for (var index = 0; index < this._keys.length; index++) {
- var prop = this._keys[index];
- if (typeof (this[prop]) === "number") {
- this[prop] = 0;
- }
- else {
- this[prop] = false;
- }
- }
- };
- MaterialDefines.prototype.toString = function () {
- var result = "";
- for (var index = 0; index < this._keys.length; index++) {
- var prop = this._keys[index];
- if (typeof (this[prop]) === "number") {
- result += "#define " + prop + " " + this[prop] + "\n";
- }
- else if (this[prop]) {
- result += "#define " + prop + "\n";
- }
- }
- return result;
- };
- return MaterialDefines;
- })();
- BABYLON.MaterialDefines = MaterialDefines;
- var Material = (function () {
- function Material(name, scene, doNotAdd) {
- this.name = name;
- this.checkReadyOnEveryCall = false;
- this.checkReadyOnlyOnce = false;
- this.state = "";
- this.alpha = 1.0;
- this.backFaceCulling = true;
- this.sideOrientation = Material.CounterClockWiseSideOrientation;
- this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
- this.disableDepthWrite = false;
- this.fogEnabled = true;
- this.pointSize = 1.0;
- this.zOffset = 0;
- this._wasPreviouslyReady = false;
- this._fillMode = Material.TriangleFillMode;
- this.id = name;
- this._scene = scene;
- if (!doNotAdd) {
- scene.materials.push(this);
- }
- }
- Object.defineProperty(Material, "TriangleFillMode", {
- get: function () {
- return Material._TriangleFillMode;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Material, "WireFrameFillMode", {
- get: function () {
- return Material._WireFrameFillMode;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Material, "PointFillMode", {
- get: function () {
- return Material._PointFillMode;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Material, "ClockWiseSideOrientation", {
- get: function () {
- return Material._ClockWiseSideOrientation;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
- get: function () {
- return Material._CounterClockWiseSideOrientation;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Material.prototype, "wireframe", {
- get: function () {
- return this._fillMode === Material.WireFrameFillMode;
- },
- set: function (value) {
- this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Material.prototype, "pointsCloud", {
- get: function () {
- return this._fillMode === Material.PointFillMode;
- },
- set: function (value) {
- this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Material.prototype, "fillMode", {
- get: function () {
- return this._fillMode;
- },
- set: function (value) {
- this._fillMode = value;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
- * subclasses should override adding information pertainent to themselves
- */
- Material.prototype.toString = function (fullDetails) {
- var ret = "Name: " + this.name;
- if (fullDetails) {
- }
- return ret;
- };
- Object.defineProperty(Material.prototype, "isFrozen", {
- get: function () {
- return this.checkReadyOnlyOnce;
- },
- enumerable: true,
- configurable: true
- });
- Material.prototype.freeze = function () {
- this.checkReadyOnlyOnce = true;
- };
- Material.prototype.unfreeze = function () {
- this.checkReadyOnlyOnce = false;
- };
- Material.prototype.isReady = function (mesh, useInstances) {
- return true;
- };
- Material.prototype.getEffect = function () {
- return this._effect;
- };
- Material.prototype.getScene = function () {
- return this._scene;
- };
- Material.prototype.needAlphaBlending = function () {
- return (this.alpha < 1.0);
- };
- Material.prototype.needAlphaTesting = function () {
- return false;
- };
- Material.prototype.getAlphaTestTexture = function () {
- return null;
- };
- Material.prototype.trackCreation = function (onCompiled, onError) {
- };
- Material.prototype.markDirty = function () {
- this._wasPreviouslyReady = false;
- };
- Material.prototype._preBind = function () {
- var engine = this._scene.getEngine();
- engine.enableEffect(this._effect);
- engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
- };
- Material.prototype.bind = function (world, mesh) {
- this._scene._cachedMaterial = this;
- if (this.onBind) {
- this.onBind(this, mesh);
- }
- if (this.disableDepthWrite) {
- var engine = this._scene.getEngine();
- this._cachedDepthWriteState = engine.getDepthWrite();
- engine.setDepthWrite(false);
- }
- };
- Material.prototype.bindOnlyWorldMatrix = function (world) {
- };
- Material.prototype.unbind = function () {
- if (this.disableDepthWrite) {
- var engine = this._scene.getEngine();
- engine.setDepthWrite(this._cachedDepthWriteState);
- }
- };
- Material.prototype.clone = function (name) {
- return null;
- };
- Material.prototype.getBindedMeshes = function () {
- var result = new Array();
- for (var index = 0; index < this._scene.meshes.length; index++) {
- var mesh = this._scene.meshes[index];
- if (mesh.material === this) {
- result.push(mesh);
- }
- }
- return result;
- };
- Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
- // Animations
- this.getScene().stopAnimation(this);
- // Remove from scene
- var index = this._scene.materials.indexOf(this);
- if (index >= 0) {
- this._scene.materials.splice(index, 1);
- }
- // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
- if (forceDisposeEffect && this._effect) {
- this._scene.getEngine()._releaseEffect(this._effect);
- this._effect = null;
- }
- // Remove from meshes
- for (index = 0; index < this._scene.meshes.length; index++) {
- var mesh = this._scene.meshes[index];
- if (mesh.material === this) {
- mesh.material = null;
- }
- }
- // Callback
- if (this.onDispose) {
- this.onDispose();
- }
- };
- Material.prototype.serialize = function () {
- return BABYLON.SerializationHelper.Serialize(this);
- };
- Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
- var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
- multiMaterial.id = parsedMultiMaterial.id;
- BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
- for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
- var subMatId = parsedMultiMaterial.materials[matIndex];
- if (subMatId) {
- multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
- }
- else {
- multiMaterial.subMaterials.push(null);
- }
- }
- return multiMaterial;
- };
- Material.Parse = function (parsedMaterial, scene, rootUrl) {
- if (!parsedMaterial.customType) {
- return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
- }
- var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
- return materialType.Parse(parsedMaterial, scene, rootUrl);
- ;
- };
- Material._TriangleFillMode = 0;
- Material._WireFrameFillMode = 1;
- Material._PointFillMode = 2;
- Material._ClockWiseSideOrientation = 0;
- Material._CounterClockWiseSideOrientation = 1;
- __decorate([
- BABYLON.serialize()
- ], Material.prototype, "id", void 0);
- __decorate([
- BABYLON.serialize()
- ], Material.prototype, "checkReadyOnEveryCall", void 0);
- __decorate([
- BABYLON.serialize()
- ], Material.prototype, "checkReadyOnlyOnce", void 0);
- __decorate([
- BABYLON.serialize()
- ], Material.prototype, "state", void 0);
- __decorate([
- BABYLON.serialize()
- ], Material.prototype, "alpha", void 0);
- __decorate([
- BABYLON.serialize()
- ], Material.prototype, "backFaceCulling", void 0);
- __decorate([
- BABYLON.serialize()
- ], Material.prototype, "sideOrientation", void 0);
- __decorate([
- BABYLON.serialize()
- ], Material.prototype, "alphaMode", void 0);
- __decorate([
- BABYLON.serialize()
- ], Material.prototype, "disableDepthWrite", void 0);
- __decorate([
- BABYLON.serialize()
- ], Material.prototype, "fogEnabled", void 0);
- __decorate([
- BABYLON.serialize()
- ], Material.prototype, "pointSize", void 0);
- __decorate([
- BABYLON.serialize()
- ], Material.prototype, "zOffset", void 0);
- __decorate([
- BABYLON.serialize()
- ], Material.prototype, "wireframe", null);
- __decorate([
- BABYLON.serialize()
- ], Material.prototype, "pointsCloud", null);
- __decorate([
- BABYLON.serialize()
- ], Material.prototype, "fillMode", null);
- return Material;
- })();
- BABYLON.Material = Material;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var StandardMaterialDefines = (function (_super) {
- __extends(StandardMaterialDefines, _super);
- function StandardMaterialDefines() {
- _super.call(this);
- this.DIFFUSE = false;
- this.AMBIENT = false;
- this.OPACITY = false;
- this.OPACITYRGB = false;
- this.REFLECTION = false;
- this.EMISSIVE = false;
- this.SPECULAR = false;
- this.BUMP = false;
- this.PARALLAX = false;
- this.PARALLAXOCCLUSION = false;
- this.SPECULAROVERALPHA = false;
- this.CLIPPLANE = false;
- this.ALPHATEST = false;
- this.ALPHAFROMDIFFUSE = false;
- this.POINTSIZE = false;
- this.FOG = false;
- this.LIGHT0 = false;
- this.LIGHT1 = false;
- this.LIGHT2 = false;
- this.LIGHT3 = false;
- this.SPOTLIGHT0 = false;
- this.SPOTLIGHT1 = false;
- this.SPOTLIGHT2 = false;
- this.SPOTLIGHT3 = false;
- this.HEMILIGHT0 = false;
- this.HEMILIGHT1 = false;
- this.HEMILIGHT2 = false;
- this.HEMILIGHT3 = false;
- this.POINTLIGHT0 = false;
- this.POINTLIGHT1 = false;
- this.POINTLIGHT2 = false;
- this.POINTLIGHT3 = false;
- this.DIRLIGHT0 = false;
- this.DIRLIGHT1 = false;
- this.DIRLIGHT2 = false;
- this.DIRLIGHT3 = false;
- this.SPECULARTERM = false;
- this.SHADOW0 = false;
- this.SHADOW1 = false;
- this.SHADOW2 = false;
- this.SHADOW3 = false;
- this.SHADOWS = false;
- this.SHADOWVSM0 = false;
- this.SHADOWVSM1 = false;
- this.SHADOWVSM2 = false;
- this.SHADOWVSM3 = false;
- this.SHADOWPCF0 = false;
- this.SHADOWPCF1 = false;
- this.SHADOWPCF2 = false;
- this.SHADOWPCF3 = false;
- this.DIFFUSEFRESNEL = false;
- this.OPACITYFRESNEL = false;
- this.REFLECTIONFRESNEL = false;
- this.REFRACTIONFRESNEL = false;
- this.EMISSIVEFRESNEL = false;
- this.FRESNEL = false;
- this.NORMAL = false;
- this.UV1 = false;
- this.UV2 = false;
- this.VERTEXCOLOR = false;
- this.VERTEXALPHA = false;
- this.NUM_BONE_INFLUENCERS = 0;
- this.BonesPerMesh = 0;
- this.INSTANCES = false;
- this.GLOSSINESS = false;
- this.ROUGHNESS = false;
- this.EMISSIVEASILLUMINATION = false;
- this.LINKEMISSIVEWITHDIFFUSE = false;
- this.REFLECTIONFRESNELFROMSPECULAR = false;
- this.LIGHTMAP = false;
- this.USELIGHTMAPASSHADOWMAP = false;
- this.REFLECTIONMAP_3D = false;
- this.REFLECTIONMAP_SPHERICAL = false;
- this.REFLECTIONMAP_PLANAR = false;
- this.REFLECTIONMAP_CUBIC = false;
- this.REFLECTIONMAP_PROJECTION = false;
- this.REFLECTIONMAP_SKYBOX = false;
- this.REFLECTIONMAP_EXPLICIT = false;
- this.REFLECTIONMAP_EQUIRECTANGULAR = false;
- this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
- this.INVERTCUBICMAP = false;
- this.LOGARITHMICDEPTH = false;
- this.REFRACTION = false;
- this.REFRACTIONMAP_3D = false;
- this.REFLECTIONOVERALPHA = false;
- this._keys = Object.keys(this);
- }
- return StandardMaterialDefines;
- })(BABYLON.MaterialDefines);
- var StandardMaterial = (function (_super) {
- __extends(StandardMaterial, _super);
- function StandardMaterial(name, scene) {
- var _this = this;
- _super.call(this, name, scene);
- this.ambientColor = new BABYLON.Color3(0, 0, 0);
- this.diffuseColor = new BABYLON.Color3(1, 1, 1);
- this.specularColor = new BABYLON.Color3(1, 1, 1);
- this.emissiveColor = new BABYLON.Color3(0, 0, 0);
- this.specularPower = 64;
- this.useAlphaFromDiffuseTexture = false;
- this.useEmissiveAsIllumination = false;
- this.linkEmissiveWithDiffuse = false;
- this.useReflectionFresnelFromSpecular = false;
- this.useSpecularOverAlpha = false;
- this.useReflectionOverAlpha = false;
- this.disableLighting = false;
- this.useParallax = false;
- this.useParallaxOcclusion = false;
- this.parallaxScaleBias = 0.05;
- this.roughness = 0;
- this.indexOfRefraction = 0.98;
- this.invertRefractionY = true;
- this.useLightmapAsShadowmap = false;
- this.useGlossinessFromSpecularMapAlpha = false;
- this._renderTargets = new BABYLON.SmartArray(16);
- this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
- this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
- this._defines = new StandardMaterialDefines();
- this._cachedDefines = new StandardMaterialDefines();
- this._cachedDefines.BonesPerMesh = -1;
- this.getRenderTargetTextures = function () {
- _this._renderTargets.reset();
- if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
- _this._renderTargets.push(_this.reflectionTexture);
- }
- if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
- _this._renderTargets.push(_this.refractionTexture);
- }
- return _this._renderTargets;
- };
- }
- Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
- get: function () {
- return this._useLogarithmicDepth;
- },
- set: function (value) {
- this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
- },
- enumerable: true,
- configurable: true
- });
- StandardMaterial.prototype.needAlphaBlending = function () {
- return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
- };
- StandardMaterial.prototype.needAlphaTesting = function () {
- return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
- };
- StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
- return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
- };
- StandardMaterial.prototype.getAlphaTestTexture = function () {
- return this.diffuseTexture;
- };
- // Methods
- StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
- if (!mesh) {
- return true;
- }
- if (this._defines.INSTANCES !== useInstances) {
- return false;
- }
- if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
- return true;
- }
- return false;
- };
- StandardMaterial.prototype.isReady = function (mesh, useInstances) {
- if (this.isFrozen) {
- if (this._wasPreviouslyReady) {
- return true;
- }
- }
- var scene = this.getScene();
- if (!this.checkReadyOnEveryCall) {
- if (this._renderId === scene.getRenderId()) {
- if (this._checkCache(scene, mesh, useInstances)) {
- return true;
- }
- }
- }
- var engine = scene.getEngine();
- var needNormals = false;
- var needUVs = false;
- this._defines.reset();
- // Textures
- if (scene.texturesEnabled) {
- if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
- if (!this.diffuseTexture.isReady()) {
- return false;
- }
- else {
- needUVs = true;
- this._defines.DIFFUSE = true;
- }
- }
- if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
- if (!this.ambientTexture.isReady()) {
- return false;
- }
- else {
- needUVs = true;
- this._defines.AMBIENT = true;
- }
- }
- if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
- if (!this.opacityTexture.isReady()) {
- return false;
- }
- else {
- needUVs = true;
- this._defines.OPACITY = true;
- if (this.opacityTexture.getAlphaFromRGB) {
- this._defines.OPACITYRGB = true;
- }
- }
- }
- if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
- if (!this.reflectionTexture.isReady()) {
- return false;
- }
- else {
- needNormals = true;
- this._defines.REFLECTION = true;
- if (this.roughness > 0) {
- this._defines.ROUGHNESS = true;
- }
- if (this.useReflectionOverAlpha) {
- this._defines.REFLECTIONOVERALPHA = true;
- }
- if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
- this._defines.INVERTCUBICMAP = true;
- }
- this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
- switch (this.reflectionTexture.coordinatesMode) {
- case BABYLON.Texture.CUBIC_MODE:
- case BABYLON.Texture.INVCUBIC_MODE:
- this._defines.REFLECTIONMAP_CUBIC = true;
- break;
- case BABYLON.Texture.EXPLICIT_MODE:
- this._defines.REFLECTIONMAP_EXPLICIT = true;
- break;
- case BABYLON.Texture.PLANAR_MODE:
- this._defines.REFLECTIONMAP_PLANAR = true;
- break;
- case BABYLON.Texture.PROJECTION_MODE:
- this._defines.REFLECTIONMAP_PROJECTION = true;
- break;
- case BABYLON.Texture.SKYBOX_MODE:
- this._defines.REFLECTIONMAP_SKYBOX = true;
- break;
- case BABYLON.Texture.SPHERICAL_MODE:
- this._defines.REFLECTIONMAP_SPHERICAL = true;
- break;
- case BABYLON.Texture.EQUIRECTANGULAR_MODE:
- this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
- break;
- case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
- this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
- break;
- }
- }
- }
- if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
- if (!this.emissiveTexture.isReady()) {
- return false;
- }
- else {
- needUVs = true;
- this._defines.EMISSIVE = true;
- }
- }
- if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
- if (!this.lightmapTexture.isReady()) {
- return false;
- }
- else {
- needUVs = true;
- this._defines.LIGHTMAP = true;
- this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
- }
- }
- if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
- if (!this.specularTexture.isReady()) {
- return false;
- }
- else {
- needUVs = true;
- this._defines.SPECULAR = true;
- this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
- }
- }
- if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
- if (!this.bumpTexture.isReady()) {
- return false;
- }
- else {
- needUVs = true;
- this._defines.BUMP = true;
- if (this.useParallax) {
- this._defines.PARALLAX = true;
- if (this.useParallaxOcclusion) {
- this._defines.PARALLAXOCCLUSION = true;
- }
- }
- }
- }
- if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
- if (!this.refractionTexture.isReady()) {
- return false;
- }
- else {
- needUVs = true;
- this._defines.REFRACTION = true;
- this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
- }
- }
- }
- // Effect
- if (scene.clipPlane) {
- this._defines.CLIPPLANE = true;
- }
- if (engine.getAlphaTesting()) {
- this._defines.ALPHATEST = true;
- }
- if (this._shouldUseAlphaFromDiffuseTexture()) {
- this._defines.ALPHAFROMDIFFUSE = true;
- }
- if (this.useEmissiveAsIllumination) {
- this._defines.EMISSIVEASILLUMINATION = true;
- }
- if (this.linkEmissiveWithDiffuse) {
- this._defines.LINKEMISSIVEWITHDIFFUSE = true;
- }
- if (this.useLogarithmicDepth) {
- this._defines.LOGARITHMICDEPTH = true;
- }
- // Point size
- if (this.pointsCloud || scene.forcePointsCloud) {
- this._defines.POINTSIZE = true;
- }
- // Fog
- if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
- this._defines.FOG = true;
- }
- if (scene.lightsEnabled && !this.disableLighting) {
- needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines);
- }
- if (StandardMaterial.FresnelEnabled) {
- // Fresnel
- if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
- this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
- this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
- this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
- this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
- if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
- this._defines.DIFFUSEFRESNEL = true;
- }
- if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
- this._defines.OPACITYFRESNEL = true;
- }
- if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
- this._defines.REFLECTIONFRESNEL = true;
- if (this.useReflectionFresnelFromSpecular) {
- this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
- }
- }
- if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
- this._defines.REFRACTIONFRESNEL = true;
- }
- if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
- this._defines.EMISSIVEFRESNEL = true;
- }
- needNormals = true;
- this._defines.FRESNEL = true;
- }
- }
- if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
- this._defines.SPECULAROVERALPHA = true;
- }
- // Attribs
- if (mesh) {
- if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
- this._defines.NORMAL = true;
- }
- if (needUVs) {
- if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
- this._defines.UV1 = true;
- }
- if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
- this._defines.UV2 = true;
- }
- }
- if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
- this._defines.VERTEXCOLOR = true;
- if (mesh.hasVertexAlpha) {
- this._defines.VERTEXALPHA = true;
- }
- }
- if (mesh.useBones && mesh.computeBonesUsingShaders) {
- this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
- this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
- }
- // Instances
- if (useInstances) {
- this._defines.INSTANCES = true;
- }
- }
- // Get correct effect
- if (!this._defines.isEqual(this._cachedDefines)) {
- this._defines.cloneTo(this._cachedDefines);
- scene.resetCachedMaterial();
- // Fallbacks
- var fallbacks = new BABYLON.EffectFallbacks();
- if (this._defines.REFLECTION) {
- fallbacks.addFallback(0, "REFLECTION");
- }
- if (this._defines.SPECULAR) {
- fallbacks.addFallback(0, "SPECULAR");
- }
- if (this._defines.BUMP) {
- fallbacks.addFallback(0, "BUMP");
- }
- if (this._defines.PARALLAX) {
- fallbacks.addFallback(1, "PARALLAX");
- }
- if (this._defines.PARALLAXOCCLUSION) {
- fallbacks.addFallback(0, "PARALLAXOCCLUSION");
- }
- if (this._defines.SPECULAROVERALPHA) {
- fallbacks.addFallback(0, "SPECULAROVERALPHA");
- }
- if (this._defines.FOG) {
- fallbacks.addFallback(1, "FOG");
- }
- if (this._defines.POINTSIZE) {
- fallbacks.addFallback(0, "POINTSIZE");
- }
- if (this._defines.LOGARITHMICDEPTH) {
- fallbacks.addFallback(0, "LOGARITHMICDEPTH");
- }
- BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks);
- if (this._defines.SPECULARTERM) {
- fallbacks.addFallback(0, "SPECULARTERM");
- }
- if (this._defines.DIFFUSEFRESNEL) {
- fallbacks.addFallback(1, "DIFFUSEFRESNEL");
- }
- if (this._defines.OPACITYFRESNEL) {
- fallbacks.addFallback(2, "OPACITYFRESNEL");
- }
- if (this._defines.REFLECTIONFRESNEL) {
- fallbacks.addFallback(3, "REFLECTIONFRESNEL");
- }
- if (this._defines.EMISSIVEFRESNEL) {
- fallbacks.addFallback(4, "EMISSIVEFRESNEL");
- }
- if (this._defines.FRESNEL) {
- fallbacks.addFallback(4, "FRESNEL");
- }
- //Attributes
- var attribs = [BABYLON.VertexBuffer.PositionKind];
- if (this._defines.NORMAL) {
- attribs.push(BABYLON.VertexBuffer.NormalKind);
- }
- if (this._defines.UV1) {
- attribs.push(BABYLON.VertexBuffer.UVKind);
- }
- if (this._defines.UV2) {
- attribs.push(BABYLON.VertexBuffer.UV2Kind);
- }
- if (this._defines.VERTEXCOLOR) {
- attribs.push(BABYLON.VertexBuffer.ColorKind);
- }
- BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
- BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
- // Legacy browser patch
- var shaderName = "default";
- if (!scene.getEngine().getCaps().standardDerivatives) {
- shaderName = "legacydefault";
- }
- var join = this._defines.toString();
- this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
- "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
- "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
- "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
- "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
- "vFogInfos", "vFogColor", "pointSize",
- "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
- "mBones",
- "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
- "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
- "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
- "logarithmicDepthConstant"
- ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
- "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
- ], join, fallbacks, this.onCompiled, this.onError);
- }
- if (!this._effect.isReady()) {
- return false;
- }
- this._renderId = scene.getRenderId();
- this._wasPreviouslyReady = true;
- if (mesh) {
- if (!mesh._materialDefines) {
- mesh._materialDefines = new StandardMaterialDefines();
- }
- this._defines.cloneTo(mesh._materialDefines);
- }
- return true;
- };
- StandardMaterial.prototype.unbind = function () {
- if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
- this._effect.setTexture("reflection2DSampler", null);
- }
- if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
- this._effect.setTexture("refraction2DSampler", null);
- }
- _super.prototype.unbind.call(this);
- };
- StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
- this._effect.setMatrix("world", world);
- };
- StandardMaterial.prototype.bind = function (world, mesh) {
- var scene = this.getScene();
- // Matrices
- this.bindOnlyWorldMatrix(world);
- // Bones
- BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
- if (scene.getCachedMaterial() !== this) {
- this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
- if (StandardMaterial.FresnelEnabled) {
- // Fresnel
- if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
- this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
- this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
- }
- if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
- this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
- }
- if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
- this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
- this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
- }
- if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
- this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
- this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
- }
- if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
- this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
- this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
- }
- }
- // Textures
- if (scene.texturesEnabled) {
- if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
- this._effect.setTexture("diffuseSampler", this.diffuseTexture);
- this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
- this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
- }
- if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
- this._effect.setTexture("ambientSampler", this.ambientTexture);
- this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
- this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
- }
- if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
- this._effect.setTexture("opacitySampler", this.opacityTexture);
- this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
- this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
- }
- if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
- if (this.reflectionTexture.isCube) {
- this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
- }
- else {
- this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
- }
- this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
- this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
- }
- if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
- this._effect.setTexture("emissiveSampler", this.emissiveTexture);
- this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
- this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
- }
- if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
- this._effect.setTexture("lightmapSampler", this.lightmapTexture);
- this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
- this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
- }
- if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
- this._effect.setTexture("specularSampler", this.specularTexture);
- this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
- this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
- }
- if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
- this._effect.setTexture("bumpSampler", this.bumpTexture);
- this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
- this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
- }
- if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
- var depth = 1.0;
- if (this.refractionTexture.isCube) {
- this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
- }
- else {
- this._effect.setTexture("refraction2DSampler", this.refractionTexture);
- this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
- if (this.refractionTexture.depth) {
- depth = this.refractionTexture.depth;
- }
- }
- this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
- }
- }
- // Clip plane
- BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
- // Point size
- if (this.pointsCloud) {
- this._effect.setFloat("pointSize", this.pointSize);
- }
- // Colors
- scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
- this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
- this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
- if (this._defines.SPECULARTERM) {
- this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
- }
- this._effect.setColor3("vEmissiveColor", this.emissiveColor);
- }
- if (scene.getCachedMaterial() !== this || !this.isFrozen) {
- // Diffuse
- this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
- // Lights
- if (scene.lightsEnabled && !this.disableLighting) {
- BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines);
- }
- // View
- if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
- this._effect.setMatrix("view", scene.getViewMatrix());
- }
- // Fog
- BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
- // Log. depth
- BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
- }
- _super.prototype.bind.call(this, world, mesh);
- };
- StandardMaterial.prototype.getAnimatables = function () {
- var results = [];
- if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
- results.push(this.diffuseTexture);
- }
- if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
- results.push(this.ambientTexture);
- }
- if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
- results.push(this.opacityTexture);
- }
- if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
- results.push(this.reflectionTexture);
- }
- if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
- results.push(this.emissiveTexture);
- }
- if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
- results.push(this.specularTexture);
- }
- if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
- results.push(this.bumpTexture);
- }
- if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
- results.push(this.lightmapTexture);
- }
- if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
- results.push(this.refractionTexture);
- }
- return results;
- };
- StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
- if (forceDisposeTextures) {
- if (this.diffuseTexture) {
- this.diffuseTexture.dispose();
- }
- if (this.ambientTexture) {
- this.ambientTexture.dispose();
- }
- if (this.opacityTexture) {
- this.opacityTexture.dispose();
- }
- if (this.reflectionTexture) {
- this.reflectionTexture.dispose();
- }
- if (this.emissiveTexture) {
- this.emissiveTexture.dispose();
- }
- if (this.specularTexture) {
- this.specularTexture.dispose();
- }
- if (this.bumpTexture) {
- this.bumpTexture.dispose();
- }
- if (this.lightmapTexture) {
- this.lightmapTexture.dispose();
- }
- if (this.refractionTexture) {
- this.refractionTexture.dispose();
- }
- }
- _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
- };
- StandardMaterial.prototype.clone = function (name) {
- var _this = this;
- return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
- };
- StandardMaterial.prototype.serialize = function () {
- return BABYLON.SerializationHelper.Serialize(this);
- };
- // Statics
- StandardMaterial.Parse = function (source, scene, rootUrl) {
- return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
- };
- // Flags used to enable or disable a type of texture for all Standard Materials
- StandardMaterial.DiffuseTextureEnabled = true;
- StandardMaterial.AmbientTextureEnabled = true;
- StandardMaterial.OpacityTextureEnabled = true;
- StandardMaterial.ReflectionTextureEnabled = true;
- StandardMaterial.EmissiveTextureEnabled = true;
- StandardMaterial.SpecularTextureEnabled = true;
- StandardMaterial.BumpTextureEnabled = true;
- StandardMaterial.FresnelEnabled = true;
- StandardMaterial.LightmapTextureEnabled = true;
- StandardMaterial.RefractionTextureEnabled = true;
- __decorate([
- BABYLON.serializeAsTexture()
- ], StandardMaterial.prototype, "diffuseTexture", void 0);
- __decorate([
- BABYLON.serializeAsTexture()
- ], StandardMaterial.prototype, "ambientTexture", void 0);
- __decorate([
- BABYLON.serializeAsTexture()
- ], StandardMaterial.prototype, "opacityTexture", void 0);
- __decorate([
- BABYLON.serializeAsTexture()
- ], StandardMaterial.prototype, "reflectionTexture", void 0);
- __decorate([
- BABYLON.serializeAsTexture()
- ], StandardMaterial.prototype, "emissiveTexture", void 0);
- __decorate([
- BABYLON.serializeAsTexture()
- ], StandardMaterial.prototype, "specularTexture", void 0);
- __decorate([
- BABYLON.serializeAsTexture()
- ], StandardMaterial.prototype, "bumpTexture", void 0);
- __decorate([
- BABYLON.serializeAsTexture()
- ], StandardMaterial.prototype, "lightmapTexture", void 0);
- __decorate([
- BABYLON.serializeAsTexture()
- ], StandardMaterial.prototype, "refractionTexture", void 0);
- __decorate([
- BABYLON.serializeAsColor3("ambient")
- ], StandardMaterial.prototype, "ambientColor", void 0);
- __decorate([
- BABYLON.serializeAsColor3("diffuse")
- ], StandardMaterial.prototype, "diffuseColor", void 0);
- __decorate([
- BABYLON.serializeAsColor3("specular")
- ], StandardMaterial.prototype, "specularColor", void 0);
- __decorate([
- BABYLON.serializeAsColor3("emissive")
- ], StandardMaterial.prototype, "emissiveColor", void 0);
- __decorate([
- BABYLON.serialize()
- ], StandardMaterial.prototype, "specularPower", void 0);
- __decorate([
- BABYLON.serialize()
- ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
- __decorate([
- BABYLON.serialize()
- ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
- __decorate([
- BABYLON.serialize()
- ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
- __decorate([
- BABYLON.serialize()
- ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
- __decorate([
- BABYLON.serialize()
- ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
- __decorate([
- BABYLON.serialize()
- ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
- __decorate([
- BABYLON.serialize()
- ], StandardMaterial.prototype, "disableLighting", void 0);
- __decorate([
- BABYLON.serialize()
- ], StandardMaterial.prototype, "useParallax", void 0);
- __decorate([
- BABYLON.serialize()
- ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
- __decorate([
- BABYLON.serialize()
- ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
- __decorate([
- BABYLON.serialize()
- ], StandardMaterial.prototype, "roughness", void 0);
- __decorate([
- BABYLON.serialize()
- ], StandardMaterial.prototype, "indexOfRefraction", void 0);
- __decorate([
- BABYLON.serialize()
- ], StandardMaterial.prototype, "invertRefractionY", void 0);
- __decorate([
- BABYLON.serialize()
- ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
- __decorate([
- BABYLON.serializeAsFresnelParameters()
- ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
- __decorate([
- BABYLON.serializeAsFresnelParameters()
- ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
- __decorate([
- BABYLON.serializeAsFresnelParameters()
- ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
- __decorate([
- BABYLON.serializeAsFresnelParameters()
- ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
- __decorate([
- BABYLON.serializeAsFresnelParameters()
- ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
- __decorate([
- BABYLON.serialize()
- ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
- __decorate([
- BABYLON.serialize()
- ], StandardMaterial.prototype, "useLogarithmicDepth", null);
- return StandardMaterial;
- })(BABYLON.Material);
- BABYLON.StandardMaterial = StandardMaterial;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var MultiMaterial = (function (_super) {
- __extends(MultiMaterial, _super);
- function MultiMaterial(name, scene) {
- _super.call(this, name, scene, true);
- this.subMaterials = new Array();
- scene.multiMaterials.push(this);
- }
- // Properties
- MultiMaterial.prototype.getSubMaterial = function (index) {
- if (index < 0 || index >= this.subMaterials.length) {
- return this.getScene().defaultMaterial;
- }
- return this.subMaterials[index];
- };
- // Methods
- MultiMaterial.prototype.isReady = function (mesh) {
- for (var index = 0; index < this.subMaterials.length; index++) {
- var subMaterial = this.subMaterials[index];
- if (subMaterial) {
- if (!this.subMaterials[index].isReady(mesh)) {
- return false;
- }
- }
- }
- return true;
- };
- MultiMaterial.prototype.clone = function (name, cloneChildren) {
- var newMultiMaterial = new MultiMaterial(name, this.getScene());
- for (var index = 0; index < this.subMaterials.length; index++) {
- var subMaterial = null;
- if (cloneChildren) {
- subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
- }
- else {
- subMaterial = this.subMaterials[index];
- }
- newMultiMaterial.subMaterials.push(subMaterial);
- }
- return newMultiMaterial;
- };
- MultiMaterial.prototype.serialize = function () {
- var serializationObject = {};
- serializationObject.name = this.name;
- serializationObject.id = this.id;
- serializationObject.tags = BABYLON.Tags.GetTags(this);
- serializationObject.materials = [];
- for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
- var subMat = this.subMaterials[matIndex];
- if (subMat) {
- serializationObject.materials.push(subMat.id);
- }
- else {
- serializationObject.materials.push(null);
- }
- }
- return serializationObject;
- };
- return MultiMaterial;
- })(BABYLON.Material);
- BABYLON.MultiMaterial = MultiMaterial;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var SceneLoader = (function () {
- function SceneLoader() {
- }
- Object.defineProperty(SceneLoader, "NO_LOGGING", {
- get: function () {
- return 0;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
- get: function () {
- return 1;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
- get: function () {
- return 2;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
- get: function () {
- return 3;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
- get: function () {
- return SceneLoader._ForceFullSceneLoadingForIncremental;
- },
- set: function (value) {
- SceneLoader._ForceFullSceneLoadingForIncremental = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
- get: function () {
- return SceneLoader._ShowLoadingScreen;
- },
- set: function (value) {
- SceneLoader._ShowLoadingScreen = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(SceneLoader, "loggingLevel", {
- get: function () {
- return SceneLoader._loggingLevel;
- },
- set: function (value) {
- SceneLoader._loggingLevel = value;
- },
- enumerable: true,
- configurable: true
- });
- SceneLoader._getPluginForFilename = function (sceneFilename) {
- var dotPosition = sceneFilename.lastIndexOf(".");
- var queryStringPosition = sceneFilename.indexOf("?");
- if (queryStringPosition === -1) {
- queryStringPosition = sceneFilename.length;
- }
- var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
- for (var index = 0; index < this._registeredPlugins.length; index++) {
- var plugin = this._registeredPlugins[index];
- if (plugin.extensions.indexOf(extension) !== -1) {
- return plugin;
- }
- }
- return this._registeredPlugins[0];
- };
- // Public functions
- SceneLoader.GetPluginForExtension = function (extension) {
- for (var index = 0; index < this._registeredPlugins.length; index++) {
- var plugin = this._registeredPlugins[index];
- if (plugin.extensions.indexOf(extension) !== -1) {
- return plugin;
- }
- }
- return null;
- };
- SceneLoader.RegisterPlugin = function (plugin) {
- plugin.extensions = plugin.extensions.toLowerCase();
- SceneLoader._registeredPlugins.push(plugin);
- };
- SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
- if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
- BABYLON.Tools.Error("Wrong sceneFilename parameter");
- return;
- }
- if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
- BABYLON.Tools.Error("Wrong sceneFilename parameter");
- return;
- }
- var loadingToken = {};
- scene._addPendingData(loadingToken);
- var manifestChecked = function (success) {
- scene.database = database;
- var plugin = SceneLoader._getPluginForFilename(sceneFilename);
- var importMeshFromData = function (data) {
- var meshes = [];
- var particleSystems = [];
- var skeletons = [];
- try {
- if (plugin.importMesh) {
- var syncedPlugin = plugin;
- if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
- if (onerror) {
- onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
- }
- scene._removePendingData(loadingToken);
- return;
- }
- if (onsuccess) {
- scene.importedMeshesFiles.push(rootUrl + sceneFilename);
- onsuccess(meshes, particleSystems, skeletons);
- scene._removePendingData(loadingToken);
- }
- }
- else {
- var asyncedPlugin = plugin;
- asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
- if (onsuccess) {
- scene.importedMeshesFiles.push(rootUrl + sceneFilename);
- onsuccess(meshes, particleSystems, skeletons);
- scene._removePendingData(loadingToken);
- }
- }, function () {
- if (onerror) {
- onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
- }
- scene._removePendingData(loadingToken);
- });
- }
- }
- catch (e) {
- if (onerror) {
- onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
- }
- scene._removePendingData(loadingToken);
- }
- };
- if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
- // Direct load
- importMeshFromData(sceneFilename.substr(5));
- return;
- }
- BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
- importMeshFromData(data);
- }, progressCallBack, database);
- };
- if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
- // Checking if a manifest file has been set for this scene and if offline mode has been requested
- var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
- }
- else {
- // If the scene is a data stream or offline support is not enabled, it's a direct load
- manifestChecked(true);
- }
- };
- /**
- * Load a scene
- * @param rootUrl a string that defines the root url for scene and resources
- * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
- * @param engine is the instance of BABYLON.Engine to use to create the scene
- */
- SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
- SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
- };
- /**
- * Append a scene
- * @param rootUrl a string that defines the root url for scene and resources
- * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
- * @param scene is the instance of BABYLON.Scene to append to
- */
- SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
- if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
- BABYLON.Tools.Error("Wrong sceneFilename parameter");
- return;
- }
- var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
- var database;
- var loadingToken = {};
- scene._addPendingData(loadingToken);
- if (SceneLoader.ShowLoadingScreen) {
- scene.getEngine().displayLoadingUI();
- }
- var loadSceneFromData = function (data) {
- scene.database = database;
- if (plugin.load) {
- var syncedPlugin = plugin;
- if (!syncedPlugin.load(scene, data, rootUrl)) {
- if (onerror) {
- onerror(scene);
- }
- scene._removePendingData(loadingToken);
- scene.getEngine().hideLoadingUI();
- return;
- }
- if (onsuccess) {
- onsuccess(scene);
- }
- scene._removePendingData(loadingToken);
- }
- else {
- var asyncedPlugin = plugin;
- asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
- if (onsuccess) {
- onsuccess(scene);
- }
- }, function () {
- if (onerror) {
- onerror(scene);
- }
- scene._removePendingData(loadingToken);
- scene.getEngine().hideLoadingUI();
- });
- }
- if (SceneLoader.ShowLoadingScreen) {
- scene.executeWhenReady(function () {
- scene.getEngine().hideLoadingUI();
- });
- }
- };
- var manifestChecked = function (success) {
- BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
- };
- if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
- // Direct load
- loadSceneFromData(sceneFilename.substr(5));
- return;
- }
- if (rootUrl.indexOf("file:") === -1) {
- if (scene.getEngine().enableOfflineSupport) {
- // Checking if a manifest file has been set for this scene and if offline mode has been requested
- database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
- }
- else {
- manifestChecked(true);
- }
- }
- else {
- BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
- }
- };
- // Flags
- SceneLoader._ForceFullSceneLoadingForIncremental = false;
- SceneLoader._ShowLoadingScreen = true;
- SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
- // Members
- SceneLoader._registeredPlugins = new Array();
- return SceneLoader;
- })();
- BABYLON.SceneLoader = SceneLoader;
- ;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Internals;
- (function (Internals) {
- var parseMaterialById = function (id, parsedData, scene, rootUrl) {
- for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
- var parsedMaterial = parsedData.materials[index];
- if (parsedMaterial.id === id) {
- return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
- }
- }
- return null;
- };
- var isDescendantOf = function (mesh, names, hierarchyIds) {
- names = (names instanceof Array) ? names : [names];
- for (var i in names) {
- if (mesh.name === names[i]) {
- hierarchyIds.push(mesh.id);
- return true;
- }
- }
- if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
- hierarchyIds.push(mesh.id);
- return true;
- }
- return false;
- };
- var logOperation = function (operation, producer) {
- return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
- };
- BABYLON.SceneLoader.RegisterPlugin({
- extensions: ".babylon",
- importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
- // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
- // when SceneLoader.debugLogging = true (default), or exception encountered.
- // Everything stored in var log instead of writing separate lines to support only writing in exception,
- // and avoid problems with multiple concurrent .babylon loads.
- var log = "importMesh has failed JSON parse";
- try {
- var parsedData = JSON.parse(data);
- log = "";
- var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
- var loadedSkeletonsIds = [];
- var loadedMaterialsIds = [];
- var hierarchyIds = [];
- var index;
- var cache;
- for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
- var parsedMesh = parsedData.meshes[index];
- if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
- if (meshesNames instanceof Array) {
- // Remove found mesh name from list.
- delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
- }
- //Geometry?
- if (parsedMesh.geometryId) {
- //does the file contain geometries?
- if (parsedData.geometries) {
- //find the correct geometry and add it to the scene
- var found = false;
- ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
- if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
- return;
- }
- else {
- parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
- if (parsedGeometryData.id === parsedMesh.geometryId) {
- switch (geometryType) {
- case "boxes":
- BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
- break;
- case "spheres":
- BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
- break;
- case "cylinders":
- BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
- break;
- case "toruses":
- BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
- break;
- case "grounds":
- BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
- break;
- case "planes":
- BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
- break;
- case "torusKnots":
- BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
- break;
- case "vertexData":
- BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
- break;
- }
- found = true;
- }
- });
- }
- });
- if (!found) {
- BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
- }
- }
- }
- // Material ?
- if (parsedMesh.materialId) {
- var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
- if (!materialFound && parsedData.multiMaterials) {
- for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
- var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
- if (parsedMultiMaterial.id === parsedMesh.materialId) {
- for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
- var subMatId = parsedMultiMaterial.materials[matIndex];
- loadedMaterialsIds.push(subMatId);
- var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
- log += "\n\tMaterial " + mat.toString(fullDetails);
- }
- loadedMaterialsIds.push(parsedMultiMaterial.id);
- var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
- materialFound = true;
- log += "\n\tMulti-Material " + mmat.toString(fullDetails);
- break;
- }
- }
- }
- if (!materialFound) {
- loadedMaterialsIds.push(parsedMesh.materialId);
- var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
- if (!mat) {
- BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
- }
- else {
- log += "\n\tMaterial " + mat.toString(fullDetails);
- }
- }
- }
- // Skeleton ?
- if (parsedMesh.skeletonId > -1 && scene.skeletons) {
- var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
- if (!skeletonAlreadyLoaded) {
- for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
- var parsedSkeleton = parsedData.skeletons[skeletonIndex];
- if (parsedSkeleton.id === parsedMesh.skeletonId) {
- var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
- skeletons.push(skeleton);
- loadedSkeletonsIds.push(parsedSkeleton.id);
- log += "\n\tSkeleton " + skeleton.toString(fullDetails);
- }
- }
- }
- }
- var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
- meshes.push(mesh);
- log += "\n\tMesh " + mesh.toString(fullDetails);
- }
- }
- // Connecting parents
- var currentMesh;
- for (index = 0, cache = scene.meshes.length; index < cache; index++) {
- currentMesh = scene.meshes[index];
- if (currentMesh._waitingParentId) {
- currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
- currentMesh._waitingParentId = undefined;
- }
- }
- // freeze and compute world matrix application
- for (index = 0, cache = scene.meshes.length; index < cache; index++) {
- currentMesh = scene.meshes[index];
- if (currentMesh._waitingFreezeWorldMatrix) {
- currentMesh.freezeWorldMatrix();
- currentMesh._waitingFreezeWorldMatrix = undefined;
- }
- else {
- currentMesh.computeWorldMatrix(true);
- }
- }
- // Particles
- if (parsedData.particleSystems) {
- for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
- var parsedParticleSystem = parsedData.particleSystems[index];
- if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
- particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
- }
- }
- }
- return true;
- }
- catch (err) {
- BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + log);
- log = null;
- throw err;
- }
- finally {
- if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
- BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
- }
- }
- },
- load: function (scene, data, rootUrl) {
- // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
- // when SceneLoader.debugLogging = true (default), or exception encountered.
- // Everything stored in var log instead of writing separate lines to support only writing in exception,
- // and avoid problems with multiple concurrent .babylon loads.
- var log = "importScene has failed JSON parse";
- try {
- var parsedData = JSON.parse(data);
- log = "";
- var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
- // Scene
- scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
- scene.autoClear = parsedData.autoClear;
- scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
- scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
- if (parsedData.gravity) {
- scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
- }
- // Fog
- if (parsedData.fogMode && parsedData.fogMode !== 0) {
- scene.fogMode = parsedData.fogMode;
- scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
- scene.fogStart = parsedData.fogStart;
- scene.fogEnd = parsedData.fogEnd;
- scene.fogDensity = parsedData.fogDensity;
- log += "\tFog mode for scene: ";
- switch (scene.fogMode) {
- // getters not compiling, so using hardcoded
- case 1:
- log += "exp\n";
- break;
- case 2:
- log += "exp2\n";
- break;
- case 3:
- log += "linear\n";
- break;
- }
- }
- //Physics
- if (parsedData.physicsEnabled) {
- var physicsPlugin;
- if (parsedData.physicsEngine === "cannon") {
- physicsPlugin = new BABYLON.CannonJSPlugin();
- }
- else if (parsedData.physicsEngine === "oimo") {
- physicsPlugin = new BABYLON.OimoJSPlugin();
- }
- log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
- //else - default engine, which is currently oimo
- var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
- scene.enablePhysics(physicsGravity, physicsPlugin);
- }
- //collisions, if defined. otherwise, default is true
- if (parsedData.collisionsEnabled != undefined) {
- scene.collisionsEnabled = parsedData.collisionsEnabled;
- }
- scene.workerCollisions = !!parsedData.workerCollisions;
- var index;
- var cache;
- // Lights
- for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
- var parsedLight = parsedData.lights[index];
- var light = BABYLON.Light.Parse(parsedLight, scene);
- log += (index === 0 ? "\n\tLights:" : "");
- log += "\n\t\t" + light.toString(fullDetails);
- }
- // Animations
- if (parsedData.animations) {
- for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
- var parsedAnimation = parsedData.animations[index];
- var animation = BABYLON.Animation.Parse(parsedAnimation);
- scene.animations.push(animation);
- log += (index === 0 ? "\n\tAnimations:" : "");
- log += "\n\t\t" + animation.toString(fullDetails);
- }
- }
- // Materials
- if (parsedData.materials) {
- for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
- var parsedMaterial = parsedData.materials[index];
- var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
- log += (index === 0 ? "\n\tMaterials:" : "");
- log += "\n\t\t" + mat.toString(fullDetails);
- }
- }
- if (parsedData.multiMaterials) {
- for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
- var parsedMultiMaterial = parsedData.multiMaterials[index];
- var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
- log += (index === 0 ? "\n\tMultiMaterials:" : "");
- log += "\n\t\t" + mmat.toString(fullDetails);
- }
- }
- // Skeletons
- if (parsedData.skeletons) {
- for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
- var parsedSkeleton = parsedData.skeletons[index];
- var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
- log += (index === 0 ? "\n\tSkeletons:" : "");
- log += "\n\t\t" + skeleton.toString(fullDetails);
- }
- }
- // Geometries
- var geometries = parsedData.geometries;
- if (geometries) {
- // Boxes
- var boxes = geometries.boxes;
- if (boxes) {
- for (index = 0, cache = boxes.length; index < cache; index++) {
- var parsedBox = boxes[index];
- BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
- }
- }
- // Spheres
- var spheres = geometries.spheres;
- if (spheres) {
- for (index = 0, cache = spheres.length; index < cache; index++) {
- var parsedSphere = spheres[index];
- BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
- }
- }
- // Cylinders
- var cylinders = geometries.cylinders;
- if (cylinders) {
- for (index = 0, cache = cylinders.length; index < cache; index++) {
- var parsedCylinder = cylinders[index];
- BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
- }
- }
- // Toruses
- var toruses = geometries.toruses;
- if (toruses) {
- for (index = 0, cache = toruses.length; index < cache; index++) {
- var parsedTorus = toruses[index];
- BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
- }
- }
- // Grounds
- var grounds = geometries.grounds;
- if (grounds) {
- for (index = 0, cache = grounds.length; index < cache; index++) {
- var parsedGround = grounds[index];
- BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
- }
- }
- // Planes
- var planes = geometries.planes;
- if (planes) {
- for (index = 0, cache = planes.length; index < cache; index++) {
- var parsedPlane = planes[index];
- BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
- }
- }
- // TorusKnots
- var torusKnots = geometries.torusKnots;
- if (torusKnots) {
- for (index = 0, cache = torusKnots.length; index < cache; index++) {
- var parsedTorusKnot = torusKnots[index];
- BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
- }
- }
- // VertexData
- var vertexData = geometries.vertexData;
- if (vertexData) {
- for (index = 0, cache = vertexData.length; index < cache; index++) {
- var parsedVertexData = vertexData[index];
- BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
- }
- }
- }
- // Meshes
- for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
- var parsedMesh = parsedData.meshes[index];
- var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
- log += (index === 0 ? "\n\tMeshes:" : "");
- log += "\n\t\t" + mesh.toString(fullDetails);
- }
- // Cameras
- for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
- var parsedCamera = parsedData.cameras[index];
- var camera = BABYLON.Camera.Parse(parsedCamera, scene);
- log += (index === 0 ? "\n\tCameras:" : "");
- log += "\n\t\t" + camera.toString(fullDetails);
- }
- if (parsedData.activeCameraID) {
- scene.setActiveCameraByID(parsedData.activeCameraID);
- }
- // Browsing all the graph to connect the dots
- for (index = 0, cache = scene.cameras.length; index < cache; index++) {
- var camera = scene.cameras[index];
- if (camera._waitingParentId) {
- camera.parent = scene.getLastEntryByID(camera._waitingParentId);
- camera._waitingParentId = undefined;
- }
- }
- for (index = 0, cache = scene.lights.length; index < cache; index++) {
- var light = scene.lights[index];
- if (light._waitingParentId) {
- light.parent = scene.getLastEntryByID(light._waitingParentId);
- light._waitingParentId = undefined;
- }
- }
- // Sounds
- var loadedSounds = [];
- var loadedSound;
- if (BABYLON.AudioEngine && parsedData.sounds) {
- for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
- var parsedSound = parsedData.sounds[index];
- if (BABYLON.Engine.audioEngine.canUseWebAudio) {
- if (!parsedSound.url)
- parsedSound.url = parsedSound.name;
- if (!loadedSounds[parsedSound.url]) {
- loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
- loadedSounds[parsedSound.url] = loadedSound;
- }
- else {
- BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
- }
- }
- else {
- var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
- }
- }
- }
- loadedSounds = [];
- // Connect parents & children and parse actions
- for (index = 0, cache = scene.meshes.length; index < cache; index++) {
- var mesh = scene.meshes[index];
- if (mesh._waitingParentId) {
- mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
- mesh._waitingParentId = undefined;
- }
- if (mesh._waitingActions) {
- BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
- mesh._waitingActions = undefined;
- }
- }
- // freeze world matrix application
- for (index = 0, cache = scene.meshes.length; index < cache; index++) {
- var currentMesh = scene.meshes[index];
- if (currentMesh._waitingFreezeWorldMatrix) {
- currentMesh.freezeWorldMatrix();
- currentMesh._waitingFreezeWorldMatrix = undefined;
- }
- else {
- currentMesh.computeWorldMatrix(true);
- }
- }
- // Particles Systems
- if (parsedData.particleSystems) {
- for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
- var parsedParticleSystem = parsedData.particleSystems[index];
- BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
- }
- }
- // Lens flares
- if (parsedData.lensFlareSystems) {
- for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
- var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
- BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
- }
- }
- // Shadows
- if (parsedData.shadowGenerators) {
- for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
- var parsedShadowGenerator = parsedData.shadowGenerators[index];
- BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
- }
- }
- // Actions (scene)
- if (parsedData.actions) {
- BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
- }
- // Finish
- return true;
- }
- catch (err) {
- BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + log);
- log = null;
- throw err;
- }
- finally {
- if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
- BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
- }
- }
- }
- });
- })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var SpriteManager = (function () {
- function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
- this.name = name;
- this.cellSize = cellSize;
- this.sprites = new Array();
- this.renderingGroupId = 0;
- this.layerMask = 0x0FFFFFFF;
- this.fogEnabled = true;
- this.isPickable = false;
- this._vertexDeclaration = [4, 4, 4, 4];
- this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
- this._capacity = capacity;
- this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
- this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
- this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
- this._epsilon = epsilon === undefined ? 0.01 : epsilon;
- this._scene = scene;
- this._scene.spriteManagers.push(this);
- // VBO
- this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
- var indices = [];
- var index = 0;
- for (var count = 0; count < capacity; count++) {
- indices.push(index);
- indices.push(index + 1);
- indices.push(index + 2);
- indices.push(index);
- indices.push(index + 2);
- indices.push(index + 3);
- index += 4;
- }
- this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
- this._vertices = new Float32Array(capacity * this._vertexStrideSize);
- // Effects
- this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
- this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
- }
- Object.defineProperty(SpriteManager.prototype, "texture", {
- get: function () {
- return this._spriteTexture;
- },
- set: function (value) {
- this._spriteTexture = value;
- },
- enumerable: true,
- configurable: true
- });
- SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
- var arrayOffset = index * 16;
- if (offsetX === 0)
- offsetX = this._epsilon;
- else if (offsetX === 1)
- offsetX = 1 - this._epsilon;
- if (offsetY === 0)
- offsetY = this._epsilon;
- else if (offsetY === 1)
- offsetY = 1 - this._epsilon;
- this._vertices[arrayOffset] = sprite.position.x;
- this._vertices[arrayOffset + 1] = sprite.position.y;
- this._vertices[arrayOffset + 2] = sprite.position.z;
- this._vertices[arrayOffset + 3] = sprite.angle;
- this._vertices[arrayOffset + 4] = sprite.width;
- this._vertices[arrayOffset + 5] = sprite.height;
- this._vertices[arrayOffset + 6] = offsetX;
- this._vertices[arrayOffset + 7] = offsetY;
- this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
- this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
- var offset = (sprite.cellIndex / rowSize) >> 0;
- this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
- this._vertices[arrayOffset + 11] = offset;
- // Color
- this._vertices[arrayOffset + 12] = sprite.color.r;
- this._vertices[arrayOffset + 13] = sprite.color.g;
- this._vertices[arrayOffset + 14] = sprite.color.b;
- this._vertices[arrayOffset + 15] = sprite.color.a;
- };
- SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
- var count = Math.min(this._capacity, this.sprites.length);
- var min = BABYLON.Vector3.Zero();
- var max = BABYLON.Vector3.Zero();
- var distance = Number.MAX_VALUE;
- var currentSprite;
- var cameraSpacePosition = BABYLON.Vector3.Zero();
- var cameraView = camera.getViewMatrix();
- for (var index = 0; index < count; index++) {
- var sprite = this.sprites[index];
- if (!sprite) {
- continue;
- }
- if (predicate) {
- if (!predicate(sprite)) {
- continue;
- }
- }
- else if (!sprite.isPickable) {
- continue;
- }
- BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
- min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
- max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
- if (ray.intersectsBoxMinMax(min, max)) {
- var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
- if (distance > currentDistance) {
- distance = currentDistance;
- currentSprite = sprite;
- if (fastCheck) {
- break;
- }
- }
- }
- }
- if (currentSprite) {
- var result = new BABYLON.PickingInfo();
- result.hit = true;
- result.pickedSprite = currentSprite;
- result.distance = distance;
- return result;
- }
- return null;
- };
- SpriteManager.prototype.render = function () {
- // Check
- if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
- return;
- var engine = this._scene.getEngine();
- var baseSize = this._spriteTexture.getBaseSize();
- // Sprites
- var deltaTime = engine.getDeltaTime();
- var max = Math.min(this._capacity, this.sprites.length);
- var rowSize = baseSize.width / this.cellSize;
- var offset = 0;
- for (var index = 0; index < max; index++) {
- var sprite = this.sprites[index];
- if (!sprite) {
- continue;
- }
- sprite._animate(deltaTime);
- this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
- this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
- this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
- this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
- }
- engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
- // Render
- var effect = this._effectBase;
- if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
- effect = this._effectFog;
- }
- engine.enableEffect(effect);
- var viewMatrix = this._scene.getViewMatrix();
- effect.setTexture("diffuseSampler", this._spriteTexture);
- effect.setMatrix("view", viewMatrix);
- effect.setMatrix("projection", this._scene.getProjectionMatrix());
- effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
- // Fog
- if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
- effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
- effect.setColor3("vFogColor", this._scene.fogColor);
- }
- // VBOs
- engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
- // Draw order
- engine.setDepthFunctionToLessOrEqual();
- effect.setBool("alphaTest", true);
- engine.setColorWrite(false);
- engine.draw(true, 0, max * 6);
- engine.setColorWrite(true);
- effect.setBool("alphaTest", false);
- engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
- engine.draw(true, 0, max * 6);
- engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
- };
- SpriteManager.prototype.dispose = function () {
- if (this._vertexBuffer) {
- this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
- this._vertexBuffer = null;
- }
- if (this._indexBuffer) {
- this._scene.getEngine()._releaseBuffer(this._indexBuffer);
- this._indexBuffer = null;
- }
- if (this._spriteTexture) {
- this._spriteTexture.dispose();
- this._spriteTexture = null;
- }
- // Remove from scene
- var index = this._scene.spriteManagers.indexOf(this);
- this._scene.spriteManagers.splice(index, 1);
- // Callback
- if (this.onDispose) {
- this.onDispose();
- }
- };
- return SpriteManager;
- })();
- BABYLON.SpriteManager = SpriteManager;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Sprite = (function () {
- function Sprite(name, manager) {
- this.name = name;
- this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
- this.width = 1.0;
- this.height = 1.0;
- this.angle = 0;
- this.cellIndex = 0;
- this.invertU = 0;
- this.invertV = 0;
- this.animations = new Array();
- this.isPickable = false;
- this._animationStarted = false;
- this._loopAnimation = false;
- this._fromIndex = 0;
- this._toIndex = 0;
- this._delay = 0;
- this._direction = 1;
- this._frameCount = 0;
- this._time = 0;
- this._manager = manager;
- this._manager.sprites.push(this);
- this.position = BABYLON.Vector3.Zero();
- }
- Object.defineProperty(Sprite.prototype, "size", {
- get: function () {
- return this.width;
- },
- set: function (value) {
- this.width = value;
- this.height = value;
- },
- enumerable: true,
- configurable: true
- });
- Sprite.prototype.playAnimation = function (from, to, loop, delay) {
- this._fromIndex = from;
- this._toIndex = to;
- this._loopAnimation = loop;
- this._delay = delay;
- this._animationStarted = true;
- this._direction = from < to ? 1 : -1;
- this.cellIndex = from;
- this._time = 0;
- };
- Sprite.prototype.stopAnimation = function () {
- this._animationStarted = false;
- };
- Sprite.prototype._animate = function (deltaTime) {
- if (!this._animationStarted)
- return;
- this._time += deltaTime;
- if (this._time > this._delay) {
- this._time = this._time % this._delay;
- this.cellIndex += this._direction;
- if (this.cellIndex == this._toIndex) {
- if (this._loopAnimation) {
- this.cellIndex = this._fromIndex;
- }
- else {
- this._animationStarted = false;
- if (this.disposeWhenFinishedAnimating) {
- this.dispose();
- }
- }
- }
- }
- };
- Sprite.prototype.dispose = function () {
- for (var i = 0; i < this._manager.sprites.length; i++) {
- if (this._manager.sprites[i] == this) {
- this._manager.sprites.splice(i, 1);
- }
- }
- };
- return Sprite;
- })();
- BABYLON.Sprite = Sprite;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Layer = (function () {
- function Layer(name, imgUrl, scene, isBackground, color) {
- this.name = name;
- this.scale = new BABYLON.Vector2(1, 1);
- this.offset = new BABYLON.Vector2(0, 0);
- this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
- this._vertexDeclaration = [2];
- this._vertexStrideSize = 2 * 4;
- this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
- this.isBackground = isBackground === undefined ? true : isBackground;
- this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
- this._scene = scene;
- this._scene.layers.push(this);
- // VBO
- var vertices = [];
- vertices.push(1, 1);
- vertices.push(-1, 1);
- vertices.push(-1, -1);
- vertices.push(1, -1);
- this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
- // Indices
- var indices = [];
- indices.push(0);
- indices.push(1);
- indices.push(2);
- indices.push(0);
- indices.push(2);
- indices.push(3);
- this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
- // Effects
- this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
- this._alphaTestEffect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
- }
- Layer.prototype.render = function () {
- var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
- // Check
- if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
- return;
- var engine = this._scene.getEngine();
- if (this.onBeforeRender) {
- this.onBeforeRender();
- }
- // Render
- engine.enableEffect(currentEffect);
- engine.setState(false);
- // Texture
- currentEffect.setTexture("textureSampler", this.texture);
- currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
- // Color
- currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
- // Scale / offset
- currentEffect.setVector2("offset", this.offset);
- currentEffect.setVector2("scale", this.scale);
- // VBOs
- engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, currentEffect);
- // Draw order
- if (!this._alphaTestEffect) {
- engine.setAlphaMode(this.alphaBlendingMode);
- engine.draw(true, 0, 6);
- engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
- }
- else {
- engine.draw(true, 0, 6);
- }
- if (this.onAfterRender) {
- this.onAfterRender();
- }
- };
- Layer.prototype.dispose = function () {
- if (this._vertexBuffer) {
- this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
- this._vertexBuffer = null;
- }
- if (this._indexBuffer) {
- this._scene.getEngine()._releaseBuffer(this._indexBuffer);
- this._indexBuffer = null;
- }
- if (this.texture) {
- this.texture.dispose();
- this.texture = null;
- }
- // Remove from scene
- var index = this._scene.layers.indexOf(this);
- this._scene.layers.splice(index, 1);
- // Callback
- if (this.onDispose) {
- this.onDispose();
- }
- };
- return Layer;
- })();
- BABYLON.Layer = Layer;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Particle = (function () {
- function Particle() {
- this.position = BABYLON.Vector3.Zero();
- this.direction = BABYLON.Vector3.Zero();
- this.color = new BABYLON.Color4(0, 0, 0, 0);
- this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
- this.lifeTime = 1.0;
- this.age = 0;
- this.size = 0;
- this.angle = 0;
- this.angularSpeed = 0;
- }
- Particle.prototype.copyTo = function (other) {
- other.position.copyFrom(this.position);
- other.direction.copyFrom(this.direction);
- other.color.copyFrom(this.color);
- other.colorStep.copyFrom(this.colorStep);
- other.lifeTime = this.lifeTime;
- other.age = this.age;
- other.size = this.size;
- other.angle = this.angle;
- other.angularSpeed = this.angularSpeed;
- };
- return Particle;
- })();
- BABYLON.Particle = Particle;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var randomNumber = function (min, max) {
- if (min === max) {
- return (min);
- }
- var random = Math.random();
- return ((random * (max - min)) + min);
- };
- var ParticleSystem = (function () {
- function ParticleSystem(name, capacity, scene, customEffect) {
- var _this = this;
- this.name = name;
- // Members
- this.animations = [];
- this.renderingGroupId = 0;
- this.emitter = null;
- this.emitRate = 10;
- this.manualEmitCount = -1;
- this.updateSpeed = 0.01;
- this.targetStopDuration = 0;
- this.disposeOnStop = false;
- this.minEmitPower = 1;
- this.maxEmitPower = 1;
- this.minLifeTime = 1;
- this.maxLifeTime = 1;
- this.minSize = 1;
- this.maxSize = 1;
- this.minAngularSpeed = 0;
- this.maxAngularSpeed = 0;
- this.layerMask = 0x0FFFFFFF;
- this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
- this.forceDepthWrite = false;
- this.gravity = BABYLON.Vector3.Zero();
- this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
- this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
- this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
- this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
- this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
- this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
- this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
- this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
- this.particles = new Array();
- this._vertexDeclaration = [3, 4, 4];
- this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
- this._stockParticles = new Array();
- this._newPartsExcess = 0;
- this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
- this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
- this._scaledDirection = BABYLON.Vector3.Zero();
- this._scaledGravity = BABYLON.Vector3.Zero();
- this._currentRenderId = -1;
- this._started = false;
- this._stopped = false;
- this._actualFrame = 0;
- this.id = name;
- this._capacity = capacity;
- this._scene = scene;
- this._customEffect = customEffect;
- scene.particleSystems.push(this);
- // VBO
- this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
- var indices = [];
- var index = 0;
- for (var count = 0; count < capacity; count++) {
- indices.push(index);
- indices.push(index + 1);
- indices.push(index + 2);
- indices.push(index);
- indices.push(index + 2);
- indices.push(index + 3);
- index += 4;
- }
- this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
- this._vertices = new Float32Array(capacity * this._vertexStrideSize);
- // Default behaviors
- this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
- var randX = randomNumber(_this.direction1.x, _this.direction2.x);
- var randY = randomNumber(_this.direction1.y, _this.direction2.y);
- var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
- BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
- };
- this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
- var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
- var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
- var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
- BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
- };
- this.updateFunction = function (particles) {
- for (var index = 0; index < particles.length; index++) {
- var particle = particles[index];
- particle.age += _this._scaledUpdateSpeed;
- if (particle.age >= particle.lifeTime) {
- _this.recycleParticle(particle);
- index--;
- continue;
- }
- else {
- particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
- particle.color.addInPlace(_this._scaledColorStep);
- if (particle.color.a < 0)
- particle.color.a = 0;
- particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
- particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
- particle.position.addInPlace(_this._scaledDirection);
- _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
- particle.direction.addInPlace(_this._scaledGravity);
- }
- }
- };
- }
- ParticleSystem.prototype.recycleParticle = function (particle) {
- var lastParticle = this.particles.pop();
- if (lastParticle !== particle) {
- lastParticle.copyTo(particle);
- this._stockParticles.push(lastParticle);
- }
- };
- ParticleSystem.prototype.getCapacity = function () {
- return this._capacity;
- };
- ParticleSystem.prototype.isAlive = function () {
- return this._alive;
- };
- ParticleSystem.prototype.isStarted = function () {
- return this._started;
- };
- ParticleSystem.prototype.start = function () {
- this._started = true;
- this._stopped = false;
- this._actualFrame = 0;
- };
- ParticleSystem.prototype.stop = function () {
- this._stopped = true;
- };
- ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
- var offset = index * 11;
- this._vertices[offset] = particle.position.x;
- this._vertices[offset + 1] = particle.position.y;
- this._vertices[offset + 2] = particle.position.z;
- this._vertices[offset + 3] = particle.color.r;
- this._vertices[offset + 4] = particle.color.g;
- this._vertices[offset + 5] = particle.color.b;
- this._vertices[offset + 6] = particle.color.a;
- this._vertices[offset + 7] = particle.angle;
- this._vertices[offset + 8] = particle.size;
- this._vertices[offset + 9] = offsetX;
- this._vertices[offset + 10] = offsetY;
- };
- ParticleSystem.prototype._update = function (newParticles) {
- // Update current
- this._alive = this.particles.length > 0;
- this.updateFunction(this.particles);
- // Add new ones
- var worldMatrix;
- if (this.emitter.position) {
- worldMatrix = this.emitter.getWorldMatrix();
- }
- else {
- worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
- }
- var particle;
- for (var index = 0; index < newParticles; index++) {
- if (this.particles.length === this._capacity) {
- break;
- }
- if (this._stockParticles.length !== 0) {
- particle = this._stockParticles.pop();
- particle.age = 0;
- }
- else {
- particle = new BABYLON.Particle();
- }
- this.particles.push(particle);
- var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
- this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
- particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
- particle.size = randomNumber(this.minSize, this.maxSize);
- particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
- this.startPositionFunction(worldMatrix, particle.position, particle);
- var step = randomNumber(0, 1.0);
- BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
- this.colorDead.subtractToRef(particle.color, this._colorDiff);
- this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
- }
- };
- ParticleSystem.prototype._getEffect = function () {
- if (this._customEffect) {
- return this._customEffect;
- }
- ;
- var defines = [];
- if (this._scene.clipPlane) {
- defines.push("#define CLIPPLANE");
- }
- // Effect
- var join = defines.join("\n");
- if (this._cachedDefines !== join) {
- this._cachedDefines = join;
- this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
- }
- return this._effect;
- };
- ParticleSystem.prototype.animate = function () {
- if (!this._started)
- return;
- var effect = this._getEffect();
- // Check
- if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
- return;
- if (this._currentRenderId === this._scene.getRenderId()) {
- return;
- }
- this._currentRenderId = this._scene.getRenderId();
- this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
- // determine the number of particles we need to create
- var newParticles;
- if (this.manualEmitCount > -1) {
- newParticles = this.manualEmitCount;
- this._newPartsExcess = 0;
- this.manualEmitCount = 0;
- }
- else {
- newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
- this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
- }
- if (this._newPartsExcess > 1.0) {
- newParticles += this._newPartsExcess >> 0;
- this._newPartsExcess -= this._newPartsExcess >> 0;
- }
- this._alive = false;
- if (!this._stopped) {
- this._actualFrame += this._scaledUpdateSpeed;
- if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
- this.stop();
- }
- else {
- newParticles = 0;
- }
- this._update(newParticles);
- // Stopped?
- if (this._stopped) {
- if (!this._alive) {
- this._started = false;
- if (this.disposeOnStop) {
- this._scene._toBeDisposed.push(this);
- }
- }
- }
- // Update VBO
- var offset = 0;
- for (var index = 0; index < this.particles.length; index++) {
- var particle = this.particles[index];
- this._appendParticleVertex(offset++, particle, 0, 0);
- this._appendParticleVertex(offset++, particle, 1, 0);
- this._appendParticleVertex(offset++, particle, 1, 1);
- this._appendParticleVertex(offset++, particle, 0, 1);
- }
- var engine = this._scene.getEngine();
- engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
- };
- ParticleSystem.prototype.render = function () {
- var effect = this._getEffect();
- // Check
- if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
- return 0;
- var engine = this._scene.getEngine();
- // Render
- engine.enableEffect(effect);
- engine.setState(false);
- var viewMatrix = this._scene.getViewMatrix();
- effect.setTexture("diffuseSampler", this.particleTexture);
- effect.setMatrix("view", viewMatrix);
- effect.setMatrix("projection", this._scene.getProjectionMatrix());
- effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
- if (this._scene.clipPlane) {
- var clipPlane = this._scene.clipPlane;
- var invView = viewMatrix.clone();
- invView.invert();
- effect.setMatrix("invView", invView);
- effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
- }
- // VBOs
- engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
- // Draw order
- if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
- engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
- }
- else {
- engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
- }
- if (this.forceDepthWrite) {
- engine.setDepthWrite(true);
- }
- engine.draw(true, 0, this.particles.length * 6);
- engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
- return this.particles.length;
- };
- ParticleSystem.prototype.dispose = function () {
- if (this._vertexBuffer) {
- this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
- this._vertexBuffer = null;
- }
- if (this._indexBuffer) {
- this._scene.getEngine()._releaseBuffer(this._indexBuffer);
- this._indexBuffer = null;
- }
- if (this.particleTexture) {
- this.particleTexture.dispose();
- this.particleTexture = null;
- }
- // Remove from scene
- var index = this._scene.particleSystems.indexOf(this);
- this._scene.particleSystems.splice(index, 1);
- // Callback
- if (this.onDispose) {
- this.onDispose();
- }
- };
- // Clone
- ParticleSystem.prototype.clone = function (name, newEmitter) {
- var result = new ParticleSystem(name, this._capacity, this._scene);
- BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
- if (newEmitter === undefined) {
- newEmitter = this.emitter;
- }
- result.emitter = newEmitter;
- if (this.particleTexture) {
- result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
- }
- result.start();
- return result;
- };
- ParticleSystem.prototype.serialize = function () {
- var serializationObject = {};
- serializationObject.name = this.name;
- serializationObject.id = this.id;
- // Emitter
- if (this.emitter.position) {
- serializationObject.emitterId = this.emitter.id;
- }
- else {
- serializationObject.emitter = this.emitter.asArray();
- }
- serializationObject.capacity = this.getCapacity();
- if (this.particleTexture) {
- serializationObject.textureName = this.particleTexture.name;
- }
- // Animations
- BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
- // Particle system
- serializationObject.minAngularSpeed = this.minAngularSpeed;
- serializationObject.maxAngularSpeed = this.maxAngularSpeed;
- serializationObject.minSize = this.minSize;
- serializationObject.maxSize = this.maxSize;
- serializationObject.minEmitPower = this.minEmitPower;
- serializationObject.maxEmitPower = this.maxEmitPower;
- serializationObject.minLifeTime = this.minLifeTime;
- serializationObject.maxLifeTime = this.maxLifeTime;
- serializationObject.emitRate = this.emitRate;
- serializationObject.minEmitBox = this.minEmitBox.asArray();
- serializationObject.maxEmitBox = this.maxEmitBox.asArray();
- serializationObject.gravity = this.gravity.asArray();
- serializationObject.direction1 = this.direction1.asArray();
- serializationObject.direction2 = this.direction2.asArray();
- serializationObject.color1 = this.color1.asArray();
- serializationObject.color2 = this.color2.asArray();
- serializationObject.colorDead = this.colorDead.asArray();
- serializationObject.updateSpeed = this.updateSpeed;
- serializationObject.targetStopDuration = this.targetStopDuration;
- serializationObject.textureMask = this.textureMask.asArray();
- serializationObject.blendMode = this.blendMode;
- return serializationObject;
- };
- ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
- var name = parsedParticleSystem.name;
- var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
- if (parsedParticleSystem.id) {
- particleSystem.id = parsedParticleSystem.id;
- }
- // Texture
- if (parsedParticleSystem.textureName) {
- particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
- particleSystem.particleTexture.name = parsedParticleSystem.textureName;
- }
- // Emitter
- if (parsedParticleSystem.emitterId) {
- particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
- }
- else {
- particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
- }
- // Animations
- if (parsedParticleSystem.animations) {
- for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
- var parsedAnimation = parsedParticleSystem.animations[animationIndex];
- particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
- }
- }
- if (parsedParticleSystem.autoAnimate) {
- scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
- }
- // Particle system
- particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
- particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
- particleSystem.minSize = parsedParticleSystem.minSize;
- particleSystem.maxSize = parsedParticleSystem.maxSize;
- particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
- particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
- particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
- particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
- particleSystem.emitRate = parsedParticleSystem.emitRate;
- particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
- particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
- particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
- particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
- particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
- particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
- particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
- particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
- particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
- particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
- particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
- particleSystem.blendMode = parsedParticleSystem.blendMode;
- if (!parsedParticleSystem.preventAutoStart) {
- particleSystem.start();
- }
- return particleSystem;
- };
- // Statics
- ParticleSystem.BLENDMODE_ONEONE = 0;
- ParticleSystem.BLENDMODE_STANDARD = 1;
- return ParticleSystem;
- })();
- BABYLON.ParticleSystem = ParticleSystem;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var AnimationRange = (function () {
- function AnimationRange(name, from, to) {
- this.name = name;
- this.from = from;
- this.to = to;
- }
- AnimationRange.prototype.clone = function () {
- return new AnimationRange(this.name, this.from, this.to);
- };
- return AnimationRange;
- })();
- BABYLON.AnimationRange = AnimationRange;
- /**
- * Composed of a frame, and an action function
- */
- var AnimationEvent = (function () {
- function AnimationEvent(frame, action, onlyOnce) {
- this.frame = frame;
- this.action = action;
- this.onlyOnce = onlyOnce;
- this.isDone = false;
- }
- return AnimationEvent;
- })();
- BABYLON.AnimationEvent = AnimationEvent;
- var PathCursor = (function () {
- function PathCursor(path) {
- this.path = path;
- this._onchange = new Array();
- this.value = 0;
- this.animations = new Array();
- }
- PathCursor.prototype.getPoint = function () {
- var point = this.path.getPointAtLengthPosition(this.value);
- return new BABYLON.Vector3(point.x, 0, point.y);
- };
- PathCursor.prototype.moveAhead = function (step) {
- if (step === void 0) { step = 0.002; }
- this.move(step);
- return this;
- };
- PathCursor.prototype.moveBack = function (step) {
- if (step === void 0) { step = 0.002; }
- this.move(-step);
- return this;
- };
- PathCursor.prototype.move = function (step) {
- if (Math.abs(step) > 1) {
- throw "step size should be less than 1.";
- }
- this.value += step;
- this.ensureLimits();
- this.raiseOnChange();
- return this;
- };
- PathCursor.prototype.ensureLimits = function () {
- while (this.value > 1) {
- this.value -= 1;
- }
- while (this.value < 0) {
- this.value += 1;
- }
- return this;
- };
- // used by animation engine
- PathCursor.prototype.markAsDirty = function (propertyName) {
- this.ensureLimits();
- this.raiseOnChange();
- return this;
- };
- PathCursor.prototype.raiseOnChange = function () {
- var _this = this;
- this._onchange.forEach(function (f) { return f(_this); });
- return this;
- };
- PathCursor.prototype.onchange = function (f) {
- this._onchange.push(f);
- return this;
- };
- return PathCursor;
- })();
- BABYLON.PathCursor = PathCursor;
- var Animation = (function () {
- function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
- this.name = name;
- this.targetProperty = targetProperty;
- this.framePerSecond = framePerSecond;
- this.dataType = dataType;
- this.loopMode = loopMode;
- this.enableBlending = enableBlending;
- this._offsetsCache = {};
- this._highLimitsCache = {};
- this._stopped = false;
- this._blendingFactor = 0;
- // The set of event that will be linked to this animation
- this._events = new Array();
- this.allowMatricesInterpolation = false;
- this.blendingSpeed = 0.01;
- this._ranges = {};
- this.targetPropertyPath = targetProperty.split(".");
- this.dataType = dataType;
- this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
- }
- Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
- var dataType = undefined;
- if (!isNaN(parseFloat(from)) && isFinite(from)) {
- dataType = Animation.ANIMATIONTYPE_FLOAT;
- }
- else if (from instanceof BABYLON.Quaternion) {
- dataType = Animation.ANIMATIONTYPE_QUATERNION;
- }
- else if (from instanceof BABYLON.Vector3) {
- dataType = Animation.ANIMATIONTYPE_VECTOR3;
- }
- else if (from instanceof BABYLON.Vector2) {
- dataType = Animation.ANIMATIONTYPE_VECTOR2;
- }
- else if (from instanceof BABYLON.Color3) {
- dataType = Animation.ANIMATIONTYPE_COLOR3;
- }
- if (dataType == undefined) {
- return null;
- }
- var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
- var keys = [];
- keys.push({ frame: 0, value: from });
- keys.push({ frame: totalFrame, value: to });
- animation.setKeys(keys);
- if (easingFunction !== undefined) {
- animation.setEasingFunction(easingFunction);
- }
- return animation;
- };
- Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
- var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
- return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
- };
- Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
- var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
- node.animations.push(animation);
- return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
- };
- // Methods
- /**
- * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
- */
- Animation.prototype.toString = function (fullDetails) {
- var ret = "Name: " + this.name + ", property: " + this.targetProperty;
- ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
- ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
- ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
- if (fullDetails) {
- ret += ", Ranges: {";
- var first = true;
- for (var name in this._ranges) {
- if (!first) {
- ret + ", ";
- first = false;
- }
- ret += name;
- }
- ret += "}";
- }
- return ret;
- };
- /**
- * Add an event to this animation.
- */
- Animation.prototype.addEvent = function (event) {
- this._events.push(event);
- };
- /**
- * Remove all events found at the given frame
- * @param frame
- */
- Animation.prototype.removeEvents = function (frame) {
- for (var index = 0; index < this._events.length; index++) {
- if (this._events[index].frame === frame) {
- this._events.splice(index, 1);
- index--;
- }
- }
- };
- Animation.prototype.createRange = function (name, from, to) {
- // check name not already in use; could happen for bones after serialized
- if (!this._ranges[name]) {
- this._ranges[name] = new AnimationRange(name, from, to);
- }
- };
- Animation.prototype.deleteRange = function (name, deleteFrames) {
- if (deleteFrames === void 0) { deleteFrames = true; }
- if (this._ranges[name]) {
- if (deleteFrames) {
- var from = this._ranges[name].from;
- var to = this._ranges[name].to;
- // this loop MUST go high to low for multiple splices to work
- for (var key = this._keys.length - 1; key >= 0; key--) {
- if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
- this._keys.splice(key, 1);
- }
- }
- }
- this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
- }
- };
- Animation.prototype.getRange = function (name) {
- return this._ranges[name];
- };
- Animation.prototype.reset = function () {
- this._offsetsCache = {};
- this._highLimitsCache = {};
- this.currentFrame = 0;
- this._blendingFactor = 0;
- this._originalBlendValue = null;
- };
- Animation.prototype.isStopped = function () {
- return this._stopped;
- };
- Animation.prototype.getKeys = function () {
- return this._keys;
- };
- Animation.prototype.getHighestFrame = function () {
- var ret = 0;
- for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
- if (ret < this._keys[key].frame) {
- ret = this._keys[key].frame;
- }
- }
- return ret;
- };
- Animation.prototype.getEasingFunction = function () {
- return this._easingFunction;
- };
- Animation.prototype.setEasingFunction = function (easingFunction) {
- this._easingFunction = easingFunction;
- };
- Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
- return startValue + (endValue - startValue) * gradient;
- };
- Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
- return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
- };
- Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
- return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
- };
- Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
- return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
- };
- Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
- return BABYLON.Color3.Lerp(startValue, endValue, gradient);
- };
- Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
- return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
- };
- Animation.prototype.clone = function () {
- var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
- if (this._keys) {
- clone.setKeys(this._keys);
- }
- if (this._ranges) {
- clone._ranges = {};
- for (var name in this._ranges) {
- clone._ranges[name] = this._ranges[name].clone();
- }
- }
- return clone;
- };
- Animation.prototype.setKeys = function (values) {
- this._keys = values.slice(0);
- this._offsetsCache = {};
- this._highLimitsCache = {};
- };
- Animation.prototype._getKeyValue = function (value) {
- if (typeof value === "function") {
- return value();
- }
- return value;
- };
- Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
- if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
- return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
- }
- this.currentFrame = currentFrame;
- // Try to get a hash to find the right key
- 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));
- if (this._keys[startKey].frame >= currentFrame) {
- while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
- startKey--;
- }
- }
- for (var key = startKey; key < this._keys.length; key++) {
- if (this._keys[key + 1].frame >= currentFrame) {
- var startValue = this._getKeyValue(this._keys[key].value);
- var endValue = this._getKeyValue(this._keys[key + 1].value);
- // gradient : percent of currentFrame between the frame inf and the frame sup
- var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
- // check for easingFunction and correction of gradient
- if (this._easingFunction != null) {
- gradient = this._easingFunction.ease(gradient);
- }
- switch (this.dataType) {
- // Float
- case Animation.ANIMATIONTYPE_FLOAT:
- switch (loopMode) {
- case Animation.ANIMATIONLOOPMODE_CYCLE:
- case Animation.ANIMATIONLOOPMODE_CONSTANT:
- return this.floatInterpolateFunction(startValue, endValue, gradient);
- case Animation.ANIMATIONLOOPMODE_RELATIVE:
- return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
- }
- break;
- // Quaternion
- case Animation.ANIMATIONTYPE_QUATERNION:
- var quaternion = null;
- switch (loopMode) {
- case Animation.ANIMATIONLOOPMODE_CYCLE:
- case Animation.ANIMATIONLOOPMODE_CONSTANT:
- quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
- break;
- case Animation.ANIMATIONLOOPMODE_RELATIVE:
- quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
- break;
- }
- return quaternion;
- // Vector3
- case Animation.ANIMATIONTYPE_VECTOR3:
- switch (loopMode) {
- case Animation.ANIMATIONLOOPMODE_CYCLE:
- case Animation.ANIMATIONLOOPMODE_CONSTANT:
- return this.vector3InterpolateFunction(startValue, endValue, gradient);
- case Animation.ANIMATIONLOOPMODE_RELATIVE:
- return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
- }
- // Vector2
- case Animation.ANIMATIONTYPE_VECTOR2:
- switch (loopMode) {
- case Animation.ANIMATIONLOOPMODE_CYCLE:
- case Animation.ANIMATIONLOOPMODE_CONSTANT:
- return this.vector2InterpolateFunction(startValue, endValue, gradient);
- case Animation.ANIMATIONLOOPMODE_RELATIVE:
- return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
- }
- // Color3
- case Animation.ANIMATIONTYPE_COLOR3:
- switch (loopMode) {
- case Animation.ANIMATIONLOOPMODE_CYCLE:
- case Animation.ANIMATIONLOOPMODE_CONSTANT:
- return this.color3InterpolateFunction(startValue, endValue, gradient);
- case Animation.ANIMATIONLOOPMODE_RELATIVE:
- return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
- }
- // Matrix
- case Animation.ANIMATIONTYPE_MATRIX:
- switch (loopMode) {
- case Animation.ANIMATIONLOOPMODE_CYCLE:
- case Animation.ANIMATIONLOOPMODE_CONSTANT:
- if (this.allowMatricesInterpolation) {
- return this.matrixInterpolateFunction(startValue, endValue, gradient);
- }
- case Animation.ANIMATIONLOOPMODE_RELATIVE:
- return startValue;
- }
- default:
- break;
- }
- break;
- }
- }
- return this._getKeyValue(this._keys[this._keys.length - 1].value);
- };
- Animation.prototype.setValue = function (currentValue, blend) {
- if (blend === void 0) { blend = false; }
- // Set value
- var path;
- var destination;
- if (this.targetPropertyPath.length > 1) {
- var property = this._target[this.targetPropertyPath[0]];
- for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
- property = property[this.targetPropertyPath[index]];
- }
- path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
- destination = property;
- }
- else {
- path = this.targetPropertyPath[0];
- destination = this._target;
- }
- // Blending
- if (this.enableBlending && this._blendingFactor <= 1.0) {
- if (!this._originalBlendValue) {
- this._originalBlendValue = destination[path];
- }
- if (this._originalBlendValue.prototype) {
- if (this._originalBlendValue.prototype.Lerp) {
- destination[path] = this._originalBlendValue.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
- }
- else {
- destination[path] = currentValue;
- }
- }
- else {
- destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
- }
- this._blendingFactor += this.blendingSpeed;
- }
- else {
- destination[path] = currentValue;
- }
- if (this._target.markAsDirty) {
- this._target.markAsDirty(this.targetProperty);
- }
- };
- Animation.prototype.goToFrame = function (frame) {
- if (frame < this._keys[0].frame) {
- frame = this._keys[0].frame;
- }
- else if (frame > this._keys[this._keys.length - 1].frame) {
- frame = this._keys[this._keys.length - 1].frame;
- }
- var currentValue = this._interpolate(frame, 0, this.loopMode);
- this.setValue(currentValue);
- };
- Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
- if (blend === void 0) { blend = false; }
- if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
- this._stopped = true;
- return false;
- }
- var returnValue = true;
- // Adding a start key at frame 0 if missing
- if (this._keys[0].frame !== 0) {
- var newKey = { frame: 0, value: this._keys[0].value };
- this._keys.splice(0, 0, newKey);
- }
- // Check limits
- if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
- from = this._keys[0].frame;
- }
- if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
- to = this._keys[this._keys.length - 1].frame;
- }
- // Compute ratio
- var range = to - from;
- var offsetValue;
- // ratio represents the frame delta between from and to
- var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
- var highLimitValue = 0;
- if (ratio > range && !loop) {
- returnValue = false;
- highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
- }
- else {
- // Get max value if required
- if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
- var keyOffset = to.toString() + from.toString();
- if (!this._offsetsCache[keyOffset]) {
- var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
- var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
- switch (this.dataType) {
- // Float
- case Animation.ANIMATIONTYPE_FLOAT:
- this._offsetsCache[keyOffset] = toValue - fromValue;
- break;
- // Quaternion
- case Animation.ANIMATIONTYPE_QUATERNION:
- this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
- break;
- // Vector3
- case Animation.ANIMATIONTYPE_VECTOR3:
- this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
- // Vector2
- case Animation.ANIMATIONTYPE_VECTOR2:
- this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
- // Color3
- case Animation.ANIMATIONTYPE_COLOR3:
- this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
- default:
- break;
- }
- this._highLimitsCache[keyOffset] = toValue;
- }
- highLimitValue = this._highLimitsCache[keyOffset];
- offsetValue = this._offsetsCache[keyOffset];
- }
- }
- if (offsetValue === undefined) {
- switch (this.dataType) {
- // Float
- case Animation.ANIMATIONTYPE_FLOAT:
- offsetValue = 0;
- break;
- // Quaternion
- case Animation.ANIMATIONTYPE_QUATERNION:
- offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
- break;
- // Vector3
- case Animation.ANIMATIONTYPE_VECTOR3:
- offsetValue = BABYLON.Vector3.Zero();
- break;
- // Vector2
- case Animation.ANIMATIONTYPE_VECTOR2:
- offsetValue = BABYLON.Vector2.Zero();
- break;
- // Color3
- case Animation.ANIMATIONTYPE_COLOR3:
- offsetValue = BABYLON.Color3.Black();
- }
- }
- // Compute value
- var repeatCount = (ratio / range) >> 0;
- var currentFrame = returnValue ? from + ratio % range : to;
- var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
- // Set value
- this.setValue(currentValue);
- // Check events
- for (var index = 0; index < this._events.length; index++) {
- if (currentFrame >= this._events[index].frame) {
- var event = this._events[index];
- if (!event.isDone) {
- // If event should be done only once, remove it.
- if (event.onlyOnce) {
- this._events.splice(index, 1);
- index--;
- }
- event.isDone = true;
- event.action();
- } // Don't do anything if the event has already be done.
- }
- else if (this._events[index].isDone && !this._events[index].onlyOnce) {
- // reset event, the animation is looping
- this._events[index].isDone = false;
- }
- }
- if (!returnValue) {
- this._stopped = true;
- }
- return returnValue;
- };
- Animation.prototype.serialize = function () {
- var serializationObject = {};
- serializationObject.name = this.name;
- serializationObject.property = this.targetProperty;
- serializationObject.framePerSecond = this.framePerSecond;
- serializationObject.dataType = this.dataType;
- serializationObject.loopBehavior = this.loopMode;
- var dataType = this.dataType;
- serializationObject.keys = [];
- var keys = this.getKeys();
- for (var index = 0; index < keys.length; index++) {
- var animationKey = keys[index];
- var key = {};
- key.frame = animationKey.frame;
- switch (dataType) {
- case Animation.ANIMATIONTYPE_FLOAT:
- key.values = [animationKey.value];
- break;
- case Animation.ANIMATIONTYPE_QUATERNION:
- case Animation.ANIMATIONTYPE_MATRIX:
- case Animation.ANIMATIONTYPE_VECTOR3:
- case Animation.ANIMATIONTYPE_COLOR3:
- key.values = animationKey.value.asArray();
- break;
- }
- serializationObject.keys.push(key);
- }
- serializationObject.ranges = [];
- for (var name in this._ranges) {
- var range = {};
- range.name = name;
- range.from = this._ranges[name].from;
- range.to = this._ranges[name].to;
- serializationObject.ranges.push(range);
- }
- return serializationObject;
- };
- Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
- get: function () {
- return Animation._ANIMATIONTYPE_FLOAT;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
- get: function () {
- return Animation._ANIMATIONTYPE_VECTOR3;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
- get: function () {
- return Animation._ANIMATIONTYPE_VECTOR2;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
- get: function () {
- return Animation._ANIMATIONTYPE_QUATERNION;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
- get: function () {
- return Animation._ANIMATIONTYPE_MATRIX;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
- get: function () {
- return Animation._ANIMATIONTYPE_COLOR3;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
- get: function () {
- return Animation._ANIMATIONLOOPMODE_RELATIVE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
- get: function () {
- return Animation._ANIMATIONLOOPMODE_CYCLE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
- get: function () {
- return Animation._ANIMATIONLOOPMODE_CONSTANT;
- },
- enumerable: true,
- configurable: true
- });
- Animation.Parse = function (parsedAnimation) {
- var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
- var dataType = parsedAnimation.dataType;
- var keys = [];
- for (var index = 0; index < parsedAnimation.keys.length; index++) {
- var key = parsedAnimation.keys[index];
- var data;
- switch (dataType) {
- case Animation.ANIMATIONTYPE_FLOAT:
- data = key.values[0];
- break;
- case Animation.ANIMATIONTYPE_QUATERNION:
- data = BABYLON.Quaternion.FromArray(key.values);
- break;
- case Animation.ANIMATIONTYPE_MATRIX:
- data = BABYLON.Matrix.FromArray(key.values);
- break;
- case Animation.ANIMATIONTYPE_COLOR3:
- data = BABYLON.Color3.FromArray(key.values);
- break;
- case Animation.ANIMATIONTYPE_VECTOR3:
- default:
- data = BABYLON.Vector3.FromArray(key.values);
- break;
- }
- keys.push({
- frame: key.frame,
- value: data
- });
- }
- animation.setKeys(keys);
- if (parsedAnimation.ranges) {
- for (var index = 0; index < parsedAnimation.ranges.length; index++) {
- data = parsedAnimation.ranges[index];
- animation.createRange(data.name, data.from, data.to);
- }
- }
- return animation;
- };
- Animation.AppendSerializedAnimations = function (source, destination) {
- if (source.animations) {
- destination.animations = [];
- for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
- var animation = source.animations[animationIndex];
- destination.animations.push(animation.serialize());
- }
- }
- };
- // Statics
- Animation._ANIMATIONTYPE_FLOAT = 0;
- Animation._ANIMATIONTYPE_VECTOR3 = 1;
- Animation._ANIMATIONTYPE_QUATERNION = 2;
- Animation._ANIMATIONTYPE_MATRIX = 3;
- Animation._ANIMATIONTYPE_COLOR3 = 4;
- Animation._ANIMATIONTYPE_VECTOR2 = 5;
- Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
- Animation._ANIMATIONLOOPMODE_CYCLE = 1;
- Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
- return Animation;
- })();
- BABYLON.Animation = Animation;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Animatable = (function () {
- function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
- if (fromFrame === void 0) { fromFrame = 0; }
- if (toFrame === void 0) { toFrame = 100; }
- if (loopAnimation === void 0) { loopAnimation = false; }
- if (speedRatio === void 0) { speedRatio = 1.0; }
- this.target = target;
- this.fromFrame = fromFrame;
- this.toFrame = toFrame;
- this.loopAnimation = loopAnimation;
- this.speedRatio = speedRatio;
- this.onAnimationEnd = onAnimationEnd;
- this._animations = new Array();
- this._paused = false;
- this.animationStarted = false;
- if (animations) {
- this.appendAnimations(target, animations);
- }
- this._scene = scene;
- scene._activeAnimatables.push(this);
- }
- // Methods
- Animatable.prototype.getAnimations = function () {
- return this._animations;
- };
- Animatable.prototype.appendAnimations = function (target, animations) {
- for (var index = 0; index < animations.length; index++) {
- var animation = animations[index];
- animation._target = target;
- this._animations.push(animation);
- }
- };
- Animatable.prototype.getAnimationByTargetProperty = function (property) {
- var animations = this._animations;
- for (var index = 0; index < animations.length; index++) {
- if (animations[index].targetProperty === property) {
- return animations[index];
- }
- }
- return null;
- };
- Animatable.prototype.reset = function () {
- var animations = this._animations;
- for (var index = 0; index < animations.length; index++) {
- animations[index].reset();
- }
- this._localDelayOffset = null;
- this._pausedDelay = null;
- };
- Animatable.prototype.enableBlending = function (blendingSpeed) {
- var animations = this._animations;
- for (var index = 0; index < animations.length; index++) {
- animations[index].enableBlending = true;
- animations[index].blendingSpeed = blendingSpeed;
- }
- };
- Animatable.prototype.disableBlending = function () {
- var animations = this._animations;
- for (var index = 0; index < animations.length; index++) {
- animations[index].enableBlending = false;
- }
- };
- Animatable.prototype.goToFrame = function (frame) {
- var animations = this._animations;
- for (var index = 0; index < animations.length; index++) {
- animations[index].goToFrame(frame);
- }
- };
- Animatable.prototype.pause = function () {
- if (this._paused) {
- return;
- }
- this._paused = true;
- };
- Animatable.prototype.restart = function () {
- this._paused = false;
- };
- Animatable.prototype.stop = function () {
- var index = this._scene._activeAnimatables.indexOf(this);
- if (index > -1) {
- this._scene._activeAnimatables.splice(index, 1);
- var animations = this._animations;
- for (var index = 0; index < animations.length; index++) {
- animations[index].reset();
- }
- if (this.onAnimationEnd) {
- this.onAnimationEnd();
- }
- }
- };
- Animatable.prototype._animate = function (delay) {
- if (this._paused) {
- this.animationStarted = false;
- if (!this._pausedDelay) {
- this._pausedDelay = delay;
- }
- return true;
- }
- if (!this._localDelayOffset) {
- this._localDelayOffset = delay;
- }
- else if (this._pausedDelay) {
- this._localDelayOffset += delay - this._pausedDelay;
- this._pausedDelay = null;
- }
- // Animating
- var running = false;
- var animations = this._animations;
- var index;
- for (index = 0; index < animations.length; index++) {
- var animation = animations[index];
- var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
- running = running || isRunning;
- }
- this.animationStarted = running;
- if (!running) {
- // Remove from active animatables
- index = this._scene._activeAnimatables.indexOf(this);
- this._scene._activeAnimatables.splice(index, 1);
- }
- if (!running && this.onAnimationEnd) {
- this.onAnimationEnd();
- this.onAnimationEnd = null;
- }
- return running;
- };
- return Animatable;
- })();
- BABYLON.Animatable = Animatable;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var EasingFunction = (function () {
- function EasingFunction() {
- // Properties
- this._easingMode = EasingFunction.EASINGMODE_EASEIN;
- }
- Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
- get: function () {
- return EasingFunction._EASINGMODE_EASEIN;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
- get: function () {
- return EasingFunction._EASINGMODE_EASEOUT;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
- get: function () {
- return EasingFunction._EASINGMODE_EASEINOUT;
- },
- enumerable: true,
- configurable: true
- });
- EasingFunction.prototype.setEasingMode = function (easingMode) {
- var n = Math.min(Math.max(easingMode, 0), 2);
- this._easingMode = n;
- };
- EasingFunction.prototype.getEasingMode = function () {
- return this._easingMode;
- };
- EasingFunction.prototype.easeInCore = function (gradient) {
- throw new Error('You must implement this method');
- };
- EasingFunction.prototype.ease = function (gradient) {
- switch (this._easingMode) {
- case EasingFunction.EASINGMODE_EASEIN:
- return this.easeInCore(gradient);
- case EasingFunction.EASINGMODE_EASEOUT:
- return (1 - this.easeInCore(1 - gradient));
- }
- if (gradient >= 0.5) {
- return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
- }
- return (this.easeInCore(gradient * 2) * 0.5);
- };
- //Statics
- EasingFunction._EASINGMODE_EASEIN = 0;
- EasingFunction._EASINGMODE_EASEOUT = 1;
- EasingFunction._EASINGMODE_EASEINOUT = 2;
- return EasingFunction;
- })();
- BABYLON.EasingFunction = EasingFunction;
- var CircleEase = (function (_super) {
- __extends(CircleEase, _super);
- function CircleEase() {
- _super.apply(this, arguments);
- }
- CircleEase.prototype.easeInCore = function (gradient) {
- gradient = Math.max(0, Math.min(1, gradient));
- return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
- };
- return CircleEase;
- })(EasingFunction);
- BABYLON.CircleEase = CircleEase;
- var BackEase = (function (_super) {
- __extends(BackEase, _super);
- function BackEase(amplitude) {
- if (amplitude === void 0) { amplitude = 1; }
- _super.call(this);
- this.amplitude = amplitude;
- }
- BackEase.prototype.easeInCore = function (gradient) {
- var num = Math.max(0, this.amplitude);
- return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
- };
- return BackEase;
- })(EasingFunction);
- BABYLON.BackEase = BackEase;
- var BounceEase = (function (_super) {
- __extends(BounceEase, _super);
- function BounceEase(bounces, bounciness) {
- if (bounces === void 0) { bounces = 3; }
- if (bounciness === void 0) { bounciness = 2; }
- _super.call(this);
- this.bounces = bounces;
- this.bounciness = bounciness;
- }
- BounceEase.prototype.easeInCore = function (gradient) {
- var y = Math.max(0.0, this.bounces);
- var bounciness = this.bounciness;
- if (bounciness <= 1.0) {
- bounciness = 1.001;
- }
- var num9 = Math.pow(bounciness, y);
- var num5 = 1.0 - bounciness;
- var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
- var num15 = gradient * num4;
- var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
- var num3 = Math.floor(num65);
- var num13 = num3 + 1.0;
- var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
- var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
- var num7 = (num8 + num12) * 0.5;
- var num6 = gradient - num7;
- var num2 = num7 - num8;
- return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
- };
- return BounceEase;
- })(EasingFunction);
- BABYLON.BounceEase = BounceEase;
- var CubicEase = (function (_super) {
- __extends(CubicEase, _super);
- function CubicEase() {
- _super.apply(this, arguments);
- }
- CubicEase.prototype.easeInCore = function (gradient) {
- return (gradient * gradient * gradient);
- };
- return CubicEase;
- })(EasingFunction);
- BABYLON.CubicEase = CubicEase;
- var ElasticEase = (function (_super) {
- __extends(ElasticEase, _super);
- function ElasticEase(oscillations, springiness) {
- if (oscillations === void 0) { oscillations = 3; }
- if (springiness === void 0) { springiness = 3; }
- _super.call(this);
- this.oscillations = oscillations;
- this.springiness = springiness;
- }
- ElasticEase.prototype.easeInCore = function (gradient) {
- var num2;
- var num3 = Math.max(0.0, this.oscillations);
- var num = Math.max(0.0, this.springiness);
- if (num == 0) {
- num2 = gradient;
- }
- else {
- num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
- }
- return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
- };
- return ElasticEase;
- })(EasingFunction);
- BABYLON.ElasticEase = ElasticEase;
- var ExponentialEase = (function (_super) {
- __extends(ExponentialEase, _super);
- function ExponentialEase(exponent) {
- if (exponent === void 0) { exponent = 2; }
- _super.call(this);
- this.exponent = exponent;
- }
- ExponentialEase.prototype.easeInCore = function (gradient) {
- if (this.exponent <= 0) {
- return gradient;
- }
- return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
- };
- return ExponentialEase;
- })(EasingFunction);
- BABYLON.ExponentialEase = ExponentialEase;
- var PowerEase = (function (_super) {
- __extends(PowerEase, _super);
- function PowerEase(power) {
- if (power === void 0) { power = 2; }
- _super.call(this);
- this.power = power;
- }
- PowerEase.prototype.easeInCore = function (gradient) {
- var y = Math.max(0.0, this.power);
- return Math.pow(gradient, y);
- };
- return PowerEase;
- })(EasingFunction);
- BABYLON.PowerEase = PowerEase;
- var QuadraticEase = (function (_super) {
- __extends(QuadraticEase, _super);
- function QuadraticEase() {
- _super.apply(this, arguments);
- }
- QuadraticEase.prototype.easeInCore = function (gradient) {
- return (gradient * gradient);
- };
- return QuadraticEase;
- })(EasingFunction);
- BABYLON.QuadraticEase = QuadraticEase;
- var QuarticEase = (function (_super) {
- __extends(QuarticEase, _super);
- function QuarticEase() {
- _super.apply(this, arguments);
- }
- QuarticEase.prototype.easeInCore = function (gradient) {
- return (gradient * gradient * gradient * gradient);
- };
- return QuarticEase;
- })(EasingFunction);
- BABYLON.QuarticEase = QuarticEase;
- var QuinticEase = (function (_super) {
- __extends(QuinticEase, _super);
- function QuinticEase() {
- _super.apply(this, arguments);
- }
- QuinticEase.prototype.easeInCore = function (gradient) {
- return (gradient * gradient * gradient * gradient * gradient);
- };
- return QuinticEase;
- })(EasingFunction);
- BABYLON.QuinticEase = QuinticEase;
- var SineEase = (function (_super) {
- __extends(SineEase, _super);
- function SineEase() {
- _super.apply(this, arguments);
- }
- SineEase.prototype.easeInCore = function (gradient) {
- return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
- };
- return SineEase;
- })(EasingFunction);
- BABYLON.SineEase = SineEase;
- var BezierCurveEase = (function (_super) {
- __extends(BezierCurveEase, _super);
- function BezierCurveEase(x1, y1, x2, y2) {
- if (x1 === void 0) { x1 = 0; }
- if (y1 === void 0) { y1 = 0; }
- if (x2 === void 0) { x2 = 1; }
- if (y2 === void 0) { y2 = 1; }
- _super.call(this);
- this.x1 = x1;
- this.y1 = y1;
- this.x2 = x2;
- this.y2 = y2;
- }
- BezierCurveEase.prototype.easeInCore = function (gradient) {
- return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
- };
- return BezierCurveEase;
- })(EasingFunction);
- BABYLON.BezierCurveEase = BezierCurveEase;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Bone = (function (_super) {
- __extends(Bone, _super);
- function Bone(name, skeleton, parentBone, matrix, restPose) {
- _super.call(this, name, skeleton.getScene());
- this.name = name;
- this.children = new Array();
- this.animations = new Array();
- this._worldTransform = new BABYLON.Matrix();
- this._absoluteTransform = new BABYLON.Matrix();
- this._invertedAbsoluteTransform = new BABYLON.Matrix();
- this._skeleton = skeleton;
- this._matrix = matrix;
- this._baseMatrix = matrix;
- this._restPose = restPose ? restPose : matrix.clone();
- skeleton.bones.push(this);
- if (parentBone) {
- this._parent = parentBone;
- parentBone.children.push(this);
- }
- else {
- this._parent = null;
- }
- this._updateDifferenceMatrix();
- }
- // Members
- Bone.prototype.getParent = function () {
- return this._parent;
- };
- Bone.prototype.getLocalMatrix = function () {
- return this._matrix;
- };
- Bone.prototype.getBaseMatrix = function () {
- return this._baseMatrix;
- };
- Bone.prototype.getRestPose = function () {
- return this._restPose;
- };
- Bone.prototype.returnToRest = function () {
- this.updateMatrix(this._restPose.clone());
- };
- Bone.prototype.getWorldMatrix = function () {
- return this._worldTransform;
- };
- Bone.prototype.getInvertedAbsoluteTransform = function () {
- return this._invertedAbsoluteTransform;
- };
- Bone.prototype.getAbsoluteTransform = function () {
- return this._absoluteTransform;
- };
- // Methods
- Bone.prototype.updateMatrix = function (matrix) {
- this._baseMatrix = matrix.clone();
- this._matrix = matrix.clone();
- this._skeleton._markAsDirty();
- this._updateDifferenceMatrix();
- };
- Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
- if (!rootMatrix) {
- rootMatrix = this._baseMatrix;
- }
- if (this._parent) {
- rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
- }
- else {
- this._absoluteTransform.copyFrom(rootMatrix);
- }
- this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
- for (var index = 0; index < this.children.length; index++) {
- this.children[index]._updateDifferenceMatrix();
- }
- };
- Bone.prototype.markAsDirty = function () {
- this._currentRenderId++;
- this._skeleton._markAsDirty();
- };
- Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
- if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
- // all animation may be coming from a library skeleton, so may need to create animation
- if (this.animations.length === 0) {
- this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
- this.animations[0].setKeys([]);
- }
- // get animation info / verify there is such a range from the source bone
- var sourceRange = source.animations[0].getRange(rangeName);
- if (!sourceRange) {
- return false;
- }
- var from = sourceRange.from;
- var to = sourceRange.to;
- var sourceKeys = source.animations[0].getKeys();
- // rescaling prep
- var sourceBoneLength = source.length;
- var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
- var ratio = scalingReqd ? this.length / sourceBoneLength : null;
- var destKeys = this.animations[0].getKeys();
- // loop vars declaration / initialization
- var orig;
- var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
- var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
- var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
- var mat;
- for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
- orig = sourceKeys[key];
- if (orig.frame >= from && orig.frame <= to) {
- if (scalingReqd) {
- orig.value.decompose(origScale, origRotation, origTranslation);
- origTranslation.scaleInPlace(ratio);
- mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
- }
- else {
- mat = orig.value;
- }
- destKeys.push({ frame: orig.frame + frameOffset, value: mat });
- }
- }
- this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
- return true;
- };
- return Bone;
- })(BABYLON.Node);
- BABYLON.Bone = Bone;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Skeleton = (function () {
- function Skeleton(name, id, scene) {
- this.name = name;
- this.id = id;
- this.bones = new Array();
- this.needInitialSkinMatrix = false;
- this._isDirty = true;
- this._meshesWithPoseMatrix = new Array();
- this._identity = BABYLON.Matrix.Identity();
- this._ranges = {};
- this.bones = [];
- this._scene = scene;
- scene.skeletons.push(this);
- //make sure it will recalculate the matrix next time prepare is called.
- this._isDirty = true;
- }
- // Members
- Skeleton.prototype.getTransformMatrices = function (mesh) {
- if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
- return mesh._bonesTransformMatrices;
- }
- return this._transformMatrices;
- };
- Skeleton.prototype.getScene = function () {
- return this._scene;
- };
- // Methods
- /**
- * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
- */
- Skeleton.prototype.toString = function (fullDetails) {
- var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
- ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
- if (fullDetails) {
- ret += ", Ranges: {";
- var first = true;
- for (var name in this._ranges) {
- if (!first) {
- ret + ", ";
- first = false;
- }
- ret += name;
- }
- ret += "}";
- }
- return ret;
- };
- /**
- * Get bone's index searching by name
- * @param {string} name is bone's name to search for
- * @return {number} Indice of the bone. Returns -1 if not found
- */
- Skeleton.prototype.getBoneIndexByName = function (name) {
- for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
- if (this.bones[boneIndex].name === name) {
- return boneIndex;
- }
- }
- return -1;
- };
- Skeleton.prototype.createAnimationRange = function (name, from, to) {
- // check name not already in use
- if (!this._ranges[name]) {
- this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
- for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
- if (this.bones[i].animations[0]) {
- this.bones[i].animations[0].createRange(name, from, to);
- }
- }
- }
- };
- Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
- if (deleteFrames === void 0) { deleteFrames = true; }
- for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
- if (this.bones[i].animations[0]) {
- this.bones[i].animations[0].deleteRange(name, deleteFrames);
- }
- }
- this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
- };
- Skeleton.prototype.getAnimationRange = function (name) {
- return this._ranges[name];
- };
- /**
- * Returns as an Array, all AnimationRanges defined on this skeleton
- */
- Skeleton.prototype.getAnimationRanges = function () {
- var animationRanges = [];
- var name;
- var i = 0;
- for (name in this._ranges) {
- animationRanges[i] = this._ranges[name];
- i++;
- }
- return animationRanges;
- };
- /**
- * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
- */
- Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
- if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
- if (this._ranges[name] || !source.getAnimationRange(name)) {
- return false;
- }
- var ret = true;
- var frameOffset = this._getHighestAnimationFrame() + 1;
- // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
- var boneDict = {};
- var sourceBones = source.bones;
- for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
- boneDict[sourceBones[i].name] = sourceBones[i];
- }
- if (this.bones.length !== sourceBones.length) {
- BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
- ret = false;
- }
- for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
- var boneName = this.bones[i].name;
- var sourceBone = boneDict[boneName];
- if (sourceBone) {
- ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
- }
- else {
- BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
- ret = false;
- }
- }
- // do not call createAnimationRange(), since it also is done to bones, which was already done
- var range = source.getAnimationRange(name);
- this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
- return ret;
- };
- Skeleton.prototype.returnToRest = function () {
- for (var index = 0; index < this.bones.length; index++) {
- this.bones[index].returnToRest();
- }
- };
- Skeleton.prototype._getHighestAnimationFrame = function () {
- var ret = 0;
- for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
- if (this.bones[i].animations[0]) {
- var highest = this.bones[i].animations[0].getHighestFrame();
- if (ret < highest) {
- ret = highest;
- }
- }
- }
- return ret;
- };
- Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
- var range = this.getAnimationRange(name);
- if (!range) {
- return null;
- }
- this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
- };
- Skeleton.prototype._markAsDirty = function () {
- this._isDirty = true;
- };
- Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
- this._meshesWithPoseMatrix.push(mesh);
- };
- Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
- var index = this._meshesWithPoseMatrix.indexOf(mesh);
- if (index > -1) {
- this._meshesWithPoseMatrix.splice(index, 1);
- }
- };
- Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
- for (var index = 0; index < this.bones.length; index++) {
- var bone = this.bones[index];
- var parentBone = bone.getParent();
- if (parentBone) {
- bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
- }
- else {
- if (initialSkinMatrix) {
- bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
- }
- else {
- bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
- }
- }
- bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
- }
- this._identity.copyToArray(targetMatrix, this.bones.length * 16);
- };
- Skeleton.prototype.prepare = function () {
- if (!this._isDirty) {
- return;
- }
- if (this.needInitialSkinMatrix) {
- for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
- var mesh = this._meshesWithPoseMatrix[index];
- if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
- mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
- }
- var poseMatrix = mesh.getPoseMatrix();
- // Prepare bones
- for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
- var bone = this.bones[boneIndex];
- if (!bone.getParent()) {
- var matrix = bone.getBaseMatrix();
- matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
- bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
- }
- }
- this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
- }
- }
- else {
- if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
- this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
- }
- this._computeTransformMatrices(this._transformMatrices, null);
- }
- this._isDirty = false;
- this._scene._activeBones += this.bones.length;
- };
- Skeleton.prototype.getAnimatables = function () {
- if (!this._animatables || this._animatables.length !== this.bones.length) {
- this._animatables = [];
- for (var index = 0; index < this.bones.length; index++) {
- this._animatables.push(this.bones[index]);
- }
- }
- return this._animatables;
- };
- Skeleton.prototype.clone = function (name, id) {
- var result = new Skeleton(name, id || name, this._scene);
- result.needInitialSkinMatrix = this.needInitialSkinMatrix;
- for (var index = 0; index < this.bones.length; index++) {
- var source = this.bones[index];
- var parentBone = null;
- if (source.getParent()) {
- var parentIndex = this.bones.indexOf(source.getParent());
- parentBone = result.bones[parentIndex];
- }
- var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
- BABYLON.Tools.DeepCopy(source.animations, bone.animations);
- }
- if (this._ranges) {
- result._ranges = {};
- for (var rangeName in this._ranges) {
- result._ranges[rangeName] = this._ranges[rangeName].clone();
- }
- }
- this._isDirty = true;
- return result;
- };
- Skeleton.prototype.dispose = function () {
- this._meshesWithPoseMatrix = [];
- // Animations
- this.getScene().stopAnimation(this);
- // Remove from scene
- this.getScene().removeSkeleton(this);
- };
- Skeleton.prototype.serialize = function () {
- var serializationObject = {};
- serializationObject.name = this.name;
- serializationObject.id = this.id;
- serializationObject.bones = [];
- serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
- for (var index = 0; index < this.bones.length; index++) {
- var bone = this.bones[index];
- var serializedBone = {
- parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
- name: bone.name,
- matrix: bone.getLocalMatrix().toArray(),
- rest: bone.getRestPose().toArray()
- };
- serializationObject.bones.push(serializedBone);
- if (bone.length) {
- serializedBone.length = bone.length;
- }
- if (bone.animations && bone.animations.length > 0) {
- serializedBone.animation = bone.animations[0].serialize();
- }
- serializationObject.ranges = [];
- for (var name in this._ranges) {
- var range = {};
- range.name = name;
- range.from = this._ranges[name].from;
- range.to = this._ranges[name].to;
- serializationObject.ranges.push(range);
- }
- }
- return serializationObject;
- };
- Skeleton.Parse = function (parsedSkeleton, scene) {
- var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
- skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
- for (var index = 0; index < parsedSkeleton.bones.length; index++) {
- var parsedBone = parsedSkeleton.bones[index];
- var parentBone = null;
- if (parsedBone.parentBoneIndex > -1) {
- parentBone = skeleton.bones[parsedBone.parentBoneIndex];
- }
- var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
- var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
- if (parsedBone.length) {
- bone.length = parsedBone.length;
- }
- if (parsedBone.animation) {
- bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
- }
- }
- // placed after bones, so createAnimationRange can cascade down
- if (parsedSkeleton.ranges) {
- for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
- var data = parsedSkeleton.ranges[index];
- skeleton.createAnimationRange(data.name, data.from, data.to);
- }
- }
- return skeleton;
- };
- return Skeleton;
- })();
- BABYLON.Skeleton = Skeleton;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var PostProcess = (function () {
- function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
- if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
- this.name = name;
- this.width = -1;
- this.height = -1;
- /*
- Enable Pixel Perfect mode where texture is not scaled to be power of 2.
- Can only be used on a single postprocess or on the last one of a chain.
- */
- this.enablePixelPerfectMode = false;
- this._reusable = false;
- this._textures = new BABYLON.SmartArray(2);
- this._currentRenderTextureInd = 0;
- this._scaleRatio = new BABYLON.Vector2(1, 1);
- if (camera != null) {
- this._camera = camera;
- this._scene = camera.getScene();
- camera.attachPostProcess(this);
- this._engine = this._scene.getEngine();
- }
- else {
- this._engine = engine;
- }
- this._renderRatio = ratio;
- this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
- this._reusable = reusable || false;
- this._textureType = textureType;
- this._samplers = samplers || [];
- this._samplers.push("textureSampler");
- this._fragmentUrl = fragmentUrl;
- this._parameters = parameters || [];
- this._parameters.push("scale");
- this.updateEffect(defines);
- }
- PostProcess.prototype.updateEffect = function (defines) {
- this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
- };
- PostProcess.prototype.isReusable = function () {
- return this._reusable;
- };
- PostProcess.prototype.activate = function (camera, sourceTexture) {
- camera = camera || this._camera;
- var scene = camera.getScene();
- var maxSize = camera.getEngine().getCaps().maxTextureSize;
- var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
- var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
- var desiredWidth = this._renderRatio.width || requiredWidth;
- var desiredHeight = this._renderRatio.height || requiredHeight;
- if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
- if (!this._renderRatio.width) {
- desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
- }
- if (!this._renderRatio.height) {
- desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
- }
- }
- if (this.width !== desiredWidth || this.height !== desiredHeight) {
- if (this._textures.length > 0) {
- for (var i = 0; i < this._textures.length; i++) {
- this._engine._releaseTexture(this._textures.data[i]);
- }
- this._textures.reset();
- }
- this.width = desiredWidth;
- this.height = desiredHeight;
- this._textures.push(this._engine.createRenderTargetTexture({ width: this.width, height: this.height }, { generateMipMaps: false, generateDepthBuffer: camera._postProcesses.indexOf(this) === camera._postProcessesTakenIndices[0], samplingMode: this.renderTargetSamplingMode, type: this._textureType }));
- if (this._reusable) {
- this._textures.push(this._engine.createRenderTargetTexture({ width: this.width, height: this.height }, { generateMipMaps: false, generateDepthBuffer: camera._postProcesses.indexOf(this) === camera._postProcessesTakenIndices[0], samplingMode: this.renderTargetSamplingMode, type: this._textureType }));
- }
- if (this.onSizeChanged) {
- this.onSizeChanged();
- }
- }
- if (this.enablePixelPerfectMode) {
- this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
- this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
- }
- else {
- this._scaleRatio.copyFromFloats(1, 1);
- this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
- }
- if (this.onActivate) {
- this.onActivate(camera);
- }
- // Clear
- if (this.clearColor) {
- this._engine.clear(this.clearColor, true, true);
- }
- else {
- this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
- }
- if (this._reusable) {
- this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
- }
- };
- Object.defineProperty(PostProcess.prototype, "isSupported", {
- get: function () {
- return this._effect.isSupported;
- },
- enumerable: true,
- configurable: true
- });
- PostProcess.prototype.apply = function () {
- // Check
- if (!this._effect.isReady())
- return null;
- // States
- this._engine.enableEffect(this._effect);
- this._engine.setState(false);
- this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
- this._engine.setDepthBuffer(false);
- this._engine.setDepthWrite(false);
- // Texture
- this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
- // Parameters
- this._effect.setVector2("scale", this._scaleRatio);
- if (this.onApply) {
- this.onApply(this._effect);
- }
- return this._effect;
- };
- PostProcess.prototype.dispose = function (camera) {
- camera = camera || this._camera;
- if (this._textures.length > 0) {
- for (var i = 0; i < this._textures.length; i++) {
- this._engine._releaseTexture(this._textures.data[i]);
- }
- this._textures.reset();
- }
- if (!camera) {
- return;
- }
- camera.detachPostProcess(this);
- var index = camera._postProcesses.indexOf(this);
- if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
- this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
- }
- };
- return PostProcess;
- })();
- BABYLON.PostProcess = PostProcess;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var PostProcessManager = (function () {
- function PostProcessManager(scene) {
- this._vertexDeclaration = [2];
- this._vertexStrideSize = 2 * 4;
- this._scene = scene;
- }
- PostProcessManager.prototype._prepareBuffers = function () {
- if (this._vertexBuffer) {
- return;
- }
- // VBO
- var vertices = [];
- vertices.push(1, 1);
- vertices.push(-1, 1);
- vertices.push(-1, -1);
- vertices.push(1, -1);
- this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
- // Indices
- var indices = [];
- indices.push(0);
- indices.push(1);
- indices.push(2);
- indices.push(0);
- indices.push(2);
- indices.push(3);
- this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
- };
- // Methods
- PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
- var postProcesses = this._scene.activeCamera._postProcesses;
- var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
- if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
- return false;
- }
- postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
- return true;
- };
- PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
- var engine = this._scene.getEngine();
- for (var index = 0; index < postProcesses.length; index++) {
- if (index < postProcesses.length - 1) {
- postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
- }
- else {
- if (targetTexture) {
- engine.bindFramebuffer(targetTexture);
- }
- else {
- engine.restoreDefaultFramebuffer();
- }
- }
- var pp = postProcesses[index];
- var effect = pp.apply();
- if (effect) {
- if (pp.onBeforeRender) {
- pp.onBeforeRender(effect);
- }
- // VBOs
- this._prepareBuffers();
- engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
- // Draw order
- engine.draw(true, 0, 6);
- if (pp.onAfterRender) {
- pp.onAfterRender(effect);
- }
- }
- }
- // Restore depth buffer
- engine.setDepthBuffer(true);
- engine.setDepthWrite(true);
- };
- PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
- postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
- var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
- if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
- return;
- }
- var engine = this._scene.getEngine();
- for (var index = 0; index < postProcessesTakenIndices.length; index++) {
- if (index < postProcessesTakenIndices.length - 1) {
- postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera, targetTexture);
- }
- else {
- if (targetTexture) {
- engine.bindFramebuffer(targetTexture, faceIndex);
- }
- else {
- engine.restoreDefaultFramebuffer();
- }
- }
- if (doNotPresent) {
- break;
- }
- var pp = postProcesses[postProcessesTakenIndices[index]];
- var effect = pp.apply();
- if (effect) {
- if (pp.onBeforeRender) {
- pp.onBeforeRender(effect);
- }
- // VBOs
- this._prepareBuffers();
- engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
- // Draw order
- engine.draw(true, 0, 6);
- if (pp.onAfterRender) {
- pp.onAfterRender(effect);
- }
- }
- }
- // Restore depth buffer
- engine.setDepthBuffer(true);
- engine.setDepthWrite(true);
- };
- PostProcessManager.prototype.dispose = function () {
- if (this._vertexBuffer) {
- this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
- this._vertexBuffer = null;
- }
- if (this._indexBuffer) {
- this._scene.getEngine()._releaseBuffer(this._indexBuffer);
- this._indexBuffer = null;
- }
- };
- return PostProcessManager;
- })();
- BABYLON.PostProcessManager = PostProcessManager;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var PassPostProcess = (function (_super) {
- __extends(PassPostProcess, _super);
- function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
- _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
- }
- return PassPostProcess;
- })(BABYLON.PostProcess);
- BABYLON.PassPostProcess = PassPostProcess;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- /**
- * This is a holder class for the physics joint created by the physics plugin.
- * It holds a set of functions to control the underlying joint.
- */
- var PhysicsJoint = (function () {
- function PhysicsJoint(type, jointData) {
- this.type = type;
- this.jointData = jointData;
- jointData.nativeParams = jointData.nativeParams || {};
- }
- Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
- get: function () {
- return this._physicsJoint;
- },
- set: function (newJoint) {
- if (this._physicsJoint) {
- }
- this._physicsJoint = newJoint;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
- set: function (physicsPlugin) {
- this._physicsPlugin = physicsPlugin;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Execute a function that is physics-plugin specific.
- * @param {Function} func the function that will be executed.
- * It accepts two parameters: the physics world and the physics joint.
- */
- PhysicsJoint.prototype.executeNativeFunction = function (func) {
- func(this._physicsPlugin.world, this._physicsJoint);
- };
- //TODO check if the native joints are the same
- //Joint Types
- PhysicsJoint.DistanceJoint = 0;
- PhysicsJoint.HingeJoint = 1;
- PhysicsJoint.BallAndSocketJoint = 2;
- PhysicsJoint.WheelJoint = 3;
- PhysicsJoint.SliderJoint = 4;
- //OIMO
- PhysicsJoint.PrismaticJoint = 5;
- //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
- PhysicsJoint.UniversalJoint = 6;
- PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
- //Cannon
- //Similar to a Ball-Joint. Different in params
- PhysicsJoint.PointToPointJoint = 8;
- //Cannon only at the moment
- PhysicsJoint.SpringJoint = 9;
- return PhysicsJoint;
- })();
- BABYLON.PhysicsJoint = PhysicsJoint;
- /**
- * A class representing a physics distance joint.
- */
- var DistanceJoint = (function (_super) {
- __extends(DistanceJoint, _super);
- function DistanceJoint(jointData) {
- _super.call(this, PhysicsJoint.DistanceJoint, jointData);
- }
- /**
- * Update the predefined distance.
- */
- DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
- this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
- };
- return DistanceJoint;
- })(PhysicsJoint);
- BABYLON.DistanceJoint = DistanceJoint;
- var MotorEnabledJoint = (function (_super) {
- __extends(MotorEnabledJoint, _super);
- function MotorEnabledJoint(type, jointData) {
- _super.call(this, type, jointData);
- }
- /**
- * Set the motor values.
- * Attention, this function is plugin specific. Engines won't react 100% the same.
- * @param {number} force the force to apply
- * @param {number} maxForce max force for this motor.
- */
- MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
- this._physicsPlugin.setMotor(this, force, maxForce);
- };
- /**
- * Set the motor's limits.
- * Attention, this function is plugin specific. Engines won't react 100% the same.
- */
- MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
- this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
- };
- return MotorEnabledJoint;
- })(PhysicsJoint);
- BABYLON.MotorEnabledJoint = MotorEnabledJoint;
- /**
- * This class represents a single hinge physics joint
- */
- var HingeJoint = (function (_super) {
- __extends(HingeJoint, _super);
- function HingeJoint(jointData) {
- _super.call(this, PhysicsJoint.HingeJoint, jointData);
- }
- /**
- * Set the motor values.
- * Attention, this function is plugin specific. Engines won't react 100% the same.
- * @param {number} force the force to apply
- * @param {number} maxForce max force for this motor.
- */
- HingeJoint.prototype.setMotor = function (force, maxForce) {
- this._physicsPlugin.setMotor(this, force, maxForce);
- };
- /**
- * Set the motor's limits.
- * Attention, this function is plugin specific. Engines won't react 100% the same.
- */
- HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
- this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
- };
- return HingeJoint;
- })(MotorEnabledJoint);
- BABYLON.HingeJoint = HingeJoint;
- /**
- * This class represents a dual hinge physics joint (same as wheel joint)
- */
- var Hinge2Joint = (function (_super) {
- __extends(Hinge2Joint, _super);
- function Hinge2Joint(jointData) {
- _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
- }
- /**
- * Set the motor values.
- * Attention, this function is plugin specific. Engines won't react 100% the same.
- * @param {number} force the force to apply
- * @param {number} maxForce max force for this motor.
- * @param {motorIndex} the motor's index, 0 or 1.
- */
- Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
- if (motorIndex === void 0) { motorIndex = 0; }
- this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
- };
- /**
- * Set the motor limits.
- * Attention, this function is plugin specific. Engines won't react 100% the same.
- * @param {number} upperLimit the upper limit
- * @param {number} lowerLimit lower limit
- * @param {motorIndex} the motor's index, 0 or 1.
- */
- Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
- if (motorIndex === void 0) { motorIndex = 0; }
- this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
- };
- return Hinge2Joint;
- })(MotorEnabledJoint);
- BABYLON.Hinge2Joint = Hinge2Joint;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var PhysicsImpostor = (function () {
- function PhysicsImpostor(object, type, _options, _scene) {
- var _this = this;
- if (_options === void 0) { _options = { mass: 0 }; }
- this.object = object;
- this.type = type;
- this._options = _options;
- this._scene = _scene;
- this._bodyUpdateRequired = false;
- this._onBeforePhysicsStepCallbacks = new Array();
- this._onAfterPhysicsStepCallbacks = new Array();
- this._onPhysicsCollideCallbacks = [];
- this._deltaPosition = BABYLON.Vector3.Zero();
- this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
- this._tmpRotationWithDelta = new BABYLON.Quaternion();
- /**
- * this function is executed by the physics engine.
- */
- this.beforeStep = function () {
- _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
- //conjugate deltaRotation
- if (_this._deltaRotationConjugated) {
- _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
- }
- else {
- _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
- }
- _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
- _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
- func(_this);
- });
- };
- /**
- * this function is executed by the physics engine.
- */
- this.afterStep = function () {
- _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
- func(_this);
- });
- _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
- _this.object.position.addInPlace(_this._deltaPosition);
- if (_this._deltaRotation) {
- _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
- }
- };
- //event and body object due to cannon's event-based architecture.
- this.onCollide = function (e) {
- if (!_this._onPhysicsCollideCallbacks.length)
- return;
- var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
- if (otherImpostor) {
- _this._onPhysicsCollideCallbacks.filter(function (obj) {
- return obj.otherImpostors.indexOf(otherImpostor) !== -1;
- }).forEach(function (obj) {
- obj.callback(_this, otherImpostor);
- });
- }
- };
- //sanity check!
- if (!this.object) {
- BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
- return;
- }
- //legacy support for old syntax.
- if (!this._scene && object.getScene) {
- this._scene = object.getScene();
- }
- this._physicsEngine = this._scene.getPhysicsEngine();
- if (!this._physicsEngine) {
- BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
- }
- else {
- //set the object's quaternion, if not set
- if (!this.object.rotationQuaternion) {
- if (this.object.rotation) {
- this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
- }
- else {
- this.object.rotationQuaternion = new BABYLON.Quaternion();
- }
- }
- //default options params
- this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
- this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
- this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
- this._joints = [];
- //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
- if (!this.object.parent) {
- this._init();
- }
- }
- }
- /**
- * This function will completly initialize this impostor.
- * It will create a new body - but only if this mesh has no parent.
- * If it has, this impostor will not be used other than to define the impostor
- * of the child mesh.
- */
- PhysicsImpostor.prototype._init = function () {
- this._physicsEngine.removeImpostor(this);
- this.physicsBody = null;
- this._parent = this._parent || this._getPhysicsParent();
- if (!this.parent) {
- this._physicsEngine.addImpostor(this);
- }
- };
- PhysicsImpostor.prototype._getPhysicsParent = function () {
- if (this.object.parent instanceof BABYLON.AbstractMesh) {
- var parentMesh = this.object.parent;
- return parentMesh.physicsImpostor;
- }
- return;
- };
- /**
- * Should a new body be generated.
- */
- PhysicsImpostor.prototype.isBodyInitRequired = function () {
- return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
- };
- PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
- this.forceUpdate();
- };
- /**
- * Force a regeneration of this or the parent's impostor's body.
- * Use under cautious - This will remove all joints already implemented.
- */
- PhysicsImpostor.prototype.forceUpdate = function () {
- this._init();
- if (this.parent) {
- this.parent.forceUpdate();
- }
- };
- Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
- /*public get mesh(): AbstractMesh {
- return this._mesh;
- }*/
- /**
- * Gets the body that holds this impostor. Either its own, or its parent.
- */
- get: function () {
- return this._parent ? this._parent.physicsBody : this._physicsBody;
- },
- /**
- * Set the physics body. Used mainly by the physics engine/plugin
- */
- set: function (physicsBody) {
- if (this._physicsBody) {
- this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
- }
- this._physicsBody = physicsBody;
- this.resetUpdateFlags();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PhysicsImpostor.prototype, "parent", {
- get: function () {
- return this._parent;
- },
- enumerable: true,
- configurable: true
- });
- PhysicsImpostor.prototype.resetUpdateFlags = function () {
- this._bodyUpdateRequired = false;
- };
- PhysicsImpostor.prototype.getObjectExtendSize = function () {
- if (this.object.getBoundingInfo) {
- this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
- return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
- }
- else {
- return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
- }
- };
- PhysicsImpostor.prototype.getObjectCenter = function () {
- if (this.object.getBoundingInfo) {
- return this.object.getBoundingInfo().boundingBox.center;
- }
- else {
- return this.object.position;
- }
- };
- /**
- * Get a specific parametes from the options parameter.
- */
- PhysicsImpostor.prototype.getParam = function (paramName) {
- return this._options[paramName];
- };
- /**
- * Sets a specific parameter in the options given to the physics plugin
- */
- PhysicsImpostor.prototype.setParam = function (paramName, value) {
- this._options[paramName] = value;
- this._bodyUpdateRequired = true;
- };
- /**
- * Specifically change the body's mass option. Won't recreate the physics body object
- */
- PhysicsImpostor.prototype.setMass = function (mass) {
- if (this.getParam("mass") !== mass) {
- this.setParam("mass", mass);
- }
- this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
- };
- PhysicsImpostor.prototype.getLinearVelocity = function () {
- return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
- };
- /**
- * Set the body's linear velocity.
- */
- PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
- this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
- };
- PhysicsImpostor.prototype.getAngularVelocity = function () {
- return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
- };
- /**
- * Set the body's linear velocity.
- */
- PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
- this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
- };
- /**
- * Execute a function with the physics plugin native code.
- * Provide a function the will have two variables - the world object and the physics body object.
- */
- PhysicsImpostor.prototype.executeNativeFunction = function (func) {
- func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
- };
- /**
- * Register a function that will be executed before the physics world is stepping forward.
- */
- PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
- this._onBeforePhysicsStepCallbacks.push(func);
- };
- PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
- var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
- if (index > -1) {
- this._onBeforePhysicsStepCallbacks.splice(index, 1);
- }
- else {
- BABYLON.Tools.Warn("Function to remove was not found");
- }
- };
- /**
- * Register a function that will be executed after the physics step
- */
- PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
- this._onAfterPhysicsStepCallbacks.push(func);
- };
- PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
- var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
- if (index > -1) {
- this._onAfterPhysicsStepCallbacks.splice(index, 1);
- }
- else {
- BABYLON.Tools.Warn("Function to remove was not found");
- }
- };
- /**
- * register a function that will be executed when this impostor collides against a different body.
- */
- PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
- var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
- this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
- };
- PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
- var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
- var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
- if (index > -1) {
- this._onPhysicsCollideCallbacks.splice(index, 1);
- }
- else {
- BABYLON.Tools.Warn("Function to remove was not found");
- }
- };
- /**
- * Apply a force
- */
- PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
- this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
- };
- /**
- * Apply an impulse
- */
- PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
- this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
- };
- /**
- * A help function to create a joint.
- */
- PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
- var joint = new BABYLON.PhysicsJoint(jointType, jointData);
- this.addJoint(otherImpostor, joint);
- };
- /**
- * Add a joint to this impostor with a different impostor.
- */
- PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
- this._joints.push({
- otherImpostor: otherImpostor,
- joint: joint
- });
- this._physicsEngine.addJoint(this, otherImpostor, joint);
- };
- /**
- * Will keep this body still, in a sleep mode.
- */
- PhysicsImpostor.prototype.sleep = function () {
- this._physicsEngine.getPhysicsPlugin().sleepBody(this);
- };
- /**
- * Wake the body up.
- */
- PhysicsImpostor.prototype.wakeUp = function () {
- this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
- };
- PhysicsImpostor.prototype.clone = function (newObject) {
- if (!newObject)
- return null;
- return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
- };
- PhysicsImpostor.prototype.dispose = function () {
- var _this = this;
- this._joints.forEach(function (j) {
- _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
- });
- //dispose the physics body
- this._physicsEngine.removeImpostor(this);
- if (this.parent) {
- this.parent.forceUpdate();
- }
- else {
- }
- };
- PhysicsImpostor.prototype.setDeltaPosition = function (position) {
- this._deltaPosition.copyFrom(position);
- };
- PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
- if (!this._deltaRotation) {
- this._deltaRotation = new BABYLON.Quaternion();
- }
- this._deltaRotation.copyFrom(rotation);
- this._deltaRotationConjugated = this._deltaRotation.conjugate();
- };
- PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
- //Impostor types
- PhysicsImpostor.NoImpostor = 0;
- PhysicsImpostor.SphereImpostor = 1;
- PhysicsImpostor.BoxImpostor = 2;
- PhysicsImpostor.PlaneImpostor = 3;
- PhysicsImpostor.MeshImpostor = 4;
- PhysicsImpostor.CylinderImpostor = 7;
- PhysicsImpostor.ParticleImpostor = 8;
- PhysicsImpostor.HeightmapImpostor = 9;
- return PhysicsImpostor;
- })();
- BABYLON.PhysicsImpostor = PhysicsImpostor;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var PhysicsEngine = (function () {
- function PhysicsEngine(gravity, _physicsPlugin) {
- if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
- this._physicsPlugin = _physicsPlugin;
- //new methods and parameters
- this._impostors = [];
- this._joints = [];
- if (!this._physicsPlugin.isSupported()) {
- throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
- + "Please make sure it is included.");
- }
- gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
- this.setGravity(gravity);
- this.setTimeStep();
- }
- PhysicsEngine.prototype.setGravity = function (gravity) {
- this.gravity = gravity;
- this._physicsPlugin.setGravity(this.gravity);
- };
- /**
- * Set the time step of the physics engine.
- * default is 1/60.
- * To slow it down, enter 1/600 for example.
- * To speed it up, 1/30
- * @param {number} newTimeStep the new timestep to apply to this world.
- */
- PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
- if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
- this._physicsPlugin.setTimeStep(newTimeStep);
- };
- PhysicsEngine.prototype.dispose = function () {
- this._impostors.forEach(function (impostor) {
- impostor.dispose();
- });
- this._physicsPlugin.dispose();
- };
- PhysicsEngine.prototype.getPhysicsPluginName = function () {
- return this._physicsPlugin.name;
- };
- /**
- * Adding a new impostor for the impostor tracking.
- * This will be done by the impostor itself.
- * @param {PhysicsImpostor} impostor the impostor to add
- */
- PhysicsEngine.prototype.addImpostor = function (impostor) {
- impostor.uniqueId = this._impostors.push(impostor);
- //if no parent, generate the body
- if (!impostor.parent) {
- this._physicsPlugin.generatePhysicsBody(impostor);
- }
- };
- /**
- * Remove an impostor from the engine.
- * This impostor and its mesh will not longer be updated by the physics engine.
- * @param {PhysicsImpostor} impostor the impostor to remove
- */
- PhysicsEngine.prototype.removeImpostor = function (impostor) {
- var index = this._impostors.indexOf(impostor);
- if (index > -1) {
- var removed = this._impostors.splice(index, 1);
- //Is it needed?
- if (removed.length) {
- //this will also remove it from the world.
- removed[0].physicsBody = null;
- }
- }
- };
- /**
- * Add a joint to the physics engine
- * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
- * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
- * @param {PhysicsJoint} the joint that will connect both impostors.
- */
- PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
- var impostorJoint = {
- mainImpostor: mainImpostor,
- connectedImpostor: connectedImpostor,
- joint: joint
- };
- joint.physicsPlugin = this._physicsPlugin;
- this._joints.push(impostorJoint);
- this._physicsPlugin.generateJoint(impostorJoint);
- };
- PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
- var matchingJoints = this._joints.filter(function (impostorJoint) {
- return (impostorJoint.connectedImpostor === connectedImpostor
- && impostorJoint.joint === joint
- && impostorJoint.mainImpostor === mainImpostor);
- });
- if (matchingJoints.length) {
- this._physicsPlugin.removeJoint(matchingJoints[0]);
- }
- };
- /**
- * Called by the scene. no need to call it.
- */
- PhysicsEngine.prototype._step = function (delta) {
- var _this = this;
- //check if any mesh has no body / requires an update
- this._impostors.forEach(function (impostor) {
- if (impostor.isBodyInitRequired()) {
- _this._physicsPlugin.generatePhysicsBody(impostor);
- }
- });
- if (delta > 0.1) {
- delta = 0.1;
- }
- else if (delta <= 0) {
- delta = 1.0 / 60.0;
- }
- this._physicsPlugin.executeStep(delta, this._impostors);
- };
- PhysicsEngine.prototype.getPhysicsPlugin = function () {
- return this._physicsPlugin;
- };
- PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
- for (var i = 0; i < this._impostors.length; ++i) {
- if (this._impostors[i].object === object) {
- return this._impostors[i];
- }
- }
- };
- PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
- for (var i = 0; i < this._impostors.length; ++i) {
- if (this._impostors[i].physicsBody === body) {
- return this._impostors[i];
- }
- }
- };
- // Statics, Legacy support.
- /**
- * @Deprecated
- *
- */
- PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
- PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
- PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
- PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
- PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
- PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
- PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
- PhysicsEngine.CapsuleImpostor = -1;
- PhysicsEngine.ConeImpostor = -1;
- PhysicsEngine.ConvexHullImpostor = -1;
- PhysicsEngine.Epsilon = 0.001;
- return PhysicsEngine;
- })();
- BABYLON.PhysicsEngine = PhysicsEngine;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var VertexData = (function () {
- function VertexData() {
- }
- VertexData.prototype.set = function (data, kind) {
- switch (kind) {
- case BABYLON.VertexBuffer.PositionKind:
- this.positions = data;
- break;
- case BABYLON.VertexBuffer.NormalKind:
- this.normals = data;
- break;
- case BABYLON.VertexBuffer.UVKind:
- this.uvs = data;
- break;
- case BABYLON.VertexBuffer.UV2Kind:
- this.uvs2 = data;
- break;
- case BABYLON.VertexBuffer.UV3Kind:
- this.uvs3 = data;
- break;
- case BABYLON.VertexBuffer.UV4Kind:
- this.uvs4 = data;
- break;
- case BABYLON.VertexBuffer.UV5Kind:
- this.uvs5 = data;
- break;
- case BABYLON.VertexBuffer.UV6Kind:
- this.uvs6 = data;
- break;
- case BABYLON.VertexBuffer.ColorKind:
- this.colors = data;
- break;
- case BABYLON.VertexBuffer.MatricesIndicesKind:
- this.matricesIndices = data;
- break;
- case BABYLON.VertexBuffer.MatricesWeightsKind:
- this.matricesWeights = data;
- break;
- case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
- this.matricesIndicesExtra = data;
- break;
- case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
- this.matricesWeightsExtra = data;
- break;
- }
- };
- VertexData.prototype.applyToMesh = function (mesh, updatable) {
- this._applyTo(mesh, updatable);
- };
- VertexData.prototype.applyToGeometry = function (geometry, updatable) {
- this._applyTo(geometry, updatable);
- };
- VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
- this._update(mesh);
- };
- VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
- this._update(geometry);
- };
- VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
- if (this.positions) {
- meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
- }
- if (this.normals) {
- meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
- }
- if (this.uvs) {
- meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
- }
- if (this.uvs2) {
- meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
- }
- if (this.uvs3) {
- meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
- }
- if (this.uvs4) {
- meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
- }
- if (this.uvs5) {
- meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
- }
- if (this.uvs6) {
- meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
- }
- if (this.colors) {
- meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
- }
- if (this.matricesIndices) {
- meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
- }
- if (this.matricesWeights) {
- meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
- }
- if (this.matricesIndicesExtra) {
- meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
- }
- if (this.matricesWeightsExtra) {
- meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
- }
- if (this.indices) {
- meshOrGeometry.setIndices(this.indices);
- }
- };
- VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
- if (this.positions) {
- meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
- }
- if (this.normals) {
- meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
- }
- if (this.uvs) {
- meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
- }
- if (this.uvs2) {
- meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
- }
- if (this.uvs3) {
- meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
- }
- if (this.uvs4) {
- meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
- }
- if (this.uvs5) {
- meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
- }
- if (this.uvs6) {
- meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
- }
- if (this.colors) {
- meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
- }
- if (this.matricesIndices) {
- meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
- }
- if (this.matricesWeights) {
- meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
- }
- if (this.matricesIndicesExtra) {
- meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
- }
- if (this.matricesWeightsExtra) {
- meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
- }
- if (this.indices) {
- meshOrGeometry.setIndices(this.indices);
- }
- };
- VertexData.prototype.transform = function (matrix) {
- var transformed = BABYLON.Vector3.Zero();
- var index;
- if (this.positions) {
- var position = BABYLON.Vector3.Zero();
- for (index = 0; index < this.positions.length; index += 3) {
- BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
- BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
- this.positions[index] = transformed.x;
- this.positions[index + 1] = transformed.y;
- this.positions[index + 2] = transformed.z;
- }
- }
- if (this.normals) {
- var normal = BABYLON.Vector3.Zero();
- for (index = 0; index < this.normals.length; index += 3) {
- BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
- BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
- this.normals[index] = transformed.x;
- this.normals[index + 1] = transformed.y;
- this.normals[index + 2] = transformed.z;
- }
- }
- };
- VertexData.prototype.merge = function (other) {
- if (other.indices) {
- if (!this.indices) {
- this.indices = [];
- }
- var offset = this.positions ? this.positions.length / 3 : 0;
- for (var index = 0; index < other.indices.length; index++) {
- //TODO check type - if Int32Array!
- this.indices.push(other.indices[index] + offset);
- }
- }
- this.positions = this._mergeElement(this.positions, other.positions);
- this.normals = this._mergeElement(this.normals, other.normals);
- this.uvs = this._mergeElement(this.uvs, other.uvs);
- this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
- this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
- this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
- this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
- this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
- this.colors = this._mergeElement(this.colors, other.colors);
- this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
- this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
- this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
- this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
- };
- VertexData.prototype._mergeElement = function (source, other) {
- if (!other)
- return source;
- if (!source)
- return other;
- var len = other.length + source.length;
- var isSrcTypedArray = source instanceof Float32Array;
- var isOthTypedArray = other instanceof Float32Array;
- // use non-loop method when the source is Float32Array
- if (isSrcTypedArray) {
- var ret32 = new Float32Array(len);
- ret32.set(source);
- ret32.set(other, source.length);
- return ret32;
- }
- else if (!isOthTypedArray) {
- return source.concat(other);
- }
- else {
- var ret = source.slice(0); // copy source to a separate array
- for (var i = 0, len = other.length; i < len; i++) {
- ret.push(other[i]);
- }
- return ret;
- }
- };
- VertexData.prototype.serialize = function () {
- var serializationObject = this.serialize();
- if (this.positions) {
- serializationObject.positions = this.positions;
- }
- if (this.normals) {
- serializationObject.normals = this.normals;
- }
- if (this.uvs) {
- serializationObject.uvs = this.uvs;
- }
- if (this.uvs2) {
- serializationObject.uvs2 = this.uvs2;
- }
- if (this.uvs3) {
- serializationObject.uvs3 = this.uvs3;
- }
- if (this.uvs4) {
- serializationObject.uvs4 = this.uvs4;
- }
- if (this.uvs5) {
- serializationObject.uvs5 = this.uvs5;
- }
- if (this.uvs6) {
- serializationObject.uvs6 = this.uvs6;
- }
- if (this.colors) {
- serializationObject.colors = this.colors;
- }
- if (this.matricesIndices) {
- serializationObject.matricesIndices = this.matricesIndices;
- serializationObject.matricesIndices._isExpanded = true;
- }
- if (this.matricesWeights) {
- serializationObject.matricesWeights = this.matricesWeights;
- }
- if (this.matricesIndicesExtra) {
- serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
- serializationObject.matricesIndicesExtra._isExpanded = true;
- }
- if (this.matricesWeightsExtra) {
- serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
- }
- serializationObject.indices = this.indices;
- return serializationObject;
- };
- // Statics
- VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
- return VertexData._ExtractFrom(mesh, copyWhenShared);
- };
- VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
- return VertexData._ExtractFrom(geometry, copyWhenShared);
- };
- VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
- var result = new VertexData();
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
- result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
- result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
- result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
- result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
- result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
- result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
- result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
- result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
- result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
- result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
- result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
- result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
- result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
- }
- result.indices = meshOrGeometry.getIndices(copyWhenShared);
- return result;
- };
- VertexData.CreateRibbon = function (options) {
- var pathArray = options.pathArray;
- var closeArray = options.closeArray || false;
- var closePath = options.closePath || false;
- var defaultOffset = Math.floor(pathArray[0].length / 2);
- var offset = options.offset || defaultOffset;
- offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
- var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
- var positions = [];
- var indices = [];
- var normals = [];
- var uvs = [];
- var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
- var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
- var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
- var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
- var minlg; // minimal length among all paths from pathArray
- var lg = []; // array of path lengths : nb of vertex per path
- var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
- var p; // path iterator
- var i; // point iterator
- var j; // point iterator
- // if single path in pathArray
- if (pathArray.length < 2) {
- var ar1 = [];
- var ar2 = [];
- for (i = 0; i < pathArray[0].length - offset; i++) {
- ar1.push(pathArray[0][i]);
- ar2.push(pathArray[0][i + offset]);
- }
- pathArray = [ar1, ar2];
- }
- // positions and horizontal distances (u)
- var idc = 0;
- var closePathCorr = (closePath) ? 1 : 0;
- var path;
- var l;
- minlg = pathArray[0].length;
- var vectlg;
- var dist;
- for (p = 0; p < pathArray.length; p++) {
- uTotalDistance[p] = 0;
- us[p] = [0];
- path = pathArray[p];
- l = path.length;
- minlg = (minlg < l) ? minlg : l;
- j = 0;
- while (j < l) {
- positions.push(path[j].x, path[j].y, path[j].z);
- if (j > 0) {
- vectlg = path[j].subtract(path[j - 1]).length();
- dist = vectlg + uTotalDistance[p];
- us[p].push(dist);
- uTotalDistance[p] = dist;
- }
- j++;
- }
- if (closePath) {
- j--;
- positions.push(path[0].x, path[0].y, path[0].z);
- vectlg = path[j].subtract(path[0]).length();
- dist = vectlg + uTotalDistance[p];
- us[p].push(dist);
- uTotalDistance[p] = dist;
- }
- lg[p] = l + closePathCorr;
- idx[p] = idc;
- idc += (l + closePathCorr);
- }
- // vertical distances (v)
- var path1;
- var path2;
- var vertex1;
- var vertex2;
- for (i = 0; i < minlg + closePathCorr; i++) {
- vTotalDistance[i] = 0;
- vs[i] = [0];
- for (p = 0; p < pathArray.length - 1; p++) {
- path1 = pathArray[p];
- path2 = pathArray[p + 1];
- if (i === minlg) {
- vertex1 = path1[0];
- vertex2 = path2[0];
- }
- else {
- vertex1 = path1[i];
- vertex2 = path2[i];
- }
- vectlg = vertex2.subtract(vertex1).length();
- dist = vectlg + vTotalDistance[i];
- vs[i].push(dist);
- vTotalDistance[i] = dist;
- }
- if (closeArray) {
- path1 = pathArray[p];
- path2 = pathArray[0];
- if (i === minlg) {
- vertex2 = path2[0];
- }
- vectlg = vertex2.subtract(vertex1).length();
- dist = vectlg + vTotalDistance[i];
- vTotalDistance[i] = dist;
- }
- }
- // uvs
- var u;
- var v;
- for (p = 0; p < pathArray.length; p++) {
- for (i = 0; i < minlg + closePathCorr; i++) {
- u = us[p][i] / uTotalDistance[p];
- v = vs[i][p] / vTotalDistance[i];
- uvs.push(u, v);
- }
- }
- // indices
- p = 0; // path index
- var pi = 0; // positions array index
- var l1 = lg[p] - 1; // path1 length
- var l2 = lg[p + 1] - 1; // path2 length
- var min = (l1 < l2) ? l1 : l2; // current path stop index
- var shft = idx[1] - idx[0]; // shift
- var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
- while (pi <= min && p < path1nb) {
- // 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
- indices.push(pi, pi + shft, pi + 1);
- indices.push(pi + shft + 1, pi + 1, pi + shft);
- pi += 1;
- if (pi === min) {
- p++;
- if (p === lg.length - 1) {
- shft = idx[0] - idx[p];
- l1 = lg[p] - 1;
- l2 = lg[0] - 1;
- }
- else {
- shft = idx[p + 1] - idx[p];
- l1 = lg[p] - 1;
- l2 = lg[p + 1] - 1;
- }
- pi = idx[p];
- min = (l1 < l2) ? l1 + pi : l2 + pi;
- }
- }
- // normals
- VertexData.ComputeNormals(positions, indices, normals);
- if (closePath) {
- var indexFirst = 0;
- var indexLast = 0;
- for (p = 0; p < pathArray.length; p++) {
- indexFirst = idx[p] * 3;
- if (p + 1 < pathArray.length) {
- indexLast = (idx[p + 1] - 1) * 3;
- }
- else {
- indexLast = normals.length - 3;
- }
- normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
- normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
- normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
- normals[indexLast] = normals[indexFirst];
- normals[indexLast + 1] = normals[indexFirst + 1];
- normals[indexLast + 2] = normals[indexFirst + 2];
- }
- }
- // sides
- VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
- // Result
- var vertexData = new VertexData();
- vertexData.indices = indices;
- vertexData.positions = positions;
- vertexData.normals = normals;
- vertexData.uvs = uvs;
- if (closePath) {
- vertexData._idx = idx;
- }
- return vertexData;
- };
- VertexData.CreateBox = function (options) {
- var normalsSource = [
- new BABYLON.Vector3(0, 0, 1),
- new BABYLON.Vector3(0, 0, -1),
- new BABYLON.Vector3(1, 0, 0),
- new BABYLON.Vector3(-1, 0, 0),
- new BABYLON.Vector3(0, 1, 0),
- new BABYLON.Vector3(0, -1, 0)
- ];
- var indices = [];
- var positions = [];
- var normals = [];
- var uvs = [];
- var width = options.width || options.size || 1;
- var height = options.height || options.size || 1;
- var depth = options.depth || options.size || 1;
- var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
- var faceUV = options.faceUV || new Array(6);
- var faceColors = options.faceColors;
- var colors = [];
- // default face colors and UV if undefined
- for (var f = 0; f < 6; f++) {
- if (faceUV[f] === undefined) {
- faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
- }
- if (faceColors && faceColors[f] === undefined) {
- faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
- }
- }
- var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
- // Create each face in turn.
- for (var index = 0; index < normalsSource.length; index++) {
- var normal = normalsSource[index];
- // Get two vectors perpendicular to the face normal and to each other.
- var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
- var side2 = BABYLON.Vector3.Cross(normal, side1);
- // Six indices (two triangles) per face.
- var verticesLength = positions.length / 3;
- indices.push(verticesLength);
- indices.push(verticesLength + 1);
- indices.push(verticesLength + 2);
- indices.push(verticesLength);
- indices.push(verticesLength + 2);
- indices.push(verticesLength + 3);
- // Four vertices per face.
- var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
- positions.push(vertex.x, vertex.y, vertex.z);
- normals.push(normal.x, normal.y, normal.z);
- uvs.push(faceUV[index].z, faceUV[index].w);
- if (faceColors) {
- colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
- }
- vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
- positions.push(vertex.x, vertex.y, vertex.z);
- normals.push(normal.x, normal.y, normal.z);
- uvs.push(faceUV[index].x, faceUV[index].w);
- if (faceColors) {
- colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
- }
- vertex = normal.add(side1).add(side2).multiply(scaleVector);
- positions.push(vertex.x, vertex.y, vertex.z);
- normals.push(normal.x, normal.y, normal.z);
- uvs.push(faceUV[index].x, faceUV[index].y);
- if (faceColors) {
- colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
- }
- vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
- positions.push(vertex.x, vertex.y, vertex.z);
- normals.push(normal.x, normal.y, normal.z);
- uvs.push(faceUV[index].z, faceUV[index].y);
- if (faceColors) {
- colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
- }
- }
- // sides
- VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
- // Result
- var vertexData = new VertexData();
- vertexData.indices = indices;
- vertexData.positions = positions;
- vertexData.normals = normals;
- vertexData.uvs = uvs;
- if (faceColors) {
- var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
- vertexData.colors = totalColors;
- }
- return vertexData;
- };
- VertexData.CreateSphere = function (options) {
- var segments = options.segments || 32;
- var diameterX = options.diameterX || options.diameter || 1;
- var diameterY = options.diameterY || options.diameter || 1;
- var diameterZ = options.diameterZ || options.diameter || 1;
- var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
- var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
- var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
- var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
- var totalZRotationSteps = 2 + segments;
- var totalYRotationSteps = 2 * totalZRotationSteps;
- var indices = [];
- var positions = [];
- var normals = [];
- var uvs = [];
- for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
- var normalizedZ = zRotationStep / totalZRotationSteps;
- var angleZ = normalizedZ * Math.PI * slice;
- for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
- var normalizedY = yRotationStep / totalYRotationSteps;
- var angleY = normalizedY * Math.PI * 2 * arc;
- var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
- var rotationY = BABYLON.Matrix.RotationY(angleY);
- var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
- var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
- var vertex = complete.multiply(radius);
- var normal = complete.divide(radius).normalize();
- positions.push(vertex.x, vertex.y, vertex.z);
- normals.push(normal.x, normal.y, normal.z);
- uvs.push(normalizedY, normalizedZ);
- }
- if (zRotationStep > 0) {
- var verticesCount = positions.length / 3;
- for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
- indices.push((firstIndex));
- indices.push((firstIndex + 1));
- indices.push(firstIndex + totalYRotationSteps + 1);
- indices.push((firstIndex + totalYRotationSteps + 1));
- indices.push((firstIndex + 1));
- indices.push((firstIndex + totalYRotationSteps + 2));
- }
- }
- }
- // Sides
- VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
- // Result
- var vertexData = new VertexData();
- vertexData.indices = indices;
- vertexData.positions = positions;
- vertexData.normals = normals;
- vertexData.uvs = uvs;
- return vertexData;
- };
- // Cylinder and cone
- VertexData.CreateCylinder = function (options) {
- var height = options.height || 2;
- var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
- var diameterBottom = options.diameterBottom || options.diameter || 1;
- var tessellation = options.tessellation || 24;
- var subdivisions = options.subdivisions || 1;
- var hasRings = options.hasRings;
- var enclose = options.enclose;
- var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
- var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
- var faceUV = options.faceUV || new Array(3);
- var faceColors = options.faceColors;
- // default face colors and UV if undefined
- var quadNb = (arc !== 1 && enclose) ? 2 : 0;
- var ringNb = (hasRings) ? subdivisions : 1;
- var surfaceNb = 2 + (1 + quadNb) * ringNb;
- var f;
- for (f = 0; f < surfaceNb; f++) {
- if (faceColors && faceColors[f] === undefined) {
- faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
- }
- }
- for (f = 0; f < surfaceNb; f++) {
- if (faceUV && faceUV[f] === undefined) {
- faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
- }
- }
- var indices = [];
- var positions = [];
- var normals = [];
- var uvs = [];
- var colors = [];
- var angle_step = Math.PI * 2 * arc / tessellation;
- var angle;
- var h;
- var radius;
- var tan = (diameterBottom - diameterTop) / 2 / height;
- var ringVertex = BABYLON.Vector3.Zero();
- var ringNormal = BABYLON.Vector3.Zero();
- var ringFirstVertex = BABYLON.Vector3.Zero();
- var ringFirstNormal = BABYLON.Vector3.Zero();
- var quadNormal = BABYLON.Vector3.Zero();
- var Y = BABYLON.Axis.Y;
- // positions, normals, uvs
- var i;
- var j;
- var r;
- var ringIdx = 1;
- var s = 1; // surface index
- var cs = 0;
- var v = 0;
- for (i = 0; i <= subdivisions; i++) {
- h = i / subdivisions;
- radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
- ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
- for (r = 0; r < ringIdx; r++) {
- if (hasRings) {
- s += r;
- }
- if (enclose) {
- s += 2 * r;
- }
- for (j = 0; j <= tessellation; j++) {
- angle = j * angle_step;
- // position
- ringVertex.x = Math.cos(-angle) * radius;
- ringVertex.y = -height / 2 + h * height;
- ringVertex.z = Math.sin(-angle) * radius;
- // normal
- if (diameterTop === 0 && i === subdivisions) {
- // if no top cap, reuse former normals
- ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
- ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
- ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
- }
- else {
- ringNormal.x = ringVertex.x;
- ringNormal.z = ringVertex.z;
- ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
- ringNormal.normalize();
- }
- // keep first ring vertex values for enclose
- if (j === 0) {
- ringFirstVertex.copyFrom(ringVertex);
- ringFirstNormal.copyFrom(ringNormal);
- }
- positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
- normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
- if (hasRings) {
- v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
- }
- else {
- v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
- }
- uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
- if (faceColors) {
- colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
- }
- }
- // if enclose, add four vertices and their dedicated normals
- if (arc !== 1 && enclose) {
- positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
- positions.push(0, ringVertex.y, 0);
- positions.push(0, ringVertex.y, 0);
- positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
- BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
- quadNormal.normalize();
- normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
- BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
- quadNormal.normalize();
- normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
- if (hasRings) {
- v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
- }
- else {
- v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
- }
- uvs.push(faceUV[s + 1].x, v);
- uvs.push(faceUV[s + 1].z, v);
- if (hasRings) {
- v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
- }
- else {
- v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
- }
- uvs.push(faceUV[s + 2].x, v);
- uvs.push(faceUV[s + 2].z, v);
- if (faceColors) {
- colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
- colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
- colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
- colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
- }
- }
- if (cs !== s) {
- cs = s;
- }
- }
- }
- // indices
- var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
- var s;
- i = 0;
- for (s = 0; s < subdivisions; s++) {
- for (j = 0; j < tessellation; j++) {
- var i0 = i * (e + 1) + j;
- var i1 = (i + 1) * (e + 1) + j;
- var i2 = i * (e + 1) + (j + 1);
- var i3 = (i + 1) * (e + 1) + (j + 1);
- indices.push(i0, i1, i2);
- indices.push(i3, i2, i1);
- }
- if (arc !== 1 && enclose) {
- indices.push(i0 + 2, i1 + 2, i2 + 2);
- indices.push(i3 + 2, i2 + 2, i1 + 2);
- indices.push(i0 + 4, i1 + 4, i2 + 4);
- indices.push(i3 + 4, i2 + 4, i1 + 4);
- }
- i = (hasRings) ? (i + 2) : (i + 1);
- }
- // Caps
- var createCylinderCap = function (isTop) {
- var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
- if (radius === 0) {
- return;
- }
- // Cap positions, normals & uvs
- var angle;
- var circleVector;
- var i;
- var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
- var c;
- if (faceColors) {
- c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
- }
- // cap center
- var vbase = positions.length / 3;
- var offset = isTop ? height / 2 : -height / 2;
- var center = new BABYLON.Vector3(0, offset, 0);
- positions.push(center.x, center.y, center.z);
- normals.push(0, isTop ? 1 : -1, 0);
- uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
- if (faceColors) {
- colors.push(c.r, c.g, c.b, c.a);
- }
- var textureScale = new BABYLON.Vector2(0.5, 0.5);
- for (i = 0; i <= tessellation; i++) {
- angle = Math.PI * 2 * i * arc / tessellation;
- var cos = Math.cos(-angle);
- var sin = Math.sin(-angle);
- circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
- var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
- positions.push(circleVector.x, circleVector.y, circleVector.z);
- normals.push(0, isTop ? 1 : -1, 0);
- uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
- if (faceColors) {
- colors.push(c.r, c.g, c.b, c.a);
- }
- }
- // Cap indices
- for (i = 0; i < tessellation; i++) {
- if (!isTop) {
- indices.push(vbase);
- indices.push(vbase + (i + 1));
- indices.push(vbase + (i + 2));
- }
- else {
- indices.push(vbase);
- indices.push(vbase + (i + 2));
- indices.push(vbase + (i + 1));
- }
- }
- };
- // add caps to geometry
- createCylinderCap(false);
- createCylinderCap(true);
- // Sides
- VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
- var vertexData = new VertexData();
- vertexData.indices = indices;
- vertexData.positions = positions;
- vertexData.normals = normals;
- vertexData.uvs = uvs;
- if (faceColors) {
- vertexData.colors = colors;
- }
- return vertexData;
- };
- VertexData.CreateTorus = function (options) {
- var indices = [];
- var positions = [];
- var normals = [];
- var uvs = [];
- var diameter = options.diameter || 1;
- var thickness = options.thickness || 0.5;
- var tessellation = options.tessellation || 16;
- var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
- var stride = tessellation + 1;
- for (var i = 0; i <= tessellation; i++) {
- var u = i / tessellation;
- var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
- var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
- for (var j = 0; j <= tessellation; j++) {
- var v = 1 - j / tessellation;
- var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
- var dx = Math.cos(innerAngle);
- var dy = Math.sin(innerAngle);
- // Create a vertex.
- var normal = new BABYLON.Vector3(dx, dy, 0);
- var position = normal.scale(thickness / 2);
- var textureCoordinate = new BABYLON.Vector2(u, v);
- position = BABYLON.Vector3.TransformCoordinates(position, transform);
- normal = BABYLON.Vector3.TransformNormal(normal, transform);
- positions.push(position.x, position.y, position.z);
- normals.push(normal.x, normal.y, normal.z);
- uvs.push(textureCoordinate.x, textureCoordinate.y);
- // And create indices for two triangles.
- var nextI = (i + 1) % stride;
- var nextJ = (j + 1) % stride;
- indices.push(i * stride + j);
- indices.push(i * stride + nextJ);
- indices.push(nextI * stride + j);
- indices.push(i * stride + nextJ);
- indices.push(nextI * stride + nextJ);
- indices.push(nextI * stride + j);
- }
- }
- // Sides
- VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
- // Result
- var vertexData = new VertexData();
- vertexData.indices = indices;
- vertexData.positions = positions;
- vertexData.normals = normals;
- vertexData.uvs = uvs;
- return vertexData;
- };
- VertexData.CreateLineSystem = function (options) {
- var indices = [];
- var positions = [];
- var lines = options.lines;
- var idx = 0;
- for (var l = 0; l < lines.length; l++) {
- var points = lines[l];
- for (var index = 0; index < points.length; index++) {
- positions.push(points[index].x, points[index].y, points[index].z);
- if (index > 0) {
- indices.push(idx - 1);
- indices.push(idx);
- }
- idx++;
- }
- }
- var vertexData = new VertexData();
- vertexData.indices = indices;
- vertexData.positions = positions;
- return vertexData;
- };
- VertexData.CreateDashedLines = function (options) {
- var dashSize = options.dashSize || 3;
- var gapSize = options.gapSize || 1;
- var dashNb = options.dashNb || 200;
- var points = options.points;
- var positions = new Array();
- var indices = new Array();
- var curvect = BABYLON.Vector3.Zero();
- var lg = 0;
- var nb = 0;
- var shft = 0;
- var dashshft = 0;
- var curshft = 0;
- var idx = 0;
- var i = 0;
- for (i = 0; i < points.length - 1; i++) {
- points[i + 1].subtractToRef(points[i], curvect);
- lg += curvect.length();
- }
- shft = lg / dashNb;
- dashshft = dashSize * shft / (dashSize + gapSize);
- for (i = 0; i < points.length - 1; i++) {
- points[i + 1].subtractToRef(points[i], curvect);
- nb = Math.floor(curvect.length() / shft);
- curvect.normalize();
- for (var j = 0; j < nb; j++) {
- curshft = shft * j;
- positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
- positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
- indices.push(idx, idx + 1);
- idx += 2;
- }
- }
- // Result
- var vertexData = new VertexData();
- vertexData.positions = positions;
- vertexData.indices = indices;
- return vertexData;
- };
- VertexData.CreateGround = function (options) {
- var indices = [];
- var positions = [];
- var normals = [];
- var uvs = [];
- var row, col;
- var width = options.width || 1;
- var height = options.height || 1;
- var subdivisions = options.subdivisions || 1;
- for (row = 0; row <= subdivisions; row++) {
- for (col = 0; col <= subdivisions; col++) {
- var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
- var normal = new BABYLON.Vector3(0, 1.0, 0);
- positions.push(position.x, position.y, position.z);
- normals.push(normal.x, normal.y, normal.z);
- uvs.push(col / subdivisions, 1.0 - row / subdivisions);
- }
- }
- for (row = 0; row < subdivisions; row++) {
- for (col = 0; col < subdivisions; col++) {
- indices.push(col + 1 + (row + 1) * (subdivisions + 1));
- indices.push(col + 1 + row * (subdivisions + 1));
- indices.push(col + row * (subdivisions + 1));
- indices.push(col + (row + 1) * (subdivisions + 1));
- indices.push(col + 1 + (row + 1) * (subdivisions + 1));
- indices.push(col + row * (subdivisions + 1));
- }
- }
- // Result
- var vertexData = new VertexData();
- vertexData.indices = indices;
- vertexData.positions = positions;
- vertexData.normals = normals;
- vertexData.uvs = uvs;
- return vertexData;
- };
- VertexData.CreateTiledGround = function (options) {
- var xmin = options.xmin;
- var zmin = options.zmin;
- var xmax = options.xmax;
- var zmax = options.zmax;
- var subdivisions = options.subdivisions || { w: 1, h: 1 };
- var precision = options.precision || { w: 1, h: 1 };
- var indices = [];
- var positions = [];
- var normals = [];
- var uvs = [];
- var row, col, tileRow, tileCol;
- subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
- subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
- precision.w = (precision.w < 1) ? 1 : precision.w;
- precision.h = (precision.h < 1) ? 1 : precision.h;
- var tileSize = {
- 'w': (xmax - xmin) / subdivisions.w,
- 'h': (zmax - zmin) / subdivisions.h
- };
- function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
- // Indices
- var base = positions.length / 3;
- var rowLength = precision.w + 1;
- for (row = 0; row < precision.h; row++) {
- for (col = 0; col < precision.w; col++) {
- var square = [
- base + col + row * rowLength,
- base + (col + 1) + row * rowLength,
- base + (col + 1) + (row + 1) * rowLength,
- base + col + (row + 1) * rowLength
- ];
- indices.push(square[1]);
- indices.push(square[2]);
- indices.push(square[3]);
- indices.push(square[0]);
- indices.push(square[1]);
- indices.push(square[3]);
- }
- }
- // Position, normals and uvs
- var position = BABYLON.Vector3.Zero();
- var normal = new BABYLON.Vector3(0, 1.0, 0);
- for (row = 0; row <= precision.h; row++) {
- position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
- for (col = 0; col <= precision.w; col++) {
- position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
- position.y = 0;
- positions.push(position.x, position.y, position.z);
- normals.push(normal.x, normal.y, normal.z);
- uvs.push(col / precision.w, row / precision.h);
- }
- }
- }
- for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
- for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
- applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
- }
- }
- // Result
- var vertexData = new VertexData();
- vertexData.indices = indices;
- vertexData.positions = positions;
- vertexData.normals = normals;
- vertexData.uvs = uvs;
- return vertexData;
- };
- VertexData.CreateGroundFromHeightMap = function (options) {
- var indices = [];
- var positions = [];
- var normals = [];
- var uvs = [];
- var row, col;
- // Vertices
- for (row = 0; row <= options.subdivisions; row++) {
- for (col = 0; col <= options.subdivisions; col++) {
- 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));
- // Compute height
- var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
- var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
- var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
- var r = options.buffer[pos] / 255.0;
- var g = options.buffer[pos + 1] / 255.0;
- var b = options.buffer[pos + 2] / 255.0;
- var gradient = r * 0.3 + g * 0.59 + b * 0.11;
- position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
- // Add vertex
- positions.push(position.x, position.y, position.z);
- normals.push(0, 0, 0);
- uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
- }
- }
- // Indices
- for (row = 0; row < options.subdivisions; row++) {
- for (col = 0; col < options.subdivisions; col++) {
- indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
- indices.push(col + 1 + row * (options.subdivisions + 1));
- indices.push(col + row * (options.subdivisions + 1));
- indices.push(col + (row + 1) * (options.subdivisions + 1));
- indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
- indices.push(col + row * (options.subdivisions + 1));
- }
- }
- // Normals
- VertexData.ComputeNormals(positions, indices, normals);
- // Result
- var vertexData = new VertexData();
- vertexData.indices = indices;
- vertexData.positions = positions;
- vertexData.normals = normals;
- vertexData.uvs = uvs;
- return vertexData;
- };
- VertexData.CreatePlane = function (options) {
- var indices = [];
- var positions = [];
- var normals = [];
- var uvs = [];
- var width = options.width || options.size || 1;
- var height = options.height || options.size || 1;
- var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
- // Vertices
- var halfWidth = width / 2.0;
- var halfHeight = height / 2.0;
- positions.push(-halfWidth, -halfHeight, 0);
- normals.push(0, 0, -1.0);
- uvs.push(0.0, 0.0);
- positions.push(halfWidth, -halfHeight, 0);
- normals.push(0, 0, -1.0);
- uvs.push(1.0, 0.0);
- positions.push(halfWidth, halfHeight, 0);
- normals.push(0, 0, -1.0);
- uvs.push(1.0, 1.0);
- positions.push(-halfWidth, halfHeight, 0);
- normals.push(0, 0, -1.0);
- uvs.push(0.0, 1.0);
- // Indices
- indices.push(0);
- indices.push(1);
- indices.push(2);
- indices.push(0);
- indices.push(2);
- indices.push(3);
- // Sides
- VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
- // Result
- var vertexData = new VertexData();
- vertexData.indices = indices;
- vertexData.positions = positions;
- vertexData.normals = normals;
- vertexData.uvs = uvs;
- return vertexData;
- };
- VertexData.CreateDisc = function (options) {
- var positions = [];
- var indices = [];
- var normals = [];
- var uvs = [];
- var radius = options.radius || 0.5;
- var tessellation = options.tessellation || 64;
- var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
- var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
- // positions and uvs
- positions.push(0, 0, 0); // disc center first
- uvs.push(0.5, 0.5);
- var theta = Math.PI * 2 * arc;
- var step = theta / tessellation;
- for (var a = 0; a < theta; a += step) {
- var x = Math.cos(a);
- var y = Math.sin(a);
- var u = (x + 1) / 2;
- var v = (1 - y) / 2;
- positions.push(radius * x, radius * y, 0);
- uvs.push(u, v);
- }
- if (arc === 1) {
- positions.push(positions[3], positions[4], positions[5]); // close the circle
- uvs.push(uvs[2], uvs[3]);
- }
- //indices
- var vertexNb = positions.length / 3;
- for (var i = 1; i < vertexNb - 1; i++) {
- indices.push(i + 1, 0, i);
- }
- // result
- VertexData.ComputeNormals(positions, indices, normals);
- VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
- var vertexData = new VertexData();
- vertexData.indices = indices;
- vertexData.positions = positions;
- vertexData.normals = normals;
- vertexData.uvs = uvs;
- return vertexData;
- };
- VertexData.CreateIcoSphere = function (options) {
- var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
- var radius = options.radius || 1;
- var flat = (options.flat === undefined) ? true : options.flat;
- var subdivisions = options.subdivisions || 4;
- var radiusX = options.radiusX || radius;
- var radiusY = options.radiusY || radius;
- var radiusZ = options.radiusZ || radius;
- var t = (1 + Math.sqrt(5)) / 2;
- // 12 vertex x,y,z
- var ico_vertices = [
- -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
- 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
- t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
- ];
- // index of 3 vertex makes a face of icopshere
- var ico_indices = [
- 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
- 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
- 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
- 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
- ];
- // vertex for uv have aliased position, not for UV
- var vertices_unalias_id = [
- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
- // vertex alias
- 0,
- 2,
- 3,
- 3,
- 3,
- 4,
- 7,
- 8,
- 9,
- 9,
- 10,
- 11 // 23: B + 12
- ];
- // uv as integer step (not pixels !)
- var ico_vertexuv = [
- 5, 1, 3, 1, 6, 4, 0, 0,
- 5, 3, 4, 2, 2, 2, 4, 0,
- 2, 0, 1, 1, 6, 0, 6, 2,
- // vertex alias (for same vertex on different faces)
- 0, 4,
- 3, 3,
- 4, 4,
- 3, 1,
- 4, 2,
- 4, 4,
- 0, 2,
- 1, 1,
- 2, 2,
- 3, 3,
- 1, 3,
- 2, 4 // 23: B + 12
- ];
- // Vertices[0, 1, ...9, A, B] : position on UV plane
- // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
- // First island of uv mapping
- // v = 4h 3+ 2
- // v = 3h 9+ 4
- // v = 2h 9+ 5 B
- // v = 1h 9 1 0
- // v = 0h 3 8 7 A
- // u = 0 1 2 3 4 5 6 *a
- // Second island of uv mapping
- // v = 4h 0+ B+ 4+
- // v = 3h A+ 2+
- // v = 2h 7+ 6 3+
- // v = 1h 8+ 3+
- // v = 0h
- // u = 0 1 2 3 4 5 6 *a
- // Face layout on texture UV mapping
- // ============
- // \ 4 /\ 16 / ======
- // \ / \ / /\ 11 /
- // \/ 7 \/ / \ /
- // ======= / 10 \/
- // /\ 17 /\ =======
- // / \ / \ \ 15 /\
- // / 8 \/ 12 \ \ / \
- // ============ \/ 6 \
- // \ 18 /\ ============
- // \ / \ \ 5 /\ 0 /
- // \/ 13 \ \ / \ /
- // ======= \/ 1 \/
- // =============
- // /\ 19 /\ 2 /\
- // / \ / \ / \
- // / 14 \/ 9 \/ 3 \
- // ===================
- // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
- var ustep = 138 / 1024;
- var vstep = 239 / 1024;
- var uoffset = 60 / 1024;
- var voffset = 26 / 1024;
- // Second island should have margin, not to touch the first island
- // avoid any borderline artefact in pixel rounding
- var island_u_offset = -40 / 1024;
- var island_v_offset = +20 / 1024;
- // face is either island 0 or 1 :
- // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
- var island = [
- 0, 0, 0, 0, 1,
- 0, 0, 1, 1, 0,
- 0, 0, 1, 1, 0,
- 0, 1, 1, 1, 0 // 15 - 19
- ];
- var indices = [];
- var positions = [];
- var normals = [];
- var uvs = [];
- var current_indice = 0;
- // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
- var face_vertex_pos = new Array(3);
- var face_vertex_uv = new Array(3);
- var v012;
- for (v012 = 0; v012 < 3; v012++) {
- face_vertex_pos[v012] = BABYLON.Vector3.Zero();
- face_vertex_uv[v012] = BABYLON.Vector2.Zero();
- }
- // create all with normals
- for (var face = 0; face < 20; face++) {
- // 3 vertex per face
- for (v012 = 0; v012 < 3; v012++) {
- // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
- var v_id = ico_indices[3 * face + v012];
- // vertex have 3D position (x,y,z)
- 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]);
- // Normalize to get normal, then scale to radius
- face_vertex_pos[v012].normalize().scaleInPlace(radius);
- // uv Coordinates from vertex ID
- 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);
- }
- // Subdivide the face (interpolate pos, norm, uv)
- // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
- // - norm is linear interpolation of vertex corner normal
- // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
- // - uv is linear interpolation
- //
- // Topology is as below for sub-divide by 2
- // vertex shown as v0,v1,v2
- // interp index is i1 to progress in range [v0,v1[
- // interp index is i2 to progress in range [v0,v2[
- // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
- // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
- //
- //
- // i2 v2
- // ^ ^
- // / / \
- // / / \
- // / / \
- // / / (0,1) \
- // / #---------\
- // / / \ (0,0)'/ \
- // / / \ / \
- // / / \ / \
- // / / (0,0) \ / (1,0) \
- // / #---------#---------\
- // v0 v1
- //
- // --------------------> i1
- //
- // interp of (i1,i2):
- // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
- // along i1 : lerp(x0,x1, i1/(S-i2))
- //
- // centroid of triangle is needed to get help normal computation
- // (c1,c2) are used for centroid location
- var interp_vertex = function (i1, i2, c1, c2) {
- // vertex is interpolated from
- // - face_vertex_pos[0..2]
- // - face_vertex_uv[0..2]
- var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
- var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
- var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
- pos_interp.normalize();
- var vertex_normal;
- if (flat) {
- // in flat mode, recalculate normal as face centroid normal
- var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
- var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
- vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
- }
- else {
- // in smooth mode, recalculate normal from each single vertex position
- vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
- }
- // Vertex normal need correction due to X,Y,Z radius scaling
- vertex_normal.x /= radiusX;
- vertex_normal.y /= radiusY;
- vertex_normal.z /= radiusZ;
- vertex_normal.normalize();
- var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
- var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
- var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
- positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
- normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
- uvs.push(uv_interp.x, uv_interp.y);
- // push each vertex has member of a face
- // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
- indices.push(current_indice);
- current_indice++;
- };
- for (var i2 = 0; i2 < subdivisions; i2++) {
- for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
- // face : (i1,i2) for /\ :
- // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
- interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
- interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
- interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
- if (i1 + i2 + 1 < subdivisions) {
- // face : (i1,i2)' for \/ :
- // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
- interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
- interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
- interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
- }
- }
- }
- }
- // Sides
- VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
- // Result
- var vertexData = new VertexData();
- vertexData.indices = indices;
- vertexData.positions = positions;
- vertexData.normals = normals;
- vertexData.uvs = uvs;
- return vertexData;
- };
- // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
- VertexData.CreatePolyhedron = function (options) {
- // provided polyhedron types :
- // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
- // 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)
- var polyhedra = [];
- 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]] };
- 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]] };
- polyhedra[2] = {
- 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]],
- 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]]
- };
- polyhedra[3] = {
- 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]],
- 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]]
- };
- polyhedra[4] = {
- 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]],
- 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]]
- };
- 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]] };
- 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]] };
- 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]] };
- 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]] };
- 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]] };
- 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]] };
- 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]] };
- 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]] };
- 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]] };
- polyhedra[14] = {
- 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]],
- 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]]
- };
- var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
- var size = options.size;
- var sizeX = options.sizeX || size || 1;
- var sizeY = options.sizeY || size || 1;
- var sizeZ = options.sizeZ || size || 1;
- var data = options.custom || polyhedra[type];
- var nbfaces = data.face.length;
- var faceUV = options.faceUV || new Array(nbfaces);
- var faceColors = options.faceColors;
- var flat = (options.flat === undefined) ? true : options.flat;
- var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
- var positions = [];
- var indices = [];
- var normals = [];
- var uvs = [];
- var colors = [];
- var index = 0;
- var faceIdx = 0; // face cursor in the array "indexes"
- var indexes = [];
- var i = 0;
- var f = 0;
- var u, v, ang, x, y, tmp;
- // default face colors and UV if undefined
- if (flat) {
- for (f = 0; f < nbfaces; f++) {
- if (faceColors && faceColors[f] === undefined) {
- faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
- }
- if (faceUV && faceUV[f] === undefined) {
- faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
- }
- }
- }
- if (!flat) {
- for (i = 0; i < data.vertex.length; i++) {
- positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
- uvs.push(0, 0);
- }
- for (f = 0; f < nbfaces; f++) {
- for (i = 0; i < data.face[f].length - 2; i++) {
- indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
- }
- }
- }
- else {
- for (f = 0; f < nbfaces; f++) {
- var fl = data.face[f].length; // number of vertices of the current face
- ang = 2 * Math.PI / fl;
- x = 0.5 * Math.tan(ang / 2);
- y = 0.5;
- // positions, uvs, colors
- for (i = 0; i < fl; i++) {
- // positions
- 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);
- indexes.push(index);
- index++;
- // uvs
- u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
- v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
- uvs.push(u, v);
- tmp = x * Math.cos(ang) - y * Math.sin(ang);
- y = x * Math.sin(ang) + y * Math.cos(ang);
- x = tmp;
- // colors
- if (faceColors) {
- colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
- }
- }
- // indices from indexes
- for (i = 0; i < fl - 2; i++) {
- indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
- }
- faceIdx += fl;
- }
- }
- VertexData.ComputeNormals(positions, indices, normals);
- VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
- var vertexData = new VertexData();
- vertexData.positions = positions;
- vertexData.indices = indices;
- vertexData.normals = normals;
- vertexData.uvs = uvs;
- if (faceColors && flat) {
- vertexData.colors = colors;
- }
- return vertexData;
- };
- // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
- VertexData.CreateTorusKnot = function (options) {
- var indices = [];
- var positions = [];
- var normals = [];
- var uvs = [];
- var radius = options.radius || 2;
- var tube = options.tube || 0.5;
- var radialSegments = options.radialSegments || 32;
- var tubularSegments = options.tubularSegments || 32;
- var p = options.p || 2;
- var q = options.q || 3;
- var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
- // Helper
- var getPos = function (angle) {
- var cu = Math.cos(angle);
- var su = Math.sin(angle);
- var quOverP = q / p * angle;
- var cs = Math.cos(quOverP);
- var tx = radius * (2 + cs) * 0.5 * cu;
- var ty = radius * (2 + cs) * su * 0.5;
- var tz = radius * Math.sin(quOverP) * 0.5;
- return new BABYLON.Vector3(tx, ty, tz);
- };
- // Vertices
- var i;
- var j;
- for (i = 0; i <= radialSegments; i++) {
- var modI = i % radialSegments;
- var u = modI / radialSegments * 2 * p * Math.PI;
- var p1 = getPos(u);
- var p2 = getPos(u + 0.01);
- var tang = p2.subtract(p1);
- var n = p2.add(p1);
- var bitan = BABYLON.Vector3.Cross(tang, n);
- n = BABYLON.Vector3.Cross(bitan, tang);
- bitan.normalize();
- n.normalize();
- for (j = 0; j < tubularSegments; j++) {
- var modJ = j % tubularSegments;
- var v = modJ / tubularSegments * 2 * Math.PI;
- var cx = -tube * Math.cos(v);
- var cy = tube * Math.sin(v);
- positions.push(p1.x + cx * n.x + cy * bitan.x);
- positions.push(p1.y + cx * n.y + cy * bitan.y);
- positions.push(p1.z + cx * n.z + cy * bitan.z);
- uvs.push(i / radialSegments);
- uvs.push(j / tubularSegments);
- }
- }
- for (i = 0; i < radialSegments; i++) {
- for (j = 0; j < tubularSegments; j++) {
- var jNext = (j + 1) % tubularSegments;
- var a = i * tubularSegments + j;
- var b = (i + 1) * tubularSegments + j;
- var c = (i + 1) * tubularSegments + jNext;
- var d = i * tubularSegments + jNext;
- indices.push(d);
- indices.push(b);
- indices.push(a);
- indices.push(d);
- indices.push(c);
- indices.push(b);
- }
- }
- // Normals
- VertexData.ComputeNormals(positions, indices, normals);
- // Sides
- VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
- // Result
- var vertexData = new VertexData();
- vertexData.indices = indices;
- vertexData.positions = positions;
- vertexData.normals = normals;
- vertexData.uvs = uvs;
- return vertexData;
- };
- // Tools
- /**
- * @param {any} - positions (number[] or Float32Array)
- * @param {any} - indices (number[] or Uint16Array)
- * @param {any} - normals (number[] or Float32Array)
- */
- VertexData.ComputeNormals = function (positions, indices, normals) {
- var index = 0;
- var p1p2x = 0.0;
- var p1p2y = 0.0;
- var p1p2z = 0.0;
- var p3p2x = 0.0;
- var p3p2y = 0.0;
- var p3p2z = 0.0;
- var faceNormalx = 0.0;
- var faceNormaly = 0.0;
- var faceNormalz = 0.0;
- var length = 0.0;
- var i1 = 0;
- var i2 = 0;
- var i3 = 0;
- for (index = 0; index < positions.length; index++) {
- normals[index] = 0.0;
- }
- // indice triplet = 1 face
- var nbFaces = indices.length / 3;
- for (index = 0; index < nbFaces; index++) {
- i1 = indices[index * 3]; // get the indexes of each vertex of the face
- i2 = indices[index * 3 + 1];
- i3 = indices[index * 3 + 2];
- p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
- p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
- p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
- p3p2x = positions[i3 * 3] - positions[i2 * 3];
- p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
- p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
- faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
- faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
- faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
- length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
- length = (length === 0) ? 1.0 : length;
- faceNormalx /= length; // normalize this normal
- faceNormaly /= length;
- faceNormalz /= length;
- normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
- normals[i1 * 3 + 1] += faceNormaly;
- normals[i1 * 3 + 2] += faceNormalz;
- normals[i2 * 3] += faceNormalx;
- normals[i2 * 3 + 1] += faceNormaly;
- normals[i2 * 3 + 2] += faceNormalz;
- normals[i3 * 3] += faceNormalx;
- normals[i3 * 3 + 1] += faceNormaly;
- normals[i3 * 3 + 2] += faceNormalz;
- }
- // last normalization of each normal
- for (index = 0; index < normals.length / 3; index++) {
- faceNormalx = normals[index * 3];
- faceNormaly = normals[index * 3 + 1];
- faceNormalz = normals[index * 3 + 2];
- length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
- length = (length === 0) ? 1.0 : length;
- faceNormalx /= length;
- faceNormaly /= length;
- faceNormalz /= length;
- normals[index * 3] = faceNormalx;
- normals[index * 3 + 1] = faceNormaly;
- normals[index * 3 + 2] = faceNormalz;
- }
- };
- VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
- var li = indices.length;
- var ln = normals.length;
- var i;
- var n;
- sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
- switch (sideOrientation) {
- case BABYLON.Mesh.FRONTSIDE:
- // nothing changed
- break;
- case BABYLON.Mesh.BACKSIDE:
- var tmp;
- // indices
- for (i = 0; i < li; i += 3) {
- tmp = indices[i];
- indices[i] = indices[i + 2];
- indices[i + 2] = tmp;
- }
- // normals
- for (n = 0; n < ln; n++) {
- normals[n] = -normals[n];
- }
- break;
- case BABYLON.Mesh.DOUBLESIDE:
- // positions
- var lp = positions.length;
- var l = lp / 3;
- for (var p = 0; p < lp; p++) {
- positions[lp + p] = positions[p];
- }
- // indices
- for (i = 0; i < li; i += 3) {
- indices[i + li] = indices[i + 2] + l;
- indices[i + 1 + li] = indices[i + 1] + l;
- indices[i + 2 + li] = indices[i] + l;
- }
- // normals
- for (n = 0; n < ln; n++) {
- normals[ln + n] = -normals[n];
- }
- // uvs
- var lu = uvs.length;
- for (var u = 0; u < lu; u++) {
- uvs[u + lu] = uvs[u];
- }
- break;
- }
- };
- VertexData.ImportVertexData = function (parsedVertexData, geometry) {
- var vertexData = new VertexData();
- // positions
- var positions = parsedVertexData.positions;
- if (positions) {
- vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
- }
- // normals
- var normals = parsedVertexData.normals;
- if (normals) {
- vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
- }
- // uvs
- var uvs = parsedVertexData.uvs;
- if (uvs) {
- vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
- }
- // uv2s
- var uv2s = parsedVertexData.uv2s;
- if (uv2s) {
- vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
- }
- // uv3s
- var uv3s = parsedVertexData.uv3s;
- if (uv3s) {
- vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
- }
- // uv4s
- var uv4s = parsedVertexData.uv4s;
- if (uv4s) {
- vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
- }
- // uv5s
- var uv5s = parsedVertexData.uv5s;
- if (uv5s) {
- vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
- }
- // uv6s
- var uv6s = parsedVertexData.uv6s;
- if (uv6s) {
- vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
- }
- // colors
- var colors = parsedVertexData.colors;
- if (colors) {
- vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
- }
- // matricesIndices
- var matricesIndices = parsedVertexData.matricesIndices;
- if (matricesIndices) {
- vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
- }
- // matricesWeights
- var matricesWeights = parsedVertexData.matricesWeights;
- if (matricesWeights) {
- vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
- }
- // indices
- var indices = parsedVertexData.indices;
- if (indices) {
- vertexData.indices = indices;
- }
- geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
- };
- return VertexData;
- })();
- BABYLON.VertexData = VertexData;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Tags = (function () {
- function Tags() {
- }
- Tags.EnableFor = function (obj) {
- obj._tags = obj._tags || {};
- obj.hasTags = function () {
- return Tags.HasTags(obj);
- };
- obj.addTags = function (tagsString) {
- return Tags.AddTagsTo(obj, tagsString);
- };
- obj.removeTags = function (tagsString) {
- return Tags.RemoveTagsFrom(obj, tagsString);
- };
- obj.matchesTagsQuery = function (tagsQuery) {
- return Tags.MatchesQuery(obj, tagsQuery);
- };
- };
- Tags.DisableFor = function (obj) {
- delete obj._tags;
- delete obj.hasTags;
- delete obj.addTags;
- delete obj.removeTags;
- delete obj.matchesTagsQuery;
- };
- Tags.HasTags = function (obj) {
- if (!obj._tags) {
- return false;
- }
- return !BABYLON.Tools.IsEmpty(obj._tags);
- };
- Tags.GetTags = function (obj, asString) {
- if (asString === void 0) { asString = true; }
- if (!obj._tags) {
- return null;
- }
- if (asString) {
- var tagsArray = [];
- for (var tag in obj._tags) {
- if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
- tagsArray.push(tag);
- }
- }
- return tagsArray.join(" ");
- }
- else {
- return obj._tags;
- }
- };
- // the tags 'true' and 'false' are reserved and cannot be used as tags
- // a tag cannot start with '||', '&&', and '!'
- // it cannot contain whitespaces
- Tags.AddTagsTo = function (obj, tagsString) {
- if (!tagsString) {
- return;
- }
- if (typeof tagsString !== "string") {
- return;
- }
- var tags = tagsString.split(" ");
- for (var t in tags) {
- Tags._AddTagTo(obj, tags[t]);
- }
- };
- Tags._AddTagTo = function (obj, tag) {
- tag = tag.trim();
- if (tag === "" || tag === "true" || tag === "false") {
- return;
- }
- if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
- return;
- }
- Tags.EnableFor(obj);
- obj._tags[tag] = true;
- };
- Tags.RemoveTagsFrom = function (obj, tagsString) {
- if (!Tags.HasTags(obj)) {
- return;
- }
- var tags = tagsString.split(" ");
- for (var t in tags) {
- Tags._RemoveTagFrom(obj, tags[t]);
- }
- };
- Tags._RemoveTagFrom = function (obj, tag) {
- delete obj._tags[tag];
- };
- Tags.MatchesQuery = function (obj, tagsQuery) {
- if (tagsQuery === undefined) {
- return true;
- }
- if (tagsQuery === "") {
- return Tags.HasTags(obj);
- }
- return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
- };
- return Tags;
- })();
- BABYLON.Tags = Tags;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Internals;
- (function (Internals) {
- var AndOrNotEvaluator = (function () {
- function AndOrNotEvaluator() {
- }
- AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
- if (!query.match(/\([^\(\)]*\)/g)) {
- query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
- }
- else {
- query = query.replace(/\([^\(\)]*\)/g, function (r) {
- // remove parenthesis
- r = r.slice(1, r.length - 1);
- return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
- });
- }
- if (query === "true") {
- return true;
- }
- if (query === "false") {
- return false;
- }
- return AndOrNotEvaluator.Eval(query, evaluateCallback);
- };
- AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
- evaluateCallback = evaluateCallback || (function (r) {
- return r === "true" ? true : false;
- });
- var result;
- var or = parenthesisContent.split("||");
- for (var i in or) {
- var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
- var and = ori.split("&&");
- if (and.length > 1) {
- for (var j = 0; j < and.length; ++j) {
- var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
- if (andj !== "true" && andj !== "false") {
- if (andj[0] === "!") {
- result = !evaluateCallback(andj.substring(1));
- }
- else {
- result = evaluateCallback(andj);
- }
- }
- else {
- result = andj === "true" ? true : false;
- }
- if (!result) {
- ori = "false";
- break;
- }
- }
- }
- if (result || ori === "true") {
- result = true;
- break;
- }
- // result equals false (or undefined)
- if (ori !== "true" && ori !== "false") {
- if (ori[0] === "!") {
- result = !evaluateCallback(ori.substring(1));
- }
- else {
- result = evaluateCallback(ori);
- }
- }
- else {
- result = ori === "true" ? true : false;
- }
- }
- // the whole parenthesis scope is replaced by 'true' or 'false'
- return result ? "true" : "false";
- };
- AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
- booleanString = booleanString.replace(/^[\s!]+/, function (r) {
- // remove whitespaces
- r = r.replace(/[\s]/g, function () { return ""; });
- return r.length % 2 ? "!" : "";
- });
- booleanString = booleanString.trim();
- if (booleanString === "!true") {
- booleanString = "false";
- }
- else if (booleanString === "!false") {
- booleanString = "true";
- }
- return booleanString;
- };
- return AndOrNotEvaluator;
- })();
- Internals.AndOrNotEvaluator = AndOrNotEvaluator;
- })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var PostProcessRenderPass = (function () {
- function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
- this._enabled = true;
- this._refCount = 0;
- this._name = name;
- this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
- this.setRenderList(renderList);
- this._renderTexture.onBeforeRender = beforeRender;
- this._renderTexture.onAfterRender = afterRender;
- this._scene = scene;
- this._renderList = renderList;
- }
- // private
- PostProcessRenderPass.prototype._incRefCount = function () {
- if (this._refCount === 0) {
- this._scene.customRenderTargets.push(this._renderTexture);
- }
- return ++this._refCount;
- };
- PostProcessRenderPass.prototype._decRefCount = function () {
- this._refCount--;
- if (this._refCount <= 0) {
- this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
- }
- return this._refCount;
- };
- PostProcessRenderPass.prototype._update = function () {
- this.setRenderList(this._renderList);
- };
- // public
- PostProcessRenderPass.prototype.setRenderList = function (renderList) {
- this._renderTexture.renderList = renderList;
- };
- PostProcessRenderPass.prototype.getRenderTexture = function () {
- return this._renderTexture;
- };
- return PostProcessRenderPass;
- })();
- BABYLON.PostProcessRenderPass = PostProcessRenderPass;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var PostProcessRenderEffect = (function () {
- function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
- this._engine = engine;
- this._name = name;
- this._singleInstance = singleInstance || true;
- this._getPostProcess = getPostProcess;
- this._cameras = [];
- this._indicesForCamera = [];
- this._postProcesses = {};
- this._renderPasses = {};
- this._renderEffectAsPasses = {};
- }
- Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
- get: function () {
- for (var index in this._postProcesses) {
- if (!this._postProcesses[index].isSupported) {
- return false;
- }
- }
- return true;
- },
- enumerable: true,
- configurable: true
- });
- PostProcessRenderEffect.prototype._update = function () {
- for (var renderPassName in this._renderPasses) {
- this._renderPasses[renderPassName]._update();
- }
- };
- PostProcessRenderEffect.prototype.addPass = function (renderPass) {
- this._renderPasses[renderPass._name] = renderPass;
- this._linkParameters();
- };
- PostProcessRenderEffect.prototype.removePass = function (renderPass) {
- delete this._renderPasses[renderPass._name];
- this._linkParameters();
- };
- PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
- this._renderEffectAsPasses[renderEffect._name] = renderEffect;
- this._linkParameters();
- };
- PostProcessRenderEffect.prototype.getPass = function (passName) {
- for (var renderPassName in this._renderPasses) {
- if (renderPassName === passName) {
- return this._renderPasses[passName];
- }
- }
- };
- PostProcessRenderEffect.prototype.emptyPasses = function () {
- this._renderPasses = {};
- this._linkParameters();
- };
- PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
- var cameraKey;
- var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
- for (var i = 0; i < _cam.length; i++) {
- var camera = _cam[i];
- var cameraName = camera.name;
- if (this._singleInstance) {
- cameraKey = 0;
- }
- else {
- cameraKey = cameraName;
- }
- this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
- var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
- if (!this._indicesForCamera[cameraName]) {
- this._indicesForCamera[cameraName] = [];
- }
- this._indicesForCamera[cameraName].push(index);
- if (this._cameras.indexOf(camera) === -1) {
- this._cameras[cameraName] = camera;
- }
- for (var passName in this._renderPasses) {
- this._renderPasses[passName]._incRefCount();
- }
- }
- this._linkParameters();
- };
- PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
- var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
- for (var i = 0; i < _cam.length; i++) {
- var camera = _cam[i];
- var cameraName = camera.name;
- camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
- var index = this._cameras.indexOf(cameraName);
- this._indicesForCamera.splice(index, 1);
- this._cameras.splice(index, 1);
- for (var passName in this._renderPasses) {
- this._renderPasses[passName]._decRefCount();
- }
- }
- };
- PostProcessRenderEffect.prototype._enable = function (cameras) {
- var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
- for (var i = 0; i < _cam.length; i++) {
- var camera = _cam[i];
- var cameraName = camera.name;
- for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
- if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
- cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
- }
- }
- for (var passName in this._renderPasses) {
- this._renderPasses[passName]._incRefCount();
- }
- }
- };
- PostProcessRenderEffect.prototype._disable = function (cameras) {
- var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
- for (var i = 0; i < _cam.length; i++) {
- var camera = _cam[i];
- var cameraName = camera.Name;
- camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
- for (var passName in this._renderPasses) {
- this._renderPasses[passName]._decRefCount();
- }
- }
- };
- PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
- if (this._singleInstance) {
- return this._postProcesses[0];
- }
- else {
- return this._postProcesses[camera.name];
- }
- };
- PostProcessRenderEffect.prototype._linkParameters = function () {
- var _this = this;
- for (var index in this._postProcesses) {
- if (this.applyParameters) {
- this.applyParameters(this._postProcesses[index]);
- }
- this._postProcesses[index].onBeforeRender = function (effect) {
- _this._linkTextures(effect);
- };
- }
- };
- PostProcessRenderEffect.prototype._linkTextures = function (effect) {
- for (var renderPassName in this._renderPasses) {
- effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
- }
- for (var renderEffectName in this._renderEffectAsPasses) {
- effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
- }
- };
- return PostProcessRenderEffect;
- })();
- BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var PostProcessRenderPipeline = (function () {
- function PostProcessRenderPipeline(engine, name) {
- this._engine = engine;
- this._name = name;
- this._renderEffects = {};
- this._renderEffectsForIsolatedPass = {};
- this._cameras = [];
- }
- Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
- get: function () {
- for (var renderEffectName in this._renderEffects) {
- if (!this._renderEffects[renderEffectName].isSupported) {
- return false;
- }
- }
- return true;
- },
- enumerable: true,
- configurable: true
- });
- PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
- this._renderEffects[renderEffect._name] = renderEffect;
- };
- PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
- var renderEffects = this._renderEffects[renderEffectName];
- if (!renderEffects) {
- return;
- }
- renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
- };
- PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
- var renderEffects = this._renderEffects[renderEffectName];
- if (!renderEffects) {
- return;
- }
- renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
- };
- PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
- var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
- var indicesToDelete = [];
- var i;
- for (i = 0; i < _cam.length; i++) {
- var camera = _cam[i];
- var cameraName = camera.name;
- if (this._cameras.indexOf(camera) === -1) {
- this._cameras[cameraName] = camera;
- }
- else if (unique) {
- indicesToDelete.push(i);
- }
- }
- for (i = 0; i < indicesToDelete.length; i++) {
- cameras.splice(indicesToDelete[i], 1);
- }
- for (var renderEffectName in this._renderEffects) {
- this._renderEffects[renderEffectName]._attachCameras(_cam);
- }
- };
- PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
- var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
- for (var renderEffectName in this._renderEffects) {
- this._renderEffects[renderEffectName]._detachCameras(_cam);
- }
- for (var i = 0; i < _cam.length; i++) {
- this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
- }
- };
- PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
- var _this = this;
- var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
- var pass = null;
- var renderEffectName;
- for (renderEffectName in this._renderEffects) {
- pass = this._renderEffects[renderEffectName].getPass(passName);
- if (pass != null) {
- break;
- }
- }
- if (pass === null) {
- return;
- }
- for (renderEffectName in this._renderEffects) {
- this._renderEffects[renderEffectName]._disable(_cam);
- }
- pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
- for (var i = 0; i < _cam.length; i++) {
- var camera = _cam[i];
- var cameraName = camera.name;
- 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); });
- this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
- this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
- this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
- }
- };
- PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
- var _this = this;
- var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
- for (var i = 0; i < _cam.length; i++) {
- var camera = _cam[i];
- var cameraName = camera.name;
- 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); });
- this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
- }
- for (var renderEffectName in this._renderEffects) {
- this._renderEffects[renderEffectName]._enable(_cam);
- }
- };
- PostProcessRenderPipeline.prototype._update = function () {
- for (var renderEffectName in this._renderEffects) {
- this._renderEffects[renderEffectName]._update();
- }
- for (var i = 0; i < this._cameras.length; i++) {
- var cameraName = this._cameras[i].name;
- if (this._renderEffectsForIsolatedPass[cameraName]) {
- this._renderEffectsForIsolatedPass[cameraName]._update();
- }
- }
- };
- PostProcessRenderPipeline.prototype.dispose = function () {
- // Must be implemented by children
- };
- PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
- PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
- return PostProcessRenderPipeline;
- })();
- BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var PostProcessRenderPipelineManager = (function () {
- function PostProcessRenderPipelineManager() {
- this._renderPipelines = {};
- }
- PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
- this._renderPipelines[renderPipeline._name] = renderPipeline;
- };
- PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
- var renderPipeline = this._renderPipelines[renderPipelineName];
- if (!renderPipeline) {
- return;
- }
- renderPipeline._attachCameras(cameras, unique);
- };
- PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
- var renderPipeline = this._renderPipelines[renderPipelineName];
- if (!renderPipeline) {
- return;
- }
- renderPipeline._detachCameras(cameras);
- };
- PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
- var renderPipeline = this._renderPipelines[renderPipelineName];
- if (!renderPipeline) {
- return;
- }
- renderPipeline._enableEffect(renderEffectName, cameras);
- };
- PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
- var renderPipeline = this._renderPipelines[renderPipelineName];
- if (!renderPipeline) {
- return;
- }
- renderPipeline._disableEffect(renderEffectName, cameras);
- };
- PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
- var renderPipeline = this._renderPipelines[renderPipelineName];
- if (!renderPipeline) {
- return;
- }
- renderPipeline._enableDisplayOnlyPass(passName, cameras);
- };
- PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
- var renderPipeline = this._renderPipelines[renderPipelineName];
- if (!renderPipeline) {
- return;
- }
- renderPipeline._disableDisplayOnlyPass(cameras);
- };
- PostProcessRenderPipelineManager.prototype.update = function () {
- for (var renderPipelineName in this._renderPipelines) {
- var pipeline = this._renderPipelines[renderPipelineName];
- if (!pipeline.isSupported) {
- pipeline.dispose();
- delete this._renderPipelines[renderPipelineName];
- }
- else {
- pipeline._update();
- }
- }
- };
- return PostProcessRenderPipelineManager;
- })();
- BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var BoundingBoxRenderer = (function () {
- function BoundingBoxRenderer(scene) {
- this.frontColor = new BABYLON.Color3(1, 1, 1);
- this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
- this.showBackLines = true;
- this.renderList = new BABYLON.SmartArray(32);
- this._scene = scene;
- }
- BoundingBoxRenderer.prototype._prepareRessources = function () {
- if (this._colorShader) {
- return;
- }
- this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
- attributes: ["position"],
- uniforms: ["worldViewProjection", "color"]
- });
- var engine = this._scene.getEngine();
- var boxdata = BABYLON.VertexData.CreateBox(1.0);
- this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
- this._ib = 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]);
- };
- BoundingBoxRenderer.prototype.reset = function () {
- this.renderList.reset();
- };
- BoundingBoxRenderer.prototype.render = function () {
- if (this.renderList.length === 0) {
- return;
- }
- this._prepareRessources();
- if (!this._colorShader.isReady()) {
- return;
- }
- var engine = this._scene.getEngine();
- engine.setDepthWrite(false);
- this._colorShader._preBind();
- for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
- var boundingBox = this.renderList.data[boundingBoxIndex];
- var min = boundingBox.minimum;
- var max = boundingBox.maximum;
- var diff = max.subtract(min);
- var median = min.add(diff.scale(0.5));
- var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
- .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
- .multiply(boundingBox.getWorldMatrix());
- // VBOs
- engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
- if (this.showBackLines) {
- // Back
- engine.setDepthFunctionToGreaterOrEqual();
- this._scene.resetCachedMaterial();
- this._colorShader.setColor4("color", this.backColor.toColor4());
- this._colorShader.bind(worldMatrix);
- // Draw order
- engine.draw(false, 0, 24);
- }
- // Front
- engine.setDepthFunctionToLess();
- this._scene.resetCachedMaterial();
- this._colorShader.setColor4("color", this.frontColor.toColor4());
- this._colorShader.bind(worldMatrix);
- // Draw order
- engine.draw(false, 0, 24);
- }
- this._colorShader.unbind();
- engine.setDepthFunctionToLessOrEqual();
- engine.setDepthWrite(true);
- };
- BoundingBoxRenderer.prototype.dispose = function () {
- if (!this._colorShader) {
- return;
- }
- this._colorShader.dispose();
- this._vb.dispose();
- this._scene.getEngine()._releaseBuffer(this._ib);
- };
- return BoundingBoxRenderer;
- })();
- BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Condition = (function () {
- function Condition(actionManager) {
- this._actionManager = actionManager;
- }
- Condition.prototype.isValid = function () {
- return true;
- };
- Condition.prototype._getProperty = function (propertyPath) {
- return this._actionManager._getProperty(propertyPath);
- };
- Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
- return this._actionManager._getEffectiveTarget(target, propertyPath);
- };
- Condition.prototype.serialize = function () {
- };
- Condition.prototype._serialize = function (serializedCondition) {
- return {
- type: 2,
- children: [],
- name: serializedCondition.name,
- properties: serializedCondition.properties
- };
- };
- return Condition;
- })();
- BABYLON.Condition = Condition;
- var ValueCondition = (function (_super) {
- __extends(ValueCondition, _super);
- function ValueCondition(actionManager, target, propertyPath, value, operator) {
- if (operator === void 0) { operator = ValueCondition.IsEqual; }
- _super.call(this, actionManager);
- this.propertyPath = propertyPath;
- this.value = value;
- this.operator = operator;
- this._target = target;
- this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
- this._property = this._getProperty(this.propertyPath);
- }
- Object.defineProperty(ValueCondition, "IsEqual", {
- get: function () {
- return ValueCondition._IsEqual;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ValueCondition, "IsDifferent", {
- get: function () {
- return ValueCondition._IsDifferent;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ValueCondition, "IsGreater", {
- get: function () {
- return ValueCondition._IsGreater;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ValueCondition, "IsLesser", {
- get: function () {
- return ValueCondition._IsLesser;
- },
- enumerable: true,
- configurable: true
- });
- // Methods
- ValueCondition.prototype.isValid = function () {
- switch (this.operator) {
- case ValueCondition.IsGreater:
- return this._effectiveTarget[this._property] > this.value;
- case ValueCondition.IsLesser:
- return this._effectiveTarget[this._property] < this.value;
- case ValueCondition.IsEqual:
- case ValueCondition.IsDifferent:
- var check;
- if (this.value.equals) {
- check = this.value.equals(this._effectiveTarget[this._property]);
- }
- else {
- check = this.value === this._effectiveTarget[this._property];
- }
- return this.operator === ValueCondition.IsEqual ? check : !check;
- }
- return false;
- };
- ValueCondition.prototype.serialize = function () {
- return this._serialize({
- name: "ValueCondition",
- properties: [
- BABYLON.Action._GetTargetProperty(this._target),
- { name: "propertyPath", value: this.propertyPath },
- { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
- { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
- ]
- });
- };
- ValueCondition.GetOperatorName = function (operator) {
- switch (operator) {
- case ValueCondition._IsEqual: return "IsEqual";
- case ValueCondition._IsDifferent: return "IsDifferent";
- case ValueCondition._IsGreater: return "IsGreater";
- case ValueCondition._IsLesser: return "IsLesser";
- default: return "";
- }
- };
- // Statics
- ValueCondition._IsEqual = 0;
- ValueCondition._IsDifferent = 1;
- ValueCondition._IsGreater = 2;
- ValueCondition._IsLesser = 3;
- return ValueCondition;
- })(Condition);
- BABYLON.ValueCondition = ValueCondition;
- var PredicateCondition = (function (_super) {
- __extends(PredicateCondition, _super);
- function PredicateCondition(actionManager, predicate) {
- _super.call(this, actionManager);
- this.predicate = predicate;
- }
- PredicateCondition.prototype.isValid = function () {
- return this.predicate();
- };
- return PredicateCondition;
- })(Condition);
- BABYLON.PredicateCondition = PredicateCondition;
- var StateCondition = (function (_super) {
- __extends(StateCondition, _super);
- function StateCondition(actionManager, target, value) {
- _super.call(this, actionManager);
- this.value = value;
- this._target = target;
- }
- // Methods
- StateCondition.prototype.isValid = function () {
- return this._target.state === this.value;
- };
- StateCondition.prototype.serialize = function () {
- return this._serialize({
- name: "StateCondition",
- properties: [
- BABYLON.Action._GetTargetProperty(this._target),
- { name: "value", value: this.value }
- ]
- });
- };
- return StateCondition;
- })(Condition);
- BABYLON.StateCondition = StateCondition;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Action = (function () {
- function Action(triggerOptions, condition) {
- this.triggerOptions = triggerOptions;
- if (triggerOptions.parameter) {
- this.trigger = triggerOptions.trigger;
- this._triggerParameter = triggerOptions.parameter;
- }
- else {
- this.trigger = triggerOptions;
- }
- this._nextActiveAction = this;
- this._condition = condition;
- }
- // Methods
- Action.prototype._prepare = function () {
- };
- Action.prototype.getTriggerParameter = function () {
- return this._triggerParameter;
- };
- Action.prototype._executeCurrent = function (evt) {
- if (this._nextActiveAction._condition) {
- var condition = this._nextActiveAction._condition;
- var currentRenderId = this._actionManager.getScene().getRenderId();
- // We cache the current evaluation for the current frame
- if (condition._evaluationId === currentRenderId) {
- if (!condition._currentResult) {
- return;
- }
- }
- else {
- condition._evaluationId = currentRenderId;
- if (!condition.isValid()) {
- condition._currentResult = false;
- return;
- }
- condition._currentResult = true;
- }
- }
- this._nextActiveAction.execute(evt);
- this.skipToNextActiveAction();
- };
- Action.prototype.execute = function (evt) {
- };
- Action.prototype.skipToNextActiveAction = function () {
- if (this._nextActiveAction._child) {
- if (!this._nextActiveAction._child._actionManager) {
- this._nextActiveAction._child._actionManager = this._actionManager;
- }
- this._nextActiveAction = this._nextActiveAction._child;
- }
- else {
- this._nextActiveAction = this;
- }
- };
- Action.prototype.then = function (action) {
- this._child = action;
- action._actionManager = this._actionManager;
- action._prepare();
- return action;
- };
- Action.prototype._getProperty = function (propertyPath) {
- return this._actionManager._getProperty(propertyPath);
- };
- Action.prototype._getEffectiveTarget = function (target, propertyPath) {
- return this._actionManager._getEffectiveTarget(target, propertyPath);
- };
- Action.prototype.serialize = function (parent) {
- };
- // Called by BABYLON.Action objects in serialize(...). Internal use
- Action.prototype._serialize = function (serializedAction, parent) {
- var serializationObject = {
- type: 1,
- children: [],
- name: serializedAction.name,
- properties: serializedAction.properties || []
- };
- // Serialize child
- if (this._child) {
- this._child.serialize(serializationObject);
- }
- // Check if "this" has a condition
- if (this._condition) {
- var serializedCondition = this._condition.serialize();
- serializedCondition.children.push(serializationObject);
- if (parent) {
- parent.children.push(serializedCondition);
- }
- return serializedCondition;
- }
- if (parent) {
- parent.children.push(serializationObject);
- }
- return serializationObject;
- };
- Action._SerializeValueAsString = function (value) {
- if (typeof value === "number") {
- return value.toString();
- }
- if (typeof value === "boolean") {
- return value ? "true" : "false";
- }
- if (value instanceof BABYLON.Vector2) {
- return value.x + ", " + value.y;
- }
- if (value instanceof BABYLON.Vector3) {
- return value.x + ", " + value.y + ", " + value.z;
- }
- if (value instanceof BABYLON.Color3) {
- return value.r + ", " + value.g + ", " + value.b;
- }
- if (value instanceof BABYLON.Color4) {
- return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
- }
- return value; // string
- };
- Action._GetTargetProperty = function (target) {
- return {
- name: "target",
- targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
- : target instanceof BABYLON.Light ? "LightProperties"
- : target instanceof BABYLON.Camera ? "CameraProperties"
- : "SceneProperties",
- value: target instanceof BABYLON.Scene ? "Scene" : target.name
- };
- };
- return Action;
- })();
- BABYLON.Action = Action;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- /**
- * ActionEvent is the event beint sent when an action is triggered.
- */
- var ActionEvent = (function () {
- /**
- * @constructor
- * @param source The mesh or sprite that triggered the action.
- * @param pointerX The X mouse cursor position at the time of the event
- * @param pointerY The Y mouse cursor position at the time of the event
- * @param meshUnderPointer The mesh that is currently pointed at (can be null)
- * @param sourceEvent the original (browser) event that triggered the ActionEvent
- */
- function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
- this.source = source;
- this.pointerX = pointerX;
- this.pointerY = pointerY;
- this.meshUnderPointer = meshUnderPointer;
- this.sourceEvent = sourceEvent;
- this.additionalData = additionalData;
- }
- /**
- * Helper function to auto-create an ActionEvent from a source mesh.
- * @param source The source mesh that triggered the event
- * @param evt {Event} The original (browser) event
- */
- ActionEvent.CreateNew = function (source, evt, additionalData) {
- var scene = source.getScene();
- return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
- };
- /**
- * Helper function to auto-create an ActionEvent from a source mesh.
- * @param source The source sprite that triggered the event
- * @param scene Scene associated with the sprite
- * @param evt {Event} The original (browser) event
- */
- ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
- return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
- };
- /**
- * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
- * @param scene the scene where the event occurred
- * @param evt {Event} The original (browser) event
- */
- ActionEvent.CreateNewFromScene = function (scene, evt) {
- return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
- };
- return ActionEvent;
- })();
- BABYLON.ActionEvent = ActionEvent;
- /**
- * Action Manager manages all events to be triggered on a given mesh or the global scene.
- * A single scene can have many Action Managers to handle predefined actions on specific meshes.
- */
- var ActionManager = (function () {
- function ActionManager(scene) {
- // Members
- this.actions = new Array();
- this._scene = scene;
- scene._actionManagers.push(this);
- }
- Object.defineProperty(ActionManager, "NothingTrigger", {
- get: function () {
- return ActionManager._NothingTrigger;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ActionManager, "OnPickTrigger", {
- get: function () {
- return ActionManager._OnPickTrigger;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
- get: function () {
- return ActionManager._OnLeftPickTrigger;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ActionManager, "OnRightPickTrigger", {
- get: function () {
- return ActionManager._OnRightPickTrigger;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
- get: function () {
- return ActionManager._OnCenterPickTrigger;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ActionManager, "OnPickDownTrigger", {
- get: function () {
- return ActionManager._OnPickDownTrigger;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ActionManager, "OnPickUpTrigger", {
- get: function () {
- return ActionManager._OnPickUpTrigger;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ActionManager, "OnPickOutTrigger", {
- /// This trigger will only be raised if you also declared a OnPickDown
- get: function () {
- return ActionManager._OnPickOutTrigger;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ActionManager, "OnLongPressTrigger", {
- get: function () {
- return ActionManager._OnLongPressTrigger;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
- get: function () {
- return ActionManager._OnPointerOverTrigger;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
- get: function () {
- return ActionManager._OnPointerOutTrigger;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
- get: function () {
- return ActionManager._OnEveryFrameTrigger;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
- get: function () {
- return ActionManager._OnIntersectionEnterTrigger;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
- get: function () {
- return ActionManager._OnIntersectionExitTrigger;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
- get: function () {
- return ActionManager._OnKeyDownTrigger;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
- get: function () {
- return ActionManager._OnKeyUpTrigger;
- },
- enumerable: true,
- configurable: true
- });
- // Methods
- ActionManager.prototype.dispose = function () {
- var index = this._scene._actionManagers.indexOf(this);
- if (index > -1) {
- this._scene._actionManagers.splice(index, 1);
- }
- };
- ActionManager.prototype.getScene = function () {
- return this._scene;
- };
- /**
- * Does this action manager handles actions of any of the given triggers
- * @param {number[]} triggers - the triggers to be tested
- * @return {boolean} whether one (or more) of the triggers is handeled
- */
- ActionManager.prototype.hasSpecificTriggers = function (triggers) {
- for (var index = 0; index < this.actions.length; index++) {
- var action = this.actions[index];
- if (triggers.indexOf(action.trigger) > -1) {
- return true;
- }
- }
- return false;
- };
- /**
- * Does this action manager handles actions of a given trigger
- * @param {number} trigger - the trigger to be tested
- * @return {boolean} whether the trigger is handeled
- */
- ActionManager.prototype.hasSpecificTrigger = function (trigger) {
- for (var index = 0; index < this.actions.length; index++) {
- var action = this.actions[index];
- if (action.trigger === trigger) {
- return true;
- }
- }
- return false;
- };
- Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
- /**
- * Does this action manager has pointer triggers
- * @return {boolean} whether or not it has pointer triggers
- */
- get: function () {
- for (var index = 0; index < this.actions.length; index++) {
- var action = this.actions[index];
- if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
- return true;
- }
- }
- return false;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
- /**
- * Does this action manager has pick triggers
- * @return {boolean} whether or not it has pick triggers
- */
- get: function () {
- for (var index = 0; index < this.actions.length; index++) {
- var action = this.actions[index];
- if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
- return true;
- }
- }
- return false;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Registers an action to this action manager
- * @param {BABYLON.Action} action - the action to be registered
- * @return {BABYLON.Action} the action amended (prepared) after registration
- */
- ActionManager.prototype.registerAction = function (action) {
- if (action.trigger === ActionManager.OnEveryFrameTrigger) {
- if (this.getScene().actionManager !== this) {
- BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
- return null;
- }
- }
- this.actions.push(action);
- action._actionManager = this;
- action._prepare();
- return action;
- };
- /**
- * Process a specific trigger
- * @param {number} trigger - the trigger to process
- * @param evt {BABYLON.ActionEvent} the event details to be processed
- */
- ActionManager.prototype.processTrigger = function (trigger, evt) {
- for (var index = 0; index < this.actions.length; index++) {
- var action = this.actions[index];
- if (action.trigger === trigger) {
- if (trigger === ActionManager.OnKeyUpTrigger
- || trigger === ActionManager.OnKeyDownTrigger) {
- var parameter = action.getTriggerParameter();
- if (parameter) {
- var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
- var actualkey = String.fromCharCode(unicode).toLowerCase();
- if (actualkey !== parameter.toLowerCase()) {
- continue;
- }
- }
- }
- action._executeCurrent(evt);
- }
- }
- };
- ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
- var properties = propertyPath.split(".");
- for (var index = 0; index < properties.length - 1; index++) {
- target = target[properties[index]];
- }
- return target;
- };
- ActionManager.prototype._getProperty = function (propertyPath) {
- var properties = propertyPath.split(".");
- return properties[properties.length - 1];
- };
- ActionManager.prototype.serialize = function (name) {
- var root = {
- children: [],
- name: name,
- type: 3,
- properties: [] // Empty for root but required
- };
- for (var i = 0; i < this.actions.length; i++) {
- var triggerObject = {
- type: 0,
- children: [],
- name: ActionManager.GetTriggerName(this.actions[i].trigger),
- properties: []
- };
- var triggerOptions = this.actions[i].triggerOptions;
- if (triggerOptions && typeof triggerOptions !== "number") {
- if (triggerOptions.parameter instanceof BABYLON.Node) {
- triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
- }
- else {
- triggerObject.properties.push({ name: "parameter", targetType: null, value: triggerOptions.parameter });
- }
- }
- // Serialize child action, recursively
- this.actions[i].serialize(triggerObject);
- // Add serialized trigger
- root.children.push(triggerObject);
- }
- return root;
- };
- ActionManager.Parse = function (parsedActions, object, scene) {
- var actionManager = new BABYLON.ActionManager(scene);
- if (object === null)
- scene.actionManager = actionManager;
- else
- object.actionManager = actionManager;
- // instanciate a new object
- var instanciate = function (name, params) {
- var newInstance = Object.create(BABYLON[name].prototype);
- newInstance.constructor.apply(newInstance, params);
- return newInstance;
- };
- var parseParameter = function (name, value, target, propertyPath) {
- if (propertyPath === null) {
- // String, boolean or float
- var floatValue = parseFloat(value);
- if (value === "true" || value === "false")
- return value === "true";
- else
- return isNaN(floatValue) ? value : floatValue;
- }
- var effectiveTarget = propertyPath.split(".");
- var values = value.split(",");
- // Get effective Target
- for (var i = 0; i < effectiveTarget.length; i++) {
- target = target[effectiveTarget[i]];
- }
- // Return appropriate value with its type
- if (typeof (target) === "boolean")
- return values[0] === "true";
- if (typeof (target) === "string")
- return values[0];
- // Parameters with multiple values such as Vector3 etc.
- var split = new Array();
- for (var i = 0; i < values.length; i++)
- split.push(parseFloat(values[i]));
- if (target instanceof BABYLON.Vector3)
- return BABYLON.Vector3.FromArray(split);
- if (target instanceof BABYLON.Vector4)
- return BABYLON.Vector4.FromArray(split);
- if (target instanceof BABYLON.Color3)
- return BABYLON.Color3.FromArray(split);
- if (target instanceof BABYLON.Color4)
- return BABYLON.Color4.FromArray(split);
- return parseFloat(values[0]);
- };
- // traverse graph per trigger
- var traverse = function (parsedAction, trigger, condition, action, combineArray) {
- if (combineArray === void 0) { combineArray = null; }
- if (parsedAction.detached)
- return;
- var parameters = new Array();
- var target = null;
- var propertyPath = null;
- var combine = parsedAction.combine && parsedAction.combine.length > 0;
- // Parameters
- if (parsedAction.type === 2)
- parameters.push(actionManager);
- else
- parameters.push(trigger);
- if (combine) {
- var actions = new Array();
- for (var j = 0; j < parsedAction.combine.length; j++) {
- traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
- }
- parameters.push(actions);
- }
- else {
- for (var i = 0; i < parsedAction.properties.length; i++) {
- var value = parsedAction.properties[i].value;
- var name = parsedAction.properties[i].name;
- var targetType = parsedAction.properties[i].targetType;
- if (name === "target")
- if (targetType !== null && targetType === "SceneProperties")
- value = target = scene;
- else
- value = target = scene.getNodeByName(value);
- else if (name === "parent")
- value = scene.getNodeByName(value);
- else if (name === "sound")
- value = scene.getSoundByName(value);
- else if (name !== "propertyPath") {
- if (parsedAction.type === 2 && name === "operator")
- value = BABYLON.ValueCondition[value];
- else
- value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
- }
- else {
- propertyPath = value;
- }
- parameters.push(value);
- }
- }
- if (combineArray === null) {
- parameters.push(condition);
- }
- else {
- parameters.push(null);
- }
- // If interpolate value action
- if (parsedAction.name === "InterpolateValueAction") {
- var param = parameters[parameters.length - 2];
- parameters[parameters.length - 1] = param;
- parameters[parameters.length - 2] = condition;
- }
- // Action or condition(s) and not CombineAction
- var newAction = instanciate(parsedAction.name, parameters);
- if (newAction instanceof BABYLON.Condition && condition !== null) {
- var nothing = new BABYLON.DoNothingAction(trigger, condition);
- if (action)
- action.then(nothing);
- else
- actionManager.registerAction(nothing);
- action = nothing;
- }
- if (combineArray === null) {
- if (newAction instanceof BABYLON.Condition) {
- condition = newAction;
- newAction = action;
- }
- else {
- condition = null;
- if (action)
- action.then(newAction);
- else
- actionManager.registerAction(newAction);
- }
- }
- else {
- combineArray.push(newAction);
- }
- for (var i = 0; i < parsedAction.children.length; i++)
- traverse(parsedAction.children[i], trigger, condition, newAction, null);
- };
- // triggers
- for (var i = 0; i < parsedActions.children.length; i++) {
- var triggerParams;
- var trigger = parsedActions.children[i];
- if (trigger.properties.length > 0) {
- var param = trigger.properties[0].value;
- var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
- triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
- }
- else
- triggerParams = BABYLON.ActionManager[trigger.name];
- for (var j = 0; j < trigger.children.length; j++) {
- if (!trigger.detached)
- traverse(trigger.children[j], triggerParams, null, null);
- }
- }
- };
- ActionManager.GetTriggerName = function (trigger) {
- switch (trigger) {
- case 0: return "NothingTrigger";
- case 1: return "OnPickTrigger";
- case 2: return "OnLeftPickTrigger";
- case 3: return "OnRightPickTrigger";
- case 4: return "OnCenterPickTrigger";
- case 5: return "OnPickDownTrigger";
- case 6: return "OnPickUpTrigger";
- case 7: return "OnLongPressTrigger";
- case 8: return "OnPointerOverTrigger";
- case 9: return "OnPointerOutTrigger";
- case 10: return "OnEveryFrameTrigger";
- case 11: return "OnIntersectionEnterTrigger";
- case 12: return "OnIntersectionExitTrigger";
- case 13: return "OnKeyDownTrigger";
- case 14: return "OnKeyUpTrigger";
- case 15: return "OnPickOutTrigger";
- default: return "";
- }
- };
- // Statics
- ActionManager._NothingTrigger = 0;
- ActionManager._OnPickTrigger = 1;
- ActionManager._OnLeftPickTrigger = 2;
- ActionManager._OnRightPickTrigger = 3;
- ActionManager._OnCenterPickTrigger = 4;
- ActionManager._OnPickDownTrigger = 5;
- ActionManager._OnPickUpTrigger = 6;
- ActionManager._OnLongPressTrigger = 7;
- ActionManager._OnPointerOverTrigger = 8;
- ActionManager._OnPointerOutTrigger = 9;
- ActionManager._OnEveryFrameTrigger = 10;
- ActionManager._OnIntersectionEnterTrigger = 11;
- ActionManager._OnIntersectionExitTrigger = 12;
- ActionManager._OnKeyDownTrigger = 13;
- ActionManager._OnKeyUpTrigger = 14;
- ActionManager._OnPickOutTrigger = 15;
- ActionManager.DragMovementThreshold = 10; // in pixels
- ActionManager.LongPressDelay = 500; // in milliseconds
- return ActionManager;
- })();
- BABYLON.ActionManager = ActionManager;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var InterpolateValueAction = (function (_super) {
- __extends(InterpolateValueAction, _super);
- function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
- if (duration === void 0) { duration = 1000; }
- _super.call(this, triggerOptions, condition);
- this.propertyPath = propertyPath;
- this.value = value;
- this.duration = duration;
- this.stopOtherAnimations = stopOtherAnimations;
- this.onInterpolationDone = onInterpolationDone;
- this._target = this._effectiveTarget = target;
- }
- InterpolateValueAction.prototype._prepare = function () {
- this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
- this._property = this._getProperty(this.propertyPath);
- };
- InterpolateValueAction.prototype.execute = function () {
- var scene = this._actionManager.getScene();
- var keys = [
- {
- frame: 0,
- value: this._effectiveTarget[this._property]
- }, {
- frame: 100,
- value: this.value
- }
- ];
- var dataType;
- if (typeof this.value === "number") {
- dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
- }
- else if (this.value instanceof BABYLON.Color3) {
- dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
- }
- else if (this.value instanceof BABYLON.Vector3) {
- dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
- }
- else if (this.value instanceof BABYLON.Matrix) {
- dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
- }
- else if (this.value instanceof BABYLON.Quaternion) {
- dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
- }
- else {
- BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
- return;
- }
- var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
- animation.setKeys(keys);
- if (this.stopOtherAnimations) {
- scene.stopAnimation(this._effectiveTarget);
- }
- scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
- };
- InterpolateValueAction.prototype.serialize = function (parent) {
- return _super.prototype._serialize.call(this, {
- name: "InterpolateValueAction",
- properties: [
- BABYLON.Action._GetTargetProperty(this._target),
- { name: "propertyPath", value: this.propertyPath },
- { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
- { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
- { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
- ]
- }, parent);
- };
- return InterpolateValueAction;
- })(BABYLON.Action);
- BABYLON.InterpolateValueAction = InterpolateValueAction;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var SwitchBooleanAction = (function (_super) {
- __extends(SwitchBooleanAction, _super);
- function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
- _super.call(this, triggerOptions, condition);
- this.propertyPath = propertyPath;
- this._target = this._effectiveTarget = target;
- }
- SwitchBooleanAction.prototype._prepare = function () {
- this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
- this._property = this._getProperty(this.propertyPath);
- };
- SwitchBooleanAction.prototype.execute = function () {
- this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
- };
- SwitchBooleanAction.prototype.serialize = function (parent) {
- return _super.prototype._serialize.call(this, {
- name: "SwitchBooleanAction",
- properties: [
- BABYLON.Action._GetTargetProperty(this._target),
- { name: "propertyPath", value: this.propertyPath }
- ]
- }, parent);
- };
- return SwitchBooleanAction;
- })(BABYLON.Action);
- BABYLON.SwitchBooleanAction = SwitchBooleanAction;
- var SetStateAction = (function (_super) {
- __extends(SetStateAction, _super);
- function SetStateAction(triggerOptions, target, value, condition) {
- _super.call(this, triggerOptions, condition);
- this.value = value;
- this._target = target;
- }
- SetStateAction.prototype.execute = function () {
- this._target.state = this.value;
- };
- SetStateAction.prototype.serialize = function (parent) {
- return _super.prototype._serialize.call(this, {
- name: "SetStateAction",
- properties: [
- BABYLON.Action._GetTargetProperty(this._target),
- { name: "value", value: this.value }
- ]
- }, parent);
- };
- return SetStateAction;
- })(BABYLON.Action);
- BABYLON.SetStateAction = SetStateAction;
- var SetValueAction = (function (_super) {
- __extends(SetValueAction, _super);
- function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
- _super.call(this, triggerOptions, condition);
- this.propertyPath = propertyPath;
- this.value = value;
- this._target = this._effectiveTarget = target;
- }
- SetValueAction.prototype._prepare = function () {
- this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
- this._property = this._getProperty(this.propertyPath);
- };
- SetValueAction.prototype.execute = function () {
- this._effectiveTarget[this._property] = this.value;
- };
- SetValueAction.prototype.serialize = function (parent) {
- return _super.prototype._serialize.call(this, {
- name: "SetValueAction",
- properties: [
- BABYLON.Action._GetTargetProperty(this._target),
- { name: "propertyPath", value: this.propertyPath },
- { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
- ]
- }, parent);
- };
- return SetValueAction;
- })(BABYLON.Action);
- BABYLON.SetValueAction = SetValueAction;
- var IncrementValueAction = (function (_super) {
- __extends(IncrementValueAction, _super);
- function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
- _super.call(this, triggerOptions, condition);
- this.propertyPath = propertyPath;
- this.value = value;
- this._target = this._effectiveTarget = target;
- }
- IncrementValueAction.prototype._prepare = function () {
- this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
- this._property = this._getProperty(this.propertyPath);
- if (typeof this._effectiveTarget[this._property] !== "number") {
- BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
- }
- };
- IncrementValueAction.prototype.execute = function () {
- this._effectiveTarget[this._property] += this.value;
- };
- IncrementValueAction.prototype.serialize = function (parent) {
- return _super.prototype._serialize.call(this, {
- name: "IncrementValueAction",
- properties: [
- BABYLON.Action._GetTargetProperty(this._target),
- { name: "propertyPath", value: this.propertyPath },
- { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
- ]
- }, parent);
- };
- return IncrementValueAction;
- })(BABYLON.Action);
- BABYLON.IncrementValueAction = IncrementValueAction;
- var PlayAnimationAction = (function (_super) {
- __extends(PlayAnimationAction, _super);
- function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
- _super.call(this, triggerOptions, condition);
- this.from = from;
- this.to = to;
- this.loop = loop;
- this._target = target;
- }
- PlayAnimationAction.prototype._prepare = function () {
- };
- PlayAnimationAction.prototype.execute = function () {
- var scene = this._actionManager.getScene();
- scene.beginAnimation(this._target, this.from, this.to, this.loop);
- };
- PlayAnimationAction.prototype.serialize = function (parent) {
- return _super.prototype._serialize.call(this, {
- name: "PlayAnimationAction",
- properties: [
- BABYLON.Action._GetTargetProperty(this._target),
- { name: "from", value: String(this.from) },
- { name: "to", value: String(this.to) },
- { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
- ]
- }, parent);
- };
- return PlayAnimationAction;
- })(BABYLON.Action);
- BABYLON.PlayAnimationAction = PlayAnimationAction;
- var StopAnimationAction = (function (_super) {
- __extends(StopAnimationAction, _super);
- function StopAnimationAction(triggerOptions, target, condition) {
- _super.call(this, triggerOptions, condition);
- this._target = target;
- }
- StopAnimationAction.prototype._prepare = function () {
- };
- StopAnimationAction.prototype.execute = function () {
- var scene = this._actionManager.getScene();
- scene.stopAnimation(this._target);
- };
- StopAnimationAction.prototype.serialize = function (parent) {
- return _super.prototype._serialize.call(this, {
- name: "StopAnimationAction",
- properties: [BABYLON.Action._GetTargetProperty(this._target)]
- }, parent);
- };
- return StopAnimationAction;
- })(BABYLON.Action);
- BABYLON.StopAnimationAction = StopAnimationAction;
- var DoNothingAction = (function (_super) {
- __extends(DoNothingAction, _super);
- function DoNothingAction(triggerOptions, condition) {
- if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
- _super.call(this, triggerOptions, condition);
- }
- DoNothingAction.prototype.execute = function () {
- };
- DoNothingAction.prototype.serialize = function (parent) {
- return _super.prototype._serialize.call(this, {
- name: "DoNothingAction",
- properties: []
- }, parent);
- };
- return DoNothingAction;
- })(BABYLON.Action);
- BABYLON.DoNothingAction = DoNothingAction;
- var CombineAction = (function (_super) {
- __extends(CombineAction, _super);
- function CombineAction(triggerOptions, children, condition) {
- _super.call(this, triggerOptions, condition);
- this.children = children;
- }
- CombineAction.prototype._prepare = function () {
- for (var index = 0; index < this.children.length; index++) {
- this.children[index]._actionManager = this._actionManager;
- this.children[index]._prepare();
- }
- };
- CombineAction.prototype.execute = function (evt) {
- for (var index = 0; index < this.children.length; index++) {
- this.children[index].execute(evt);
- }
- };
- CombineAction.prototype.serialize = function (parent) {
- var serializationObject = _super.prototype._serialize.call(this, {
- name: "CombineAction",
- properties: [],
- combine: []
- }, parent);
- for (var i = 0; i < this.children.length; i++) {
- serializationObject.combine.push(this.children[i].serialize(null));
- }
- return serializationObject;
- };
- return CombineAction;
- })(BABYLON.Action);
- BABYLON.CombineAction = CombineAction;
- var ExecuteCodeAction = (function (_super) {
- __extends(ExecuteCodeAction, _super);
- function ExecuteCodeAction(triggerOptions, func, condition) {
- _super.call(this, triggerOptions, condition);
- this.func = func;
- }
- ExecuteCodeAction.prototype.execute = function (evt) {
- this.func(evt);
- };
- return ExecuteCodeAction;
- })(BABYLON.Action);
- BABYLON.ExecuteCodeAction = ExecuteCodeAction;
- var SetParentAction = (function (_super) {
- __extends(SetParentAction, _super);
- function SetParentAction(triggerOptions, target, parent, condition) {
- _super.call(this, triggerOptions, condition);
- this._target = target;
- this._parent = parent;
- }
- SetParentAction.prototype._prepare = function () {
- };
- SetParentAction.prototype.execute = function () {
- if (this._target.parent === this._parent) {
- return;
- }
- var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
- invertParentWorldMatrix.invert();
- this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
- this._target.parent = this._parent;
- };
- SetParentAction.prototype.serialize = function (parent) {
- return _super.prototype._serialize.call(this, {
- name: "SetParentAction",
- properties: [
- BABYLON.Action._GetTargetProperty(this._target),
- BABYLON.Action._GetTargetProperty(this._parent),
- ]
- }, parent);
- };
- return SetParentAction;
- })(BABYLON.Action);
- BABYLON.SetParentAction = SetParentAction;
- var PlaySoundAction = (function (_super) {
- __extends(PlaySoundAction, _super);
- function PlaySoundAction(triggerOptions, sound, condition) {
- _super.call(this, triggerOptions, condition);
- this._sound = sound;
- }
- PlaySoundAction.prototype._prepare = function () {
- };
- PlaySoundAction.prototype.execute = function () {
- if (this._sound !== undefined)
- this._sound.play();
- };
- PlaySoundAction.prototype.serialize = function (parent) {
- return _super.prototype._serialize.call(this, {
- name: "PlaySoundAction",
- properties: [{ name: "sound", value: this._sound.name }]
- }, parent);
- };
- return PlaySoundAction;
- })(BABYLON.Action);
- BABYLON.PlaySoundAction = PlaySoundAction;
- var StopSoundAction = (function (_super) {
- __extends(StopSoundAction, _super);
- function StopSoundAction(triggerOptions, sound, condition) {
- _super.call(this, triggerOptions, condition);
- this._sound = sound;
- }
- StopSoundAction.prototype._prepare = function () {
- };
- StopSoundAction.prototype.execute = function () {
- if (this._sound !== undefined)
- this._sound.stop();
- };
- StopSoundAction.prototype.serialize = function (parent) {
- return _super.prototype._serialize.call(this, {
- name: "StopSoundAction",
- properties: [{ name: "sound", value: this._sound.name }]
- }, parent);
- };
- return StopSoundAction;
- })(BABYLON.Action);
- BABYLON.StopSoundAction = StopSoundAction;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Geometry = (function () {
- function Geometry(id, scene, vertexData, updatable, mesh) {
- this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
- this._totalVertices = 0;
- this._isDisposed = false;
- this.id = id;
- this._engine = scene.getEngine();
- this._meshes = [];
- this._scene = scene;
- //Init vertex buffer cache
- this._vertexBuffers = {};
- this._indices = [];
- // vertexData
- if (vertexData) {
- this.setAllVerticesData(vertexData, updatable);
- }
- else {
- this._totalVertices = 0;
- this._indices = [];
- }
- // applyToMesh
- if (mesh) {
- if (mesh instanceof BABYLON.LinesMesh) {
- this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
- this.updateExtend();
- }
- this.applyToMesh(mesh);
- mesh.computeWorldMatrix(true);
- }
- }
- Object.defineProperty(Geometry.prototype, "boundingBias", {
- /**
- * 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
- * @returns The Bias Vector
- */
- get: function () {
- return this._boundingBias;
- },
- set: function (value) {
- if (this._boundingBias && this._boundingBias.equals(value)) {
- return;
- }
- this._boundingBias = value.clone();
- this.updateBoundingInfo(true, null);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Geometry.prototype, "extend", {
- get: function () {
- return this._extend;
- },
- enumerable: true,
- configurable: true
- });
- Geometry.prototype.getScene = function () {
- return this._scene;
- };
- Geometry.prototype.getEngine = function () {
- return this._engine;
- };
- Geometry.prototype.isReady = function () {
- return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
- };
- Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
- vertexData.applyToGeometry(this, updatable);
- this.notifyUpdate();
- };
- Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
- if (this._vertexBuffers[kind]) {
- this._vertexBuffers[kind].dispose();
- }
- this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
- if (kind === BABYLON.VertexBuffer.PositionKind) {
- stride = this._vertexBuffers[kind].getStrideSize();
- this._totalVertices = data.length / stride;
- this.updateExtend(data);
- var meshes = this._meshes;
- var numOfMeshes = meshes.length;
- for (var index = 0; index < numOfMeshes; index++) {
- var mesh = meshes[index];
- mesh._resetPointsArrayCache();
- mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
- mesh._createGlobalSubMesh();
- mesh.computeWorldMatrix(true);
- }
- }
- this.notifyUpdate(kind);
- };
- Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
- var vertexBuffer = this.getVertexBuffer(kind);
- if (!vertexBuffer) {
- return;
- }
- vertexBuffer.updateDirectly(data, offset);
- this.notifyUpdate(kind);
- };
- Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
- var vertexBuffer = this.getVertexBuffer(kind);
- if (!vertexBuffer) {
- return;
- }
- vertexBuffer.update(data);
- if (kind === BABYLON.VertexBuffer.PositionKind) {
- var stride = vertexBuffer.getStrideSize();
- this._totalVertices = data.length / stride;
- this.updateBoundingInfo(updateExtends, data);
- }
- this.notifyUpdate(kind);
- };
- Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
- if (updateExtends) {
- this.updateExtend(data);
- }
- var meshes = this._meshes;
- var numOfMeshes = meshes.length;
- for (var index = 0; index < numOfMeshes; index++) {
- var mesh = meshes[index];
- mesh._resetPointsArrayCache();
- if (updateExtends) {
- mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
- for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
- var subMesh = mesh.subMeshes[subIndex];
- subMesh.refreshBoundingInfo();
- }
- }
- }
- };
- Geometry.prototype.getTotalVertices = function () {
- if (!this.isReady()) {
- return 0;
- }
- return this._totalVertices;
- };
- Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
- var vertexBuffer = this.getVertexBuffer(kind);
- if (!vertexBuffer) {
- return null;
- }
- var orig = vertexBuffer.getData();
- if (!copyWhenShared || this._meshes.length === 1) {
- return orig;
- }
- else {
- var len = orig.length;
- var copy = [];
- for (var i = 0; i < len; i++) {
- copy.push(orig[i]);
- }
- return copy;
- }
- };
- Geometry.prototype.getVertexBuffer = function (kind) {
- if (!this.isReady()) {
- return null;
- }
- return this._vertexBuffers[kind];
- };
- Geometry.prototype.getVertexBuffers = function () {
- if (!this.isReady()) {
- return null;
- }
- return this._vertexBuffers;
- };
- Geometry.prototype.isVerticesDataPresent = function (kind) {
- if (!this._vertexBuffers) {
- if (this._delayInfo) {
- return this._delayInfo.indexOf(kind) !== -1;
- }
- return false;
- }
- return this._vertexBuffers[kind] !== undefined;
- };
- Geometry.prototype.getVerticesDataKinds = function () {
- var result = [];
- var kind;
- if (!this._vertexBuffers && this._delayInfo) {
- for (kind in this._delayInfo) {
- result.push(kind);
- }
- }
- else {
- for (kind in this._vertexBuffers) {
- result.push(kind);
- }
- }
- return result;
- };
- Geometry.prototype.setIndices = function (indices, totalVertices) {
- if (this._indexBuffer) {
- this._engine._releaseBuffer(this._indexBuffer);
- }
- this._indices = indices;
- if (this._meshes.length !== 0 && this._indices) {
- this._indexBuffer = this._engine.createIndexBuffer(this._indices);
- }
- if (totalVertices !== undefined) {
- this._totalVertices = totalVertices;
- }
- var meshes = this._meshes;
- var numOfMeshes = meshes.length;
- for (var index = 0; index < numOfMeshes; index++) {
- meshes[index]._createGlobalSubMesh();
- }
- this.notifyUpdate();
- };
- Geometry.prototype.getTotalIndices = function () {
- if (!this.isReady()) {
- return 0;
- }
- return this._indices.length;
- };
- Geometry.prototype.getIndices = function (copyWhenShared) {
- if (!this.isReady()) {
- return null;
- }
- var orig = this._indices;
- if (!copyWhenShared || this._meshes.length === 1) {
- return orig;
- }
- else {
- var len = orig.length;
- var copy = [];
- for (var i = 0; i < len; i++) {
- copy.push(orig[i]);
- }
- return copy;
- }
- };
- Geometry.prototype.getIndexBuffer = function () {
- if (!this.isReady()) {
- return null;
- }
- return this._indexBuffer;
- };
- Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
- var meshes = this._meshes;
- var index = meshes.indexOf(mesh);
- if (index === -1) {
- return;
- }
- for (var kind in this._vertexBuffers) {
- this._vertexBuffers[kind].dispose();
- }
- if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
- this._indexBuffer = null;
- }
- meshes.splice(index, 1);
- mesh._geometry = null;
- if (meshes.length === 0 && shouldDispose) {
- this.dispose();
- }
- };
- Geometry.prototype.applyToMesh = function (mesh) {
- if (mesh._geometry === this) {
- return;
- }
- var previousGeometry = mesh._geometry;
- if (previousGeometry) {
- previousGeometry.releaseForMesh(mesh);
- }
- var meshes = this._meshes;
- // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
- mesh._geometry = this;
- this._scene.pushGeometry(this);
- meshes.push(mesh);
- if (this.isReady()) {
- this._applyToMesh(mesh);
- }
- else {
- mesh._boundingInfo = this._boundingInfo;
- }
- };
- Geometry.prototype.updateExtend = function (data) {
- if (data === void 0) { data = null; }
- if (!data) {
- data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
- }
- this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias);
- };
- Geometry.prototype._applyToMesh = function (mesh) {
- var numOfMeshes = this._meshes.length;
- // vertexBuffers
- for (var kind in this._vertexBuffers) {
- if (numOfMeshes === 1) {
- this._vertexBuffers[kind].create();
- }
- this._vertexBuffers[kind]._buffer.references = numOfMeshes;
- if (kind === BABYLON.VertexBuffer.PositionKind) {
- mesh._resetPointsArrayCache();
- if (!this._extend) {
- this.updateExtend(this._vertexBuffers[kind].getData());
- }
- mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
- mesh._createGlobalSubMesh();
- //bounding info was just created again, world matrix should be applied again.
- mesh._updateBoundingInfo();
- }
- }
- // indexBuffer
- if (numOfMeshes === 1 && this._indices) {
- this._indexBuffer = this._engine.createIndexBuffer(this._indices);
- }
- if (this._indexBuffer) {
- this._indexBuffer.references = numOfMeshes;
- }
- };
- Geometry.prototype.notifyUpdate = function (kind) {
- if (this.onGeometryUpdated) {
- this.onGeometryUpdated(this, kind);
- }
- };
- Geometry.prototype.load = function (scene, onLoaded) {
- var _this = this;
- if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
- return;
- }
- if (this.isReady()) {
- if (onLoaded) {
- onLoaded();
- }
- return;
- }
- this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
- scene._addPendingData(this);
- BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
- _this._delayLoadingFunction(JSON.parse(data), _this);
- _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
- _this._delayInfo = [];
- scene._removePendingData(_this);
- var meshes = _this._meshes;
- var numOfMeshes = meshes.length;
- for (var index = 0; index < numOfMeshes; index++) {
- _this._applyToMesh(meshes[index]);
- }
- if (onLoaded) {
- onLoaded();
- }
- }, function () { }, scene.database);
- };
- Geometry.prototype.isDisposed = function () {
- return this._isDisposed;
- };
- Geometry.prototype.dispose = function () {
- var meshes = this._meshes;
- var numOfMeshes = meshes.length;
- var index;
- for (index = 0; index < numOfMeshes; index++) {
- this.releaseForMesh(meshes[index]);
- }
- this._meshes = [];
- for (var kind in this._vertexBuffers) {
- this._vertexBuffers[kind].dispose();
- }
- this._vertexBuffers = [];
- this._totalVertices = 0;
- if (this._indexBuffer) {
- this._engine._releaseBuffer(this._indexBuffer);
- }
- this._indexBuffer = null;
- this._indices = [];
- this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
- this.delayLoadingFile = null;
- this._delayLoadingFunction = null;
- this._delayInfo = [];
- this._boundingInfo = null;
- this._scene.removeGeometry(this);
- this._isDisposed = true;
- };
- Geometry.prototype.copy = function (id) {
- var vertexData = new BABYLON.VertexData();
- vertexData.indices = [];
- var indices = this.getIndices();
- for (var index = 0; index < indices.length; index++) {
- vertexData.indices.push(indices[index]);
- }
- var updatable = false;
- var stopChecking = false;
- var kind;
- for (kind in this._vertexBuffers) {
- // using slice() to make a copy of the array and not just reference it
- var data = this.getVerticesData(kind);
- if (data instanceof Float32Array) {
- vertexData.set(new Float32Array(data), kind);
- }
- else {
- vertexData.set(data.slice(0), kind);
- }
- if (!stopChecking) {
- updatable = this.getVertexBuffer(kind).isUpdatable();
- stopChecking = !updatable;
- }
- }
- var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
- geometry.delayLoadState = this.delayLoadState;
- geometry.delayLoadingFile = this.delayLoadingFile;
- geometry._delayLoadingFunction = this._delayLoadingFunction;
- for (kind in this._delayInfo) {
- geometry._delayInfo = geometry._delayInfo || [];
- geometry._delayInfo.push(kind);
- }
- // Bounding info
- geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
- return geometry;
- };
- Geometry.prototype.serialize = function () {
- var serializationObject = {};
- serializationObject.id = this.id;
- if (BABYLON.Tags.HasTags(this)) {
- serializationObject.tags = BABYLON.Tags.GetTags(this);
- }
- return serializationObject;
- };
- Geometry.prototype.serializeVerticeData = function () {
- var serializationObject = this.serialize();
- if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
- serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- }
- if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
- serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
- }
- if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
- serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
- }
- if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
- serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
- }
- if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
- serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
- }
- if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
- serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
- }
- if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
- serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
- }
- if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
- serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
- }
- if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
- serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
- }
- if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
- serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
- serializationObject.matricesIndices._isExpanded = true;
- }
- if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
- serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
- }
- serializationObject.indices = this.getIndices();
- return serializationObject;
- };
- // Statics
- Geometry.ExtractFromMesh = function (mesh, id) {
- var geometry = mesh._geometry;
- if (!geometry) {
- return null;
- }
- return geometry.copy(id);
- };
- // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
- // be aware Math.random() could cause collisions
- Geometry.RandomId = function () {
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
- var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
- return v.toString(16);
- });
- };
- Geometry.ImportGeometry = function (parsedGeometry, mesh) {
- var scene = mesh.getScene();
- // Geometry
- var geometryId = parsedGeometry.geometryId;
- if (geometryId) {
- var geometry = scene.getGeometryByID(geometryId);
- if (geometry) {
- geometry.applyToMesh(mesh);
- }
- }
- else if (parsedGeometry instanceof ArrayBuffer) {
- var binaryInfo = mesh._binaryInfo;
- if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
- var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
- mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
- }
- if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
- var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
- mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
- }
- if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
- var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
- mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
- }
- if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
- var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
- mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
- }
- if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
- var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
- mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
- }
- if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
- var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
- mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
- }
- if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
- var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
- mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
- }
- if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
- var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
- mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
- }
- if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
- var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
- mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
- }
- if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
- var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
- mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
- }
- if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
- var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
- mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
- }
- if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
- var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
- mesh.setIndices(indicesData);
- }
- if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
- var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
- mesh.subMeshes = [];
- for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
- var materialIndex = subMeshesData[(i * 5) + 0];
- var verticesStart = subMeshesData[(i * 5) + 1];
- var verticesCount = subMeshesData[(i * 5) + 2];
- var indexStart = subMeshesData[(i * 5) + 3];
- var indexCount = subMeshesData[(i * 5) + 4];
- var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
- }
- }
- }
- else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
- mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
- mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
- if (parsedGeometry.uvs) {
- mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
- }
- if (parsedGeometry.uvs2) {
- mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
- }
- if (parsedGeometry.uvs3) {
- mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
- }
- if (parsedGeometry.uvs4) {
- mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
- }
- if (parsedGeometry.uvs5) {
- mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
- }
- if (parsedGeometry.uvs6) {
- mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
- }
- if (parsedGeometry.colors) {
- mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
- }
- if (parsedGeometry.matricesIndices) {
- if (!parsedGeometry.matricesIndices._isExpanded) {
- var floatIndices = [];
- for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
- var matricesIndex = parsedGeometry.matricesIndices[i];
- floatIndices.push(matricesIndex & 0x000000FF);
- floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
- floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
- floatIndices.push(matricesIndex >> 24);
- }
- mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
- }
- else {
- delete parsedGeometry.matricesIndices._isExpanded;
- mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
- }
- }
- if (parsedGeometry.matricesIndicesExtra) {
- if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
- var floatIndices = [];
- for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
- var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
- floatIndices.push(matricesIndex & 0x000000FF);
- floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
- floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
- floatIndices.push(matricesIndex >> 24);
- }
- mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
- }
- else {
- delete parsedGeometry.matricesIndices._isExpanded;
- mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
- }
- }
- if (parsedGeometry.matricesWeights) {
- mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
- }
- if (parsedGeometry.matricesWeightsExtra) {
- mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
- }
- mesh.setIndices(parsedGeometry.indices);
- }
- // SubMeshes
- if (parsedGeometry.subMeshes) {
- mesh.subMeshes = [];
- for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
- var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
- var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
- }
- }
- // Flat shading
- if (mesh._shouldGenerateFlatShading) {
- mesh.convertToFlatShadedMesh();
- delete mesh._shouldGenerateFlatShading;
- }
- // Update
- mesh.computeWorldMatrix(true);
- // Octree
- if (scene['_selectionOctree']) {
- scene['_selectionOctree'].addMesh(mesh);
- }
- };
- Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
- if (scene.getGeometryByID(parsedVertexData.id)) {
- return null; // null since geometry could be something else than a box...
- }
- var geometry = new Geometry(parsedVertexData.id, scene);
- BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
- if (parsedVertexData.delayLoadingFile) {
- geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
- geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
- geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
- geometry._delayInfo = [];
- if (parsedVertexData.hasUVs) {
- geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
- }
- if (parsedVertexData.hasUVs2) {
- geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
- }
- if (parsedVertexData.hasUVs3) {
- geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
- }
- if (parsedVertexData.hasUVs4) {
- geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
- }
- if (parsedVertexData.hasUVs5) {
- geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
- }
- if (parsedVertexData.hasUVs6) {
- geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
- }
- if (parsedVertexData.hasColors) {
- geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
- }
- if (parsedVertexData.hasMatricesIndices) {
- geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
- }
- if (parsedVertexData.hasMatricesWeights) {
- geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
- }
- geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
- }
- else {
- BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
- }
- scene.pushGeometry(geometry, true);
- return geometry;
- };
- return Geometry;
- })();
- BABYLON.Geometry = Geometry;
- /////// Primitives //////////////////////////////////////////////
- var Geometry;
- (function (Geometry) {
- var Primitives;
- (function (Primitives) {
- /// Abstract class
- var _Primitive = (function (_super) {
- __extends(_Primitive, _super);
- function _Primitive(id, scene, _canBeRegenerated, mesh) {
- _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
- this._canBeRegenerated = _canBeRegenerated;
- this._beingRegenerated = true;
- this.regenerate();
- this._beingRegenerated = false;
- }
- _Primitive.prototype.canBeRegenerated = function () {
- return this._canBeRegenerated;
- };
- _Primitive.prototype.regenerate = function () {
- if (!this._canBeRegenerated) {
- return;
- }
- this._beingRegenerated = true;
- this.setAllVerticesData(this._regenerateVertexData(), false);
- this._beingRegenerated = false;
- };
- _Primitive.prototype.asNewGeometry = function (id) {
- return _super.prototype.copy.call(this, id);
- };
- // overrides
- _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
- if (!this._beingRegenerated) {
- return;
- }
- _super.prototype.setAllVerticesData.call(this, vertexData, false);
- };
- _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
- if (!this._beingRegenerated) {
- return;
- }
- _super.prototype.setVerticesData.call(this, kind, data, false);
- };
- // to override
- // protected
- _Primitive.prototype._regenerateVertexData = function () {
- throw new Error("Abstract method");
- };
- _Primitive.prototype.copy = function (id) {
- throw new Error("Must be overriden in sub-classes.");
- };
- _Primitive.prototype.serialize = function () {
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.canBeRegenerated = this.canBeRegenerated();
- return serializationObject;
- };
- return _Primitive;
- })(Geometry);
- Primitives._Primitive = _Primitive;
- var Ribbon = (function (_super) {
- __extends(Ribbon, _super);
- // Members
- function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
- if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
- _super.call(this, id, scene, canBeRegenerated, mesh);
- this.pathArray = pathArray;
- this.closeArray = closeArray;
- this.closePath = closePath;
- this.offset = offset;
- this.side = side;
- }
- Ribbon.prototype._regenerateVertexData = function () {
- return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
- };
- Ribbon.prototype.copy = function (id) {
- return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
- };
- return Ribbon;
- })(_Primitive);
- Primitives.Ribbon = Ribbon;
- var Box = (function (_super) {
- __extends(Box, _super);
- // Members
- function Box(id, scene, size, canBeRegenerated, mesh, side) {
- if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
- _super.call(this, id, scene, canBeRegenerated, mesh);
- this.size = size;
- this.side = side;
- }
- Box.prototype._regenerateVertexData = function () {
- return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
- };
- Box.prototype.copy = function (id) {
- return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
- };
- Box.prototype.serialize = function () {
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.size = this.size;
- return serializationObject;
- };
- Box.Parse = function (parsedBox, scene) {
- if (scene.getGeometryByID(parsedBox.id)) {
- return null; // null since geometry could be something else than a box...
- }
- var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
- BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
- scene.pushGeometry(box, true);
- return box;
- };
- return Box;
- })(_Primitive);
- Primitives.Box = Box;
- var Sphere = (function (_super) {
- __extends(Sphere, _super);
- function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
- if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
- _super.call(this, id, scene, canBeRegenerated, mesh);
- this.segments = segments;
- this.diameter = diameter;
- this.side = side;
- }
- Sphere.prototype._regenerateVertexData = function () {
- return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
- };
- Sphere.prototype.copy = function (id) {
- return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
- };
- Sphere.prototype.serialize = function () {
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.segments = this.segments;
- serializationObject.diameter = this.diameter;
- return serializationObject;
- };
- Sphere.Parse = function (parsedSphere, scene) {
- if (scene.getGeometryByID(parsedSphere.id)) {
- return null; // null since geometry could be something else than a sphere...
- }
- var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
- BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
- scene.pushGeometry(sphere, true);
- return sphere;
- };
- return Sphere;
- })(_Primitive);
- Primitives.Sphere = Sphere;
- var Disc = (function (_super) {
- __extends(Disc, _super);
- // Members
- function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
- if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
- _super.call(this, id, scene, canBeRegenerated, mesh);
- this.radius = radius;
- this.tessellation = tessellation;
- this.side = side;
- }
- Disc.prototype._regenerateVertexData = function () {
- return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
- };
- Disc.prototype.copy = function (id) {
- return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
- };
- return Disc;
- })(_Primitive);
- Primitives.Disc = Disc;
- var Cylinder = (function (_super) {
- __extends(Cylinder, _super);
- function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
- if (subdivisions === void 0) { subdivisions = 1; }
- if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
- _super.call(this, id, scene, canBeRegenerated, mesh);
- this.height = height;
- this.diameterTop = diameterTop;
- this.diameterBottom = diameterBottom;
- this.tessellation = tessellation;
- this.subdivisions = subdivisions;
- this.side = side;
- }
- Cylinder.prototype._regenerateVertexData = function () {
- return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
- };
- Cylinder.prototype.copy = function (id) {
- return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
- };
- Cylinder.prototype.serialize = function () {
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.height = this.height;
- serializationObject.diameterTop = this.diameterTop;
- serializationObject.diameterBottom = this.diameterBottom;
- serializationObject.tessellation = this.tessellation;
- return serializationObject;
- };
- Cylinder.Parse = function (parsedCylinder, scene) {
- if (scene.getGeometryByID(parsedCylinder.id)) {
- return null; // null since geometry could be something else than a cylinder...
- }
- var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
- BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
- scene.pushGeometry(cylinder, true);
- return cylinder;
- };
- return Cylinder;
- })(_Primitive);
- Primitives.Cylinder = Cylinder;
- var Torus = (function (_super) {
- __extends(Torus, _super);
- function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
- if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
- _super.call(this, id, scene, canBeRegenerated, mesh);
- this.diameter = diameter;
- this.thickness = thickness;
- this.tessellation = tessellation;
- this.side = side;
- }
- Torus.prototype._regenerateVertexData = function () {
- return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
- };
- Torus.prototype.copy = function (id) {
- return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
- };
- Torus.prototype.serialize = function () {
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.diameter = this.diameter;
- serializationObject.thickness = this.thickness;
- serializationObject.tessellation = this.tessellation;
- return serializationObject;
- };
- Torus.Parse = function (parsedTorus, scene) {
- if (scene.getGeometryByID(parsedTorus.id)) {
- return null; // null since geometry could be something else than a torus...
- }
- var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
- BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
- scene.pushGeometry(torus, true);
- return torus;
- };
- return Torus;
- })(_Primitive);
- Primitives.Torus = Torus;
- var Ground = (function (_super) {
- __extends(Ground, _super);
- function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
- _super.call(this, id, scene, canBeRegenerated, mesh);
- this.width = width;
- this.height = height;
- this.subdivisions = subdivisions;
- }
- Ground.prototype._regenerateVertexData = function () {
- return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
- };
- Ground.prototype.copy = function (id) {
- return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
- };
- Ground.prototype.serialize = function () {
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.width = this.width;
- serializationObject.height = this.height;
- serializationObject.subdivisions = this.subdivisions;
- return serializationObject;
- };
- Ground.Parse = function (parsedGround, scene) {
- if (scene.getGeometryByID(parsedGround.id)) {
- return null; // null since geometry could be something else than a ground...
- }
- var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
- BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
- scene.pushGeometry(ground, true);
- return ground;
- };
- return Ground;
- })(_Primitive);
- Primitives.Ground = Ground;
- var TiledGround = (function (_super) {
- __extends(TiledGround, _super);
- function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
- _super.call(this, id, scene, canBeRegenerated, mesh);
- this.xmin = xmin;
- this.zmin = zmin;
- this.xmax = xmax;
- this.zmax = zmax;
- this.subdivisions = subdivisions;
- this.precision = precision;
- }
- TiledGround.prototype._regenerateVertexData = function () {
- return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
- };
- TiledGround.prototype.copy = function (id) {
- return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
- };
- return TiledGround;
- })(_Primitive);
- Primitives.TiledGround = TiledGround;
- var Plane = (function (_super) {
- __extends(Plane, _super);
- function Plane(id, scene, size, canBeRegenerated, mesh, side) {
- if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
- _super.call(this, id, scene, canBeRegenerated, mesh);
- this.size = size;
- this.side = side;
- }
- Plane.prototype._regenerateVertexData = function () {
- return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
- };
- Plane.prototype.copy = function (id) {
- return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
- };
- Plane.prototype.serialize = function () {
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.size = this.size;
- return serializationObject;
- };
- Plane.Parse = function (parsedPlane, scene) {
- if (scene.getGeometryByID(parsedPlane.id)) {
- return null; // null since geometry could be something else than a ground...
- }
- var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
- BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
- scene.pushGeometry(plane, true);
- return plane;
- };
- return Plane;
- })(_Primitive);
- Primitives.Plane = Plane;
- var TorusKnot = (function (_super) {
- __extends(TorusKnot, _super);
- function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
- if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
- _super.call(this, id, scene, canBeRegenerated, mesh);
- this.radius = radius;
- this.tube = tube;
- this.radialSegments = radialSegments;
- this.tubularSegments = tubularSegments;
- this.p = p;
- this.q = q;
- this.side = side;
- }
- TorusKnot.prototype._regenerateVertexData = function () {
- 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 });
- };
- TorusKnot.prototype.copy = function (id) {
- return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
- };
- TorusKnot.prototype.serialize = function () {
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.radius = this.radius;
- serializationObject.tube = this.tube;
- serializationObject.radialSegments = this.radialSegments;
- serializationObject.tubularSegments = this.tubularSegments;
- serializationObject.p = this.p;
- serializationObject.q = this.q;
- return serializationObject;
- };
- ;
- TorusKnot.Parse = function (parsedTorusKnot, scene) {
- if (scene.getGeometryByID(parsedTorusKnot.id)) {
- return null; // null since geometry could be something else than a ground...
- }
- var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
- BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
- scene.pushGeometry(torusKnot, true);
- return torusKnot;
- };
- return TorusKnot;
- })(_Primitive);
- Primitives.TorusKnot = TorusKnot;
- })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
- })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var GroundMesh = (function (_super) {
- __extends(GroundMesh, _super);
- function GroundMesh(name, scene) {
- _super.call(this, name, scene);
- this.generateOctree = false;
- this._worldInverse = new BABYLON.Matrix();
- }
- Object.defineProperty(GroundMesh.prototype, "subdivisions", {
- get: function () {
- return this._subdivisions;
- },
- enumerable: true,
- configurable: true
- });
- GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
- if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
- this._subdivisions = chunksCount;
- this.subdivide(this._subdivisions);
- this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
- };
- /**
- * Returns a height (y) value in the Worl system :
- * the ground altitude at the coordinates (x, z) expressed in the World system.
- * Returns the ground y position if (x, z) are outside the ground surface.
- * Not pertinent if the ground is rotated.
- */
- GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
- // express x and y in the ground local system
- x -= this.position.x;
- z -= this.position.z;
- x /= this.scaling.x;
- z /= this.scaling.z;
- if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
- return this.position.y;
- }
- if (!this._heightQuads || this._heightQuads.length == 0) {
- this._initHeightQuads();
- this._computeHeightQuads();
- }
- var facet = this._getFacetAt(x, z);
- var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
- // return y in the World system
- return y * this.scaling.y + this.position.y;
- };
- /**
- * Returns a normalized vector (Vector3) orthogonal to the ground
- * at the ground coordinates (x, z) expressed in the World system.
- * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
- * Not pertinent if the ground is rotated.
- */
- GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
- var normal = new BABYLON.Vector3(0, 1, 0);
- this.getNormalAtCoordinatesToRef(x, z, normal);
- return normal;
- };
- /**
- * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
- * at the ground coordinates (x, z) expressed in the World system.
- * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
- * Not pertinent if the ground is rotated.
- */
- GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
- // express x and y in the ground local system
- x -= this.position.x;
- z -= this.position.z;
- x /= this.scaling.x;
- z /= this.scaling.z;
- if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
- return;
- }
- if (!this._heightQuads || this._heightQuads.length == 0) {
- this._initHeightQuads();
- this._computeHeightQuads();
- }
- var facet = this._getFacetAt(x, z);
- ref.x = facet.x;
- ref.y = facet.y;
- ref.z = facet.z;
- };
- /**
- * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
- * if the ground has been updated.
- * This can be used in the render loop
- */
- GroundMesh.prototype.updateCoordinateHeights = function () {
- if (!this._heightQuads || this._heightQuads.length == 0) {
- this._initHeightQuads();
- }
- this._computeHeightQuads();
- };
- // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
- GroundMesh.prototype._getFacetAt = function (x, z) {
- // retrieve col and row from x, z coordinates in the ground local system
- var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
- var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
- var quad = this._heightQuads[row * this._subdivisions + col];
- var facet;
- if (z < quad.slope.x * x + quad.slope.y) {
- facet = quad.facet1;
- }
- else {
- facet = quad.facet2;
- }
- return facet;
- };
- // Creates and populates the heightMap array with "facet" elements :
- // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
- // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
- // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
- // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
- GroundMesh.prototype._initHeightQuads = function () {
- this._heightQuads = new Array();
- for (var row = 0; row < this._subdivisions; row++) {
- for (var col = 0; col < this._subdivisions; col++) {
- var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
- this._heightQuads[row * this._subdivisions + col] = quad;
- }
- }
- };
- // Compute each quad element values and update the the heightMap array :
- // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
- // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
- // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
- GroundMesh.prototype._computeHeightQuads = function () {
- var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- var v1 = BABYLON.Tmp.Vector3[0];
- var v2 = BABYLON.Tmp.Vector3[1];
- var v3 = BABYLON.Tmp.Vector3[2];
- var v4 = BABYLON.Tmp.Vector3[3];
- var v1v2 = BABYLON.Tmp.Vector3[4];
- var v1v3 = BABYLON.Tmp.Vector3[5];
- var v1v4 = BABYLON.Tmp.Vector3[6];
- var norm1 = BABYLON.Tmp.Vector3[7];
- var norm2 = BABYLON.Tmp.Vector3[8];
- var i = 0;
- var j = 0;
- var k = 0;
- var cd = 0; // 2D slope coefficient : z = cd * x + h
- var h = 0;
- var d1 = 0; // facet plane equation : ax + by + cz + d = 0
- var d2 = 0;
- for (var row = 0; row < this._subdivisions; row++) {
- for (var col = 0; col < this._subdivisions; col++) {
- i = col * 3;
- j = row * (this._subdivisions + 1) * 3;
- k = (row + 1) * (this._subdivisions + 1) * 3;
- v1.x = positions[j + i];
- v1.y = positions[j + i + 1];
- v1.z = positions[j + i + 2];
- v2.x = positions[j + i + 3];
- v2.y = positions[j + i + 4];
- v2.z = positions[j + i + 5];
- v3.x = positions[k + i];
- v3.y = positions[k + i + 1];
- v3.z = positions[k + i + 2];
- v4.x = positions[k + i + 3];
- v4.y = positions[k + i + 4];
- v4.z = positions[k + i + 5];
- // 2D slope V1V4
- cd = (v4.z - v1.z) / (v4.x - v1.x);
- h = v1.z - cd * v1.x; // v1 belongs to the slope
- // facet equations :
- // we compute each facet normal vector
- // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
- // we compute the value d by applying the equation to v1 which belongs to the plane
- // then we store the facet equation in a Vector4
- v2.subtractToRef(v1, v1v2);
- v3.subtractToRef(v1, v1v3);
- v4.subtractToRef(v1, v1v4);
- BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
- BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
- norm1.normalize();
- norm2.normalize();
- d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
- d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
- var quad = this._heightQuads[row * this._subdivisions + col];
- quad.slope.copyFromFloats(cd, h);
- quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
- quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
- }
- }
- };
- return GroundMesh;
- })(BABYLON.Mesh);
- BABYLON.GroundMesh = GroundMesh;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var LinesMesh = (function (_super) {
- __extends(LinesMesh, _super);
- function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
- if (parent === void 0) { parent = null; }
- _super.call(this, name, scene, parent, source, doNotCloneChildren);
- this.color = new BABYLON.Color3(1, 1, 1);
- this.alpha = 1;
- if (source) {
- this.color = source.color.clone();
- this.alpha = source.alpha;
- }
- this._intersectionThreshold = 0.1;
- this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
- attributes: ["position"],
- uniforms: ["worldViewProjection", "color"],
- needAlphaBlending: true
- });
- }
- Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
- /**
- * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
- * This margin is expressed in world space coordinates, so its value may vary.
- * Default value is 0.1
- * @returns the intersection Threshold value.
- */
- get: function () {
- return this._intersectionThreshold;
- },
- /**
- * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
- * This margin is expressed in world space coordinates, so its value may vary.
- * @param value the new threshold to apply
- */
- set: function (value) {
- if (this._intersectionThreshold === value) {
- return;
- }
- this._intersectionThreshold = value;
- if (this.geometry) {
- this.geometry.boundingBias = new BABYLON.Vector2(0, value);
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(LinesMesh.prototype, "material", {
- get: function () {
- return this._colorShader;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
- get: function () {
- return false;
- },
- enumerable: true,
- configurable: true
- });
- LinesMesh.prototype.createInstance = function (name) {
- BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
- return null;
- };
- LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
- var engine = this.getScene().getEngine();
- var indexToBind = this._geometry.getIndexBuffer();
- // VBOs
- engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
- // Color
- this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
- };
- LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
- if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
- return;
- }
- var engine = this.getScene().getEngine();
- // Draw order
- engine.draw(false, subMesh.indexStart, subMesh.indexCount);
- };
- LinesMesh.prototype.dispose = function (doNotRecurse) {
- this._colorShader.dispose();
- _super.prototype.dispose.call(this, doNotRecurse);
- };
- LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
- return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
- };
- return LinesMesh;
- })(BABYLON.Mesh);
- BABYLON.LinesMesh = LinesMesh;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var DebugLayer = (function () {
- function DebugLayer(scene) {
- var _this = this;
- this._transformationMatrix = BABYLON.Matrix.Identity();
- this._enabled = false;
- this._labelsEnabled = false;
- this._displayStatistics = true;
- this._displayTree = false;
- this._displayLogs = false;
- this._skeletonViewers = new Array();
- this._identityMatrix = BABYLON.Matrix.Identity();
- this.axisRatio = 0.02;
- this.accentColor = "orange";
- this._scene = scene;
- this._syncPositions = function () {
- var engine = _this._scene.getEngine();
- var canvasRect = engine.getRenderingCanvasClientRect();
- if (_this._showUI) {
- _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
- _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
- _this._statsDiv.style.width = "400px";
- _this._statsDiv.style.height = "auto";
- _this._statsSubsetDiv.style.maxHeight = "240px";
- _this._optionsDiv.style.left = "0px";
- _this._optionsDiv.style.top = "10px";
- _this._optionsDiv.style.width = "200px";
- _this._optionsDiv.style.height = "auto";
- _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
- _this._logDiv.style.left = "0px";
- _this._logDiv.style.top = (canvasRect.height - 170) + "px";
- _this._logDiv.style.width = "600px";
- _this._logDiv.style.height = "160px";
- _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
- _this._treeDiv.style.top = "10px";
- _this._treeDiv.style.width = "300px";
- _this._treeDiv.style.height = "auto";
- _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
- }
- _this._globalDiv.style.left = canvasRect.left + "px";
- _this._globalDiv.style.top = canvasRect.top + "px";
- _this._drawingCanvas.style.left = "0px";
- _this._drawingCanvas.style.top = "0px";
- _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
- _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
- var devicePixelRatio = window.devicePixelRatio || 1;
- var context = _this._drawingContext;
- var backingStoreRatio = context.webkitBackingStorePixelRatio ||
- context.mozBackingStorePixelRatio ||
- context.msBackingStorePixelRatio ||
- context.oBackingStorePixelRatio ||
- context.backingStorePixelRatio || 1;
- _this._ratio = devicePixelRatio / backingStoreRatio;
- _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
- _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
- };
- this._onCanvasClick = function (evt) {
- _this._clickPosition = {
- x: evt.clientX * _this._ratio,
- y: evt.clientY * _this._ratio
- };
- };
- this._syncUI = function () {
- if (_this._showUI) {
- if (_this._displayStatistics) {
- _this._displayStats();
- _this._statsDiv.style.display = "";
- }
- else {
- _this._statsDiv.style.display = "none";
- }
- if (_this._displayLogs) {
- _this._logDiv.style.display = "";
- }
- else {
- _this._logDiv.style.display = "none";
- }
- if (_this._displayTree) {
- _this._treeDiv.style.display = "";
- if (_this._needToRefreshMeshesTree) {
- _this._needToRefreshMeshesTree = false;
- _this._refreshMeshesTreeContent();
- }
- }
- else {
- _this._treeDiv.style.display = "none";
- }
- }
- };
- this._syncData = function () {
- if (_this._labelsEnabled || !_this._showUI) {
- _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
- _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
- var engine = _this._scene.getEngine();
- var viewport = _this._camera.viewport;
- var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
- // Meshes
- var meshes = _this._camera.getActiveMeshes();
- var index;
- var projectedPosition;
- for (index = 0; index < meshes.length; index++) {
- var mesh = meshes.data[index];
- var position = mesh.getBoundingInfo().boundingSphere.center;
- projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
- if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
- _this._renderAxis(projectedPosition, mesh, globalViewport);
- }
- if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
- _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
- }
- }
- // Cameras
- var cameras = _this._scene.cameras;
- for (index = 0; index < cameras.length; index++) {
- var camera = cameras[index];
- if (camera === _this._camera) {
- continue;
- }
- projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
- if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
- _this._renderLabel(camera.name, projectedPosition, 12, function () {
- _this._camera.detachControl(engine.getRenderingCanvas());
- _this._camera = camera;
- _this._camera.attachControl(engine.getRenderingCanvas());
- }, function () { return "purple"; });
- }
- }
- // Lights
- var lights = _this._scene.lights;
- for (index = 0; index < lights.length; index++) {
- var light = lights[index];
- if (light.position) {
- projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
- if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
- _this._renderLabel(light.name, projectedPosition, -20, function () {
- light.setEnabled(!light.isEnabled());
- }, function () { return light.isEnabled() ? "orange" : "gray"; });
- }
- }
- }
- }
- _this._clickPosition = undefined;
- };
- }
- DebugLayer.prototype._refreshMeshesTreeContent = function () {
- while (this._treeSubsetDiv.hasChildNodes()) {
- this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
- }
- // Add meshes
- var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
- sortedArray.sort(function (a, b) {
- if (a.name === b.name) {
- return 0;
- }
- return (a.name > b.name) ? 1 : -1;
- });
- for (var index = 0; index < sortedArray.length; index++) {
- var mesh = sortedArray[index];
- if (!mesh.isEnabled()) {
- continue;
- }
- this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
- m.isVisible = element.checked;
- }, mesh);
- }
- };
- DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
- this._drawingContext.beginPath();
- this._drawingContext.moveTo(zero.x, zero.y);
- this._drawingContext.lineTo(unit.x, unit.y);
- this._drawingContext.strokeStyle = color;
- this._drawingContext.lineWidth = 4;
- this._drawingContext.stroke();
- this._drawingContext.font = "normal 14px Segoe UI";
- this._drawingContext.fillStyle = color;
- this._drawingContext.fillText(label, unitText.x, unitText.y);
- };
- DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
- var position = mesh.getBoundingInfo().boundingSphere.center;
- var worldMatrix = mesh.getWorldMatrix();
- var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
- var unit = (unprojectedVector.subtract(position)).length();
- var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
- var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
- this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
- var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
- var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
- this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
- var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
- var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
- this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
- };
- DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
- if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
- this._drawingContext.font = "normal 12px Segoe UI";
- var textMetrics = this._drawingContext.measureText(text);
- var centerX = projectedPosition.x - textMetrics.width / 2;
- var centerY = projectedPosition.y;
- var clientRect = this._drawingCanvas.getBoundingClientRect();
- if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
- onClick();
- }
- this._drawingContext.beginPath();
- this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
- this._drawingContext.fillStyle = getFillStyle();
- this._drawingContext.globalAlpha = 0.5;
- this._drawingContext.fill();
- this._drawingContext.globalAlpha = 1.0;
- this._drawingContext.strokeStyle = '#FFFFFF';
- this._drawingContext.lineWidth = 1;
- this._drawingContext.stroke();
- this._drawingContext.fillStyle = "#FFFFFF";
- this._drawingContext.fillText(text, centerX, centerY - labelOffset);
- this._drawingContext.beginPath();
- this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
- this._drawingContext.fill();
- }
- };
- DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
- if (!this._clickPosition) {
- return false;
- }
- if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
- return false;
- }
- if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
- return false;
- }
- return true;
- };
- DebugLayer.prototype.isVisible = function () {
- return this._enabled;
- };
- DebugLayer.prototype.hide = function () {
- if (!this._enabled) {
- return;
- }
- this._enabled = false;
- var engine = this._scene.getEngine();
- this._scene.unregisterBeforeRender(this._syncData);
- this._scene.unregisterAfterRender(this._syncUI);
- this._rootElement.removeChild(this._globalDiv);
- this._scene.forceShowBoundingBoxes = false;
- this._scene.forceWireframe = false;
- BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
- BABYLON.StandardMaterial.AmbientTextureEnabled = true;
- BABYLON.StandardMaterial.SpecularTextureEnabled = true;
- BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
- BABYLON.StandardMaterial.BumpTextureEnabled = true;
- BABYLON.StandardMaterial.OpacityTextureEnabled = true;
- BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
- BABYLON.StandardMaterial.LightmapTextureEnabled = true;
- BABYLON.StandardMaterial.RefractionTextureEnabled = true;
- this._scene.shadowsEnabled = true;
- this._scene.particlesEnabled = true;
- this._scene.postProcessesEnabled = true;
- this._scene.collisionsEnabled = true;
- this._scene.lightsEnabled = true;
- this._scene.texturesEnabled = true;
- this._scene.lensFlaresEnabled = true;
- this._scene.proceduralTexturesEnabled = true;
- this._scene.renderTargetsEnabled = true;
- this._scene.probesEnabled = true;
- engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
- this._clearSkeletonViewers();
- };
- DebugLayer.prototype._clearSkeletonViewers = function () {
- for (var index = 0; index < this._skeletonViewers.length; index++) {
- this._skeletonViewers[index].dispose();
- }
- this._skeletonViewers = [];
- };
- DebugLayer.prototype.show = function (showUI, camera, rootElement) {
- if (showUI === void 0) { showUI = true; }
- if (camera === void 0) { camera = null; }
- if (rootElement === void 0) { rootElement = null; }
- if (this._enabled) {
- return;
- }
- this._enabled = true;
- if (camera) {
- this._camera = camera;
- }
- else {
- this._camera = this._scene.activeCamera;
- }
- this._showUI = showUI;
- var engine = this._scene.getEngine();
- this._globalDiv = document.createElement("div");
- this._rootElement = rootElement || document.body;
- this._rootElement.appendChild(this._globalDiv);
- this._generateDOMelements();
- engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
- this._syncPositions();
- this._scene.registerBeforeRender(this._syncData);
- this._scene.registerAfterRender(this._syncUI);
- };
- DebugLayer.prototype._clearLabels = function () {
- this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
- for (var index = 0; index < this._scene.meshes.length; index++) {
- var mesh = this._scene.meshes[index];
- mesh.renderOverlay = false;
- }
- };
- DebugLayer.prototype._generateheader = function (root, text) {
- var header = document.createElement("div");
- header.innerHTML = text + " ";
- header.style.textAlign = "right";
- header.style.width = "100%";
- header.style.color = "white";
- header.style.backgroundColor = "Black";
- header.style.padding = "5px 5px 4px 0px";
- header.style.marginLeft = "-5px";
- header.style.fontWeight = "bold";
- root.appendChild(header);
- };
- DebugLayer.prototype._generateTexBox = function (root, title, color) {
- var label = document.createElement("label");
- label.style.display = "inline";
- label.innerHTML = title;
- label.style.color = color;
- root.appendChild(label);
- root.appendChild(document.createElement("br"));
- };
- DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
- if (tag === void 0) { tag = null; }
- var label = document.createElement("label");
- label.style.display = "inline";
- var boundingBoxesCheckbox = document.createElement("input");
- boundingBoxesCheckbox.type = "checkbox";
- boundingBoxesCheckbox.checked = initialState;
- boundingBoxesCheckbox.style.display = "inline";
- boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
- boundingBoxesCheckbox.style.verticalAlign = "sub";
- boundingBoxesCheckbox.addEventListener("change", function (evt) {
- task(evt.target, tag);
- });
- label.appendChild(boundingBoxesCheckbox);
- var container = document.createElement("span");
- var leftPart = document.createElement("span");
- var rightPart = document.createElement("span");
- rightPart.style.cssFloat = "right";
- leftPart.innerHTML = leftTitle;
- rightPart.innerHTML = rightTitle;
- rightPart.style.fontSize = "12px";
- rightPart.style.maxWidth = "200px";
- container.appendChild(leftPart);
- container.appendChild(rightPart);
- label.appendChild(container);
- root.appendChild(label);
- root.appendChild(document.createElement("br"));
- };
- DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
- if (tag === void 0) { tag = null; }
- var label = document.createElement("label");
- label.style.display = "inline";
- var checkBox = document.createElement("input");
- checkBox.type = "checkbox";
- checkBox.checked = initialState;
- checkBox.style.display = "inline";
- checkBox.style.margin = "0px 5px 0px 0px";
- checkBox.style.verticalAlign = "sub";
- checkBox.addEventListener("change", function (evt) {
- task(evt.target, tag);
- });
- label.appendChild(checkBox);
- label.appendChild(document.createTextNode(title));
- root.appendChild(label);
- root.appendChild(document.createElement("br"));
- };
- DebugLayer.prototype._generateButton = function (root, title, task, tag) {
- if (tag === void 0) { tag = null; }
- var button = document.createElement("button");
- button.innerHTML = title;
- button.style.height = "24px";
- button.style.width = "150px";
- button.style.marginBottom = "5px";
- button.style.color = "#444444";
- button.style.border = "1px solid white";
- button.className = "debugLayerButton";
- button.addEventListener("click", function (evt) {
- task(evt.target, tag);
- });
- root.appendChild(button);
- root.appendChild(document.createElement("br"));
- };
- DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
- if (tag === void 0) { tag = null; }
- var label = document.createElement("label");
- label.style.display = "inline";
- var boundingBoxesRadio = document.createElement("input");
- boundingBoxesRadio.type = "radio";
- boundingBoxesRadio.name = name;
- boundingBoxesRadio.checked = initialState;
- boundingBoxesRadio.style.display = "inline";
- boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
- boundingBoxesRadio.style.verticalAlign = "sub";
- boundingBoxesRadio.addEventListener("change", function (evt) {
- task(evt.target, tag);
- });
- label.appendChild(boundingBoxesRadio);
- label.appendChild(document.createTextNode(title));
- root.appendChild(label);
- root.appendChild(document.createElement("br"));
- };
- DebugLayer.prototype._generateDOMelements = function () {
- var _this = this;
- this._globalDiv.id = "DebugLayer";
- this._globalDiv.style.position = "absolute";
- this._globalDiv.style.fontFamily = "Segoe UI, Arial";
- this._globalDiv.style.fontSize = "14px";
- this._globalDiv.style.color = "white";
- // Drawing canvas
- this._drawingCanvas = document.createElement("canvas");
- this._drawingCanvas.id = "DebugLayerDrawingCanvas";
- this._drawingCanvas.style.position = "absolute";
- this._drawingCanvas.style.pointerEvents = "none";
- this._drawingCanvas.style.backgroundColor = "transparent";
- this._drawingContext = this._drawingCanvas.getContext("2d");
- this._globalDiv.appendChild(this._drawingCanvas);
- if (this._showUI) {
- var background = "rgba(128, 128, 128, 0.4)";
- var border = "rgb(180, 180, 180) solid 1px";
- // Stats
- this._statsDiv = document.createElement("div");
- this._statsDiv.id = "DebugLayerStats";
- this._statsDiv.style.border = border;
- this._statsDiv.style.position = "absolute";
- this._statsDiv.style.background = background;
- this._statsDiv.style.padding = "0px 0px 0px 5px";
- this._generateheader(this._statsDiv, "STATISTICS");
- this._statsSubsetDiv = document.createElement("div");
- this._statsSubsetDiv.style.paddingTop = "5px";
- this._statsSubsetDiv.style.paddingBottom = "5px";
- this._statsSubsetDiv.style.overflowY = "auto";
- this._statsDiv.appendChild(this._statsSubsetDiv);
- // Tree
- this._treeDiv = document.createElement("div");
- this._treeDiv.id = "DebugLayerTree";
- this._treeDiv.style.border = border;
- this._treeDiv.style.position = "absolute";
- this._treeDiv.style.background = background;
- this._treeDiv.style.padding = "0px 0px 0px 5px";
- this._treeDiv.style.display = "none";
- this._generateheader(this._treeDiv, "MESHES TREE");
- this._treeSubsetDiv = document.createElement("div");
- this._treeSubsetDiv.style.paddingTop = "5px";
- this._treeSubsetDiv.style.paddingRight = "5px";
- this._treeSubsetDiv.style.overflowY = "auto";
- this._treeSubsetDiv.style.maxHeight = "300px";
- this._treeDiv.appendChild(this._treeSubsetDiv);
- this._needToRefreshMeshesTree = true;
- // Logs
- this._logDiv = document.createElement("div");
- this._logDiv.style.border = border;
- this._logDiv.id = "DebugLayerLogs";
- this._logDiv.style.position = "absolute";
- this._logDiv.style.background = background;
- this._logDiv.style.padding = "0px 0px 0px 5px";
- this._logDiv.style.display = "none";
- this._generateheader(this._logDiv, "LOGS");
- this._logSubsetDiv = document.createElement("div");
- this._logSubsetDiv.style.height = "127px";
- this._logSubsetDiv.style.paddingTop = "5px";
- this._logSubsetDiv.style.overflowY = "auto";
- this._logSubsetDiv.style.fontSize = "12px";
- this._logSubsetDiv.style.fontFamily = "consolas";
- this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
- this._logDiv.appendChild(this._logSubsetDiv);
- BABYLON.Tools.OnNewCacheEntry = function (entry) {
- _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
- };
- // Options
- this._optionsDiv = document.createElement("div");
- this._optionsDiv.id = "DebugLayerOptions";
- this._optionsDiv.style.border = border;
- this._optionsDiv.style.position = "absolute";
- this._optionsDiv.style.background = background;
- this._optionsDiv.style.padding = "0px 0px 0px 5px";
- this._optionsDiv.style.overflowY = "auto";
- this._generateheader(this._optionsDiv, "OPTIONS");
- this._optionsSubsetDiv = document.createElement("div");
- this._optionsSubsetDiv.style.paddingTop = "5px";
- this._optionsSubsetDiv.style.paddingBottom = "5px";
- this._optionsSubsetDiv.style.overflowY = "auto";
- this._optionsSubsetDiv.style.maxHeight = "200px";
- this._optionsDiv.appendChild(this._optionsSubsetDiv);
- this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
- this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
- _this._displayTree = element.checked;
- _this._needToRefreshMeshesTree = true;
- });
- this._optionsSubsetDiv.appendChild(document.createElement("br"));
- this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
- this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
- _this._labelsEnabled = element.checked;
- if (!_this._labelsEnabled) {
- _this._clearLabels();
- }
- });
- this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
- if (element.checked) {
- BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
- }
- else {
- BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
- }
- });
- ;
- this._optionsSubsetDiv.appendChild(document.createElement("br"));
- this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
- this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
- if (element.checked) {
- _this._scene.forceWireframe = false;
- _this._scene.forcePointsCloud = false;
- }
- });
- this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
- if (element.checked) {
- _this._scene.forceWireframe = true;
- _this._scene.forcePointsCloud = false;
- }
- });
- this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
- if (element.checked) {
- _this._scene.forceWireframe = false;
- _this._scene.forcePointsCloud = true;
- }
- });
- this._optionsSubsetDiv.appendChild(document.createElement("br"));
- this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
- this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
- this._optionsSubsetDiv.appendChild(document.createElement("br"));
- this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
- this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
- this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
- if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
- this._optionsSubsetDiv.appendChild(document.createElement("br"));
- this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
- this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
- if (element.checked) {
- _this._scene.headphone = true;
- }
- });
- this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
- if (element.checked) {
- _this._scene.headphone = false;
- }
- });
- this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
- _this._scene.audioEnabled = !element.checked;
- });
- }
- this._optionsSubsetDiv.appendChild(document.createElement("br"));
- this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
- this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
- if (!element.checked) {
- _this._clearSkeletonViewers();
- return;
- }
- for (var index = 0; index < _this._scene.meshes.length; index++) {
- var mesh = _this._scene.meshes[index];
- if (mesh.skeleton) {
- var found = false;
- for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
- if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
- found = true;
- break;
- }
- }
- if (found) {
- continue;
- }
- var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
- viewer.isEnabled = true;
- _this._skeletonViewers.push(viewer);
- }
- }
- });
- this._optionsSubsetDiv.appendChild(document.createElement("br"));
- this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
- this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
- this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
- this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
- if (_this._camera) {
- console.log(_this._camera);
- }
- else {
- console.warn("No camera defined, or debug layer created before camera creation!");
- }
- });
- this._optionsSubsetDiv.appendChild(document.createElement("br"));
- this._globalDiv.appendChild(this._statsDiv);
- this._globalDiv.appendChild(this._logDiv);
- this._globalDiv.appendChild(this._optionsDiv);
- this._globalDiv.appendChild(this._treeDiv);
- }
- };
- DebugLayer.prototype._displayStats = function () {
- var scene = this._scene;
- var engine = scene.getEngine();
- var glInfo = engine.getGlInfo();
- this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
- + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
- + "<b>Count</b><br>"
- + "Total meshes: " + scene.meshes.length + "<br>"
- + "Total lights: " + scene.lights.length + "<br>"
- + "Total vertices: " + scene.getTotalVertices() + "<br>"
- + "Total materials: " + scene.materials.length + "<br>"
- + "Total textures: " + scene.textures.length + "<br>"
- + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
- + "Active indices: " + scene.getActiveIndices() + "<br>"
- + "Active bones: " + scene.getActiveBones() + "<br>"
- + "Active particles: " + scene.getActiveParticles() + "<br>"
- + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
- + "<b>Duration</b><br>"
- + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
- + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
- + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
- + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
- + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
- + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
- + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
- + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
- + "</div>"
- + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
- + "<b>Extensions</b><br>"
- + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
- + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
- + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
- + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
- + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
- + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
- + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
- + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
- + "</div><br>"
- + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
- + "<b>Caps.</b><br>"
- + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
- + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
- + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
- + "<b>Info</b><br>"
- + "WebGL feature level: " + engine.webGLVersion + "<br>"
- + glInfo.version + "<br>"
- + "</div><br>"
- + glInfo.renderer + "<br>";
- if (this.customStatsFunction) {
- this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
- }
- };
- return DebugLayer;
- })();
- BABYLON.DebugLayer = DebugLayer;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var DefaultLoadingScreen = (function () {
- function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
- var _this = this;
- if (_loadingText === void 0) { _loadingText = ""; }
- if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
- this._renderingCanvas = _renderingCanvas;
- this._loadingText = _loadingText;
- this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
- // Resize
- this._resizeLoadingUI = function () {
- var canvasRect = _this._renderingCanvas.getBoundingClientRect();
- _this._loadingDiv.style.position = "absolute";
- _this._loadingDiv.style.left = canvasRect.left + "px";
- _this._loadingDiv.style.top = canvasRect.top + "px";
- _this._loadingDiv.style.width = canvasRect.width + "px";
- _this._loadingDiv.style.height = canvasRect.height + "px";
- };
- }
- DefaultLoadingScreen.prototype.displayLoadingUI = function () {
- var _this = this;
- if (this._loadingDiv) {
- // Do not add a loading screen if there is already one
- return;
- }
- this._loadingDiv = document.createElement("div");
- this._loadingDiv.id = "babylonjsLoadingDiv";
- this._loadingDiv.style.opacity = "0";
- this._loadingDiv.style.transition = "opacity 1.5s ease";
- // Loading text
- this._loadingTextDiv = document.createElement("div");
- this._loadingTextDiv.style.position = "absolute";
- this._loadingTextDiv.style.left = "0";
- this._loadingTextDiv.style.top = "50%";
- this._loadingTextDiv.style.marginTop = "80px";
- this._loadingTextDiv.style.width = "100%";
- this._loadingTextDiv.style.height = "20px";
- this._loadingTextDiv.style.fontFamily = "Arial";
- this._loadingTextDiv.style.fontSize = "14px";
- this._loadingTextDiv.style.color = "white";
- this._loadingTextDiv.style.textAlign = "center";
- this._loadingTextDiv.innerHTML = "Loading";
- this._loadingDiv.appendChild(this._loadingTextDiv);
- //set the predefined text
- this._loadingTextDiv.innerHTML = this._loadingText;
- // Loading img
- var imgBack = new Image();
- 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==";
- imgBack.style.position = "absolute";
- imgBack.style.left = "50%";
- imgBack.style.top = "50%";
- imgBack.style.marginLeft = "-50px";
- imgBack.style.marginTop = "-50px";
- imgBack.style.transition = "transform 1.0s ease";
- imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
- var deg = 360;
- var onTransitionEnd = function () {
- deg += 360;
- imgBack.style.transform = "rotateZ(" + deg + "deg)";
- imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
- };
- imgBack.addEventListener("transitionend", onTransitionEnd);
- imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
- this._loadingDiv.appendChild(imgBack);
- // front image
- var imgFront = new Image();
- 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=";
- imgFront.style.position = "absolute";
- imgFront.style.left = "50%";
- imgFront.style.top = "50%";
- imgFront.style.marginLeft = "-50px";
- imgFront.style.marginTop = "-50px";
- this._loadingDiv.appendChild(imgFront);
- this._resizeLoadingUI();
- window.addEventListener("resize", this._resizeLoadingUI);
- this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
- document.body.appendChild(this._loadingDiv);
- setTimeout(function () {
- _this._loadingDiv.style.opacity = "1";
- imgBack.style.transform = "rotateZ(360deg)";
- imgBack.style.webkitTransform = "rotateZ(360deg)";
- }, 0);
- };
- DefaultLoadingScreen.prototype.hideLoadingUI = function () {
- var _this = this;
- if (!this._loadingDiv) {
- return;
- }
- var onTransitionEnd = function () {
- if (!_this._loadingDiv) {
- return;
- }
- document.body.removeChild(_this._loadingDiv);
- window.removeEventListener("resize", _this._resizeLoadingUI);
- _this._loadingDiv = null;
- };
- this._loadingDiv.style.opacity = "0";
- this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
- };
- Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
- set: function (text) {
- this._loadingText = text;
- if (this._loadingTextDiv) {
- this._loadingTextDiv.innerHTML = this._loadingText;
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
- get: function () {
- return this._loadingDivBackgroundColor;
- },
- set: function (color) {
- this._loadingDivBackgroundColor = color;
- if (!this._loadingDiv) {
- return;
- }
- this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
- },
- enumerable: true,
- configurable: true
- });
- return DefaultLoadingScreen;
- })();
- BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var AudioEngine = (function () {
- function AudioEngine() {
- this._audioContext = null;
- this._audioContextInitialized = false;
- this.canUseWebAudio = false;
- this.WarnedWebAudioUnsupported = false;
- this.unlocked = false;
- if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
- window.AudioContext = window.AudioContext || window.webkitAudioContext;
- this.canUseWebAudio = true;
- }
- if (/iPad|iPhone|iPod/.test(navigator.platform)) {
- this._unlockiOSaudio();
- }
- else {
- this.unlocked = true;
- }
- }
- Object.defineProperty(AudioEngine.prototype, "audioContext", {
- get: function () {
- if (!this._audioContextInitialized) {
- this._initializeAudioContext();
- }
- return this._audioContext;
- },
- enumerable: true,
- configurable: true
- });
- AudioEngine.prototype._unlockiOSaudio = function () {
- var _this = this;
- var unlockaudio = function () {
- var buffer = _this.audioContext.createBuffer(1, 1, 22050);
- var source = _this.audioContext.createBufferSource();
- source.buffer = buffer;
- source.connect(_this.audioContext.destination);
- source.start(0);
- setTimeout(function () {
- if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
- _this.unlocked = true;
- window.removeEventListener('touchend', unlockaudio, false);
- if (_this.onAudioUnlocked) {
- _this.onAudioUnlocked();
- }
- }
- }, 0);
- };
- window.addEventListener('touchend', unlockaudio, false);
- };
- AudioEngine.prototype._initializeAudioContext = function () {
- try {
- if (this.canUseWebAudio) {
- this._audioContext = new AudioContext();
- // create a global volume gain node
- this.masterGain = this._audioContext.createGain();
- this.masterGain.gain.value = 1;
- this.masterGain.connect(this._audioContext.destination);
- this._audioContextInitialized = true;
- }
- }
- catch (e) {
- this.canUseWebAudio = false;
- BABYLON.Tools.Error("Web Audio: " + e.message);
- }
- };
- AudioEngine.prototype.dispose = function () {
- if (this.canUseWebAudio && this._audioContextInitialized) {
- if (this._connectedAnalyser) {
- this._connectedAnalyser.stopDebugCanvas();
- this._connectedAnalyser.dispose();
- this.masterGain.disconnect();
- this.masterGain.connect(this._audioContext.destination);
- this._connectedAnalyser = null;
- }
- this.masterGain.gain.value = 1;
- }
- this.WarnedWebAudioUnsupported = false;
- };
- AudioEngine.prototype.getGlobalVolume = function () {
- if (this.canUseWebAudio && this._audioContextInitialized) {
- return this.masterGain.gain.value;
- }
- else {
- return -1;
- }
- };
- AudioEngine.prototype.setGlobalVolume = function (newVolume) {
- if (this.canUseWebAudio && this._audioContextInitialized) {
- this.masterGain.gain.value = newVolume;
- }
- };
- AudioEngine.prototype.connectToAnalyser = function (analyser) {
- if (this._connectedAnalyser) {
- this._connectedAnalyser.stopDebugCanvas();
- }
- if (this.canUseWebAudio && this._audioContextInitialized) {
- this._connectedAnalyser = analyser;
- this.masterGain.disconnect();
- this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
- }
- };
- return AudioEngine;
- })();
- BABYLON.AudioEngine = AudioEngine;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Sound = (function () {
- /**
- * Create a sound and attach it to a scene
- * @param name Name of your sound
- * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
- * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
- * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
- */
- function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
- var _this = this;
- this.autoplay = false;
- this.loop = false;
- this.useCustomAttenuation = false;
- this.spatialSound = false;
- this.refDistance = 1;
- this.rolloffFactor = 1;
- this.maxDistance = 100;
- this.distanceModel = "linear";
- this._panningModel = "equalpower";
- this._playbackRate = 1;
- this._streaming = false;
- this._startTime = 0;
- this._startOffset = 0;
- this._position = BABYLON.Vector3.Zero();
- this._localDirection = new BABYLON.Vector3(1, 0, 0);
- this._volume = 1;
- this._isLoaded = false;
- this._isReadyToPlay = false;
- this.isPlaying = false;
- this.isPaused = false;
- this._isDirectional = false;
- // Used if you'd like to create a directional sound.
- // If not set, the sound will be omnidirectional
- this._coneInnerAngle = 360;
- this._coneOuterAngle = 360;
- this._coneOuterGain = 0;
- this._isOutputConnected = false;
- this.name = name;
- this._scene = scene;
- this._readyToPlayCallback = readyToPlayCallback;
- // Default custom attenuation function is a linear attenuation
- this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
- if (currentDistance < maxDistance) {
- return currentVolume * (1 - currentDistance / maxDistance);
- }
- else {
- return 0;
- }
- };
- if (options) {
- this.autoplay = options.autoplay || false;
- this.loop = options.loop || false;
- // if volume === 0, we need another way to check this option
- if (options.volume !== undefined) {
- this._volume = options.volume;
- }
- this.spatialSound = options.spatialSound || false;
- this.maxDistance = options.maxDistance || 100;
- this.useCustomAttenuation = options.useCustomAttenuation || false;
- this.rolloffFactor = options.rolloffFactor || 1;
- this.refDistance = options.refDistance || 1;
- this.distanceModel = options.distanceModel || "linear";
- this._playbackRate = options.playbackRate || 1;
- this._streaming = options.streaming || false;
- }
- if (BABYLON.Engine.audioEngine.canUseWebAudio) {
- this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
- this._soundGain.gain.value = this._volume;
- this._inputAudioNode = this._soundGain;
- this._ouputAudioNode = this._soundGain;
- if (this.spatialSound) {
- this._createSpatialParameters();
- }
- this._scene.mainSoundTrack.AddSound(this);
- // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
- if (urlOrArrayBuffer) {
- // If it's an URL
- if (typeof (urlOrArrayBuffer) === "string") {
- // Loading sound using XHR2
- if (!this._streaming) {
- BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
- }
- else {
- this._htmlAudioElement = new Audio(urlOrArrayBuffer);
- this._htmlAudioElement.controls = false;
- this._htmlAudioElement.loop = this.loop;
- this._htmlAudioElement.crossOrigin = "anonymous";
- this._htmlAudioElement.preload = "auto";
- this._htmlAudioElement.addEventListener("canplaythrough", function () {
- _this._isReadyToPlay = true;
- if (_this.autoplay) {
- _this.play();
- }
- if (_this._readyToPlayCallback) {
- _this._readyToPlayCallback();
- }
- });
- document.body.appendChild(this._htmlAudioElement);
- }
- }
- else {
- if (urlOrArrayBuffer instanceof ArrayBuffer) {
- if (urlOrArrayBuffer.byteLength > 0) {
- this._soundLoaded(urlOrArrayBuffer);
- }
- }
- else {
- BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
- }
- }
- }
- }
- else {
- // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
- this._scene.mainSoundTrack.AddSound(this);
- if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
- BABYLON.Tools.Error("Web Audio is not supported by your browser.");
- BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
- }
- // Simulating a ready to play event to avoid breaking code for non web audio browsers
- if (this._readyToPlayCallback) {
- window.setTimeout(function () {
- _this._readyToPlayCallback();
- }, 1000);
- }
- }
- }
- Sound.prototype.dispose = function () {
- if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
- if (this.isPlaying) {
- this.stop();
- }
- this._isReadyToPlay = false;
- if (this.soundTrackId === -1) {
- this._scene.mainSoundTrack.RemoveSound(this);
- }
- else {
- this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
- }
- if (this._soundGain) {
- this._soundGain.disconnect();
- this._soundGain = null;
- }
- if (this._soundPanner) {
- this._soundPanner.disconnect();
- this._soundPanner = null;
- }
- if (this._soundSource) {
- this._soundSource.disconnect();
- this._soundSource = null;
- }
- this._audioBuffer = null;
- if (this._htmlAudioElement) {
- this._htmlAudioElement.pause();
- this._htmlAudioElement.src = "";
- document.body.removeChild(this._htmlAudioElement);
- }
- if (this._connectedMesh) {
- this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
- this._connectedMesh = null;
- }
- }
- };
- Sound.prototype._soundLoaded = function (audioData) {
- var _this = this;
- this._isLoaded = true;
- BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
- _this._audioBuffer = buffer;
- _this._isReadyToPlay = true;
- if (_this.autoplay) {
- _this.play();
- }
- if (_this._readyToPlayCallback) {
- _this._readyToPlayCallback();
- }
- }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
- };
- Sound.prototype.setAudioBuffer = function (audioBuffer) {
- if (BABYLON.Engine.audioEngine.canUseWebAudio) {
- this._audioBuffer = audioBuffer;
- this._isReadyToPlay = true;
- }
- };
- Sound.prototype.updateOptions = function (options) {
- if (options) {
- this.loop = options.loop || this.loop;
- this.maxDistance = options.maxDistance || this.maxDistance;
- this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
- this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
- this.refDistance = options.refDistance || this.refDistance;
- this.distanceModel = options.distanceModel || this.distanceModel;
- this._playbackRate = options.playbackRate || this._playbackRate;
- this._updateSpatialParameters();
- if (this.isPlaying) {
- if (this._streaming) {
- this._htmlAudioElement.playbackRate = this._playbackRate;
- }
- else {
- this._soundSource.playbackRate.value = this._playbackRate;
- }
- }
- }
- };
- Sound.prototype._createSpatialParameters = function () {
- if (BABYLON.Engine.audioEngine.canUseWebAudio) {
- if (this._scene.headphone) {
- this._panningModel = "HRTF";
- }
- this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
- this._updateSpatialParameters();
- this._soundPanner.connect(this._ouputAudioNode);
- this._inputAudioNode = this._soundPanner;
- }
- };
- Sound.prototype._updateSpatialParameters = function () {
- if (this.spatialSound) {
- if (this.useCustomAttenuation) {
- // Tricks to disable in a way embedded Web Audio attenuation
- this._soundPanner.distanceModel = "linear";
- this._soundPanner.maxDistance = Number.MAX_VALUE;
- this._soundPanner.refDistance = 1;
- this._soundPanner.rolloffFactor = 1;
- this._soundPanner.panningModel = this._panningModel;
- }
- else {
- this._soundPanner.distanceModel = this.distanceModel;
- this._soundPanner.maxDistance = this.maxDistance;
- this._soundPanner.refDistance = this.refDistance;
- this._soundPanner.rolloffFactor = this.rolloffFactor;
- this._soundPanner.panningModel = this._panningModel;
- }
- }
- };
- Sound.prototype.switchPanningModelToHRTF = function () {
- this._panningModel = "HRTF";
- this._switchPanningModel();
- };
- Sound.prototype.switchPanningModelToEqualPower = function () {
- this._panningModel = "equalpower";
- this._switchPanningModel();
- };
- Sound.prototype._switchPanningModel = function () {
- if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
- this._soundPanner.panningModel = this._panningModel;
- }
- };
- Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
- if (BABYLON.Engine.audioEngine.canUseWebAudio) {
- if (this._isOutputConnected) {
- this._ouputAudioNode.disconnect();
- }
- this._ouputAudioNode.connect(soundTrackAudioNode);
- this._isOutputConnected = true;
- }
- };
- /**
- * Transform this sound into a directional source
- * @param coneInnerAngle Size of the inner cone in degree
- * @param coneOuterAngle Size of the outer cone in degree
- * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
- */
- Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
- if (coneOuterAngle < coneInnerAngle) {
- BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
- return;
- }
- this._coneInnerAngle = coneInnerAngle;
- this._coneOuterAngle = coneOuterAngle;
- this._coneOuterGain = coneOuterGain;
- this._isDirectional = true;
- if (this.isPlaying && this.loop) {
- this.stop();
- this.play();
- }
- };
- Sound.prototype.setPosition = function (newPosition) {
- this._position = newPosition;
- if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
- this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
- }
- };
- Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
- this._localDirection = newLocalDirection;
- if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
- this._updateDirection();
- }
- };
- Sound.prototype._updateDirection = function () {
- var mat = this._connectedMesh.getWorldMatrix();
- var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
- direction.normalize();
- this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
- };
- Sound.prototype.updateDistanceFromListener = function () {
- if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
- var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
- this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
- }
- };
- Sound.prototype.setAttenuationFunction = function (callback) {
- this._customAttenuationFunction = callback;
- };
- /**
- * Play the sound
- * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
- */
- Sound.prototype.play = function (time) {
- var _this = this;
- if (this._isReadyToPlay && this._scene.audioEnabled) {
- try {
- if (this._startOffset < 0) {
- time = -this._startOffset;
- this._startOffset = 0;
- }
- var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
- if (!this._soundSource || !this._streamingSource) {
- if (this.spatialSound) {
- this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
- if (this._isDirectional) {
- this._soundPanner.coneInnerAngle = this._coneInnerAngle;
- this._soundPanner.coneOuterAngle = this._coneOuterAngle;
- this._soundPanner.coneOuterGain = this._coneOuterGain;
- if (this._connectedMesh) {
- this._updateDirection();
- }
- else {
- this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
- }
- }
- }
- }
- if (this._streaming) {
- if (!this._streamingSource) {
- this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
- this._htmlAudioElement.onended = function () { _this._onended(); };
- this._htmlAudioElement.playbackRate = this._playbackRate;
- }
- this._streamingSource.disconnect();
- this._streamingSource.connect(this._inputAudioNode);
- this._htmlAudioElement.play();
- }
- else {
- this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
- this._soundSource.buffer = this._audioBuffer;
- this._soundSource.connect(this._inputAudioNode);
- this._soundSource.loop = this.loop;
- this._soundSource.playbackRate.value = this._playbackRate;
- this._soundSource.onended = function () { _this._onended(); };
- this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
- }
- this._startTime = startTime;
- this.isPlaying = true;
- this.isPaused = false;
- }
- catch (ex) {
- BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
- }
- }
- };
- Sound.prototype._onended = function () {
- this.isPlaying = false;
- if (this.onended) {
- this.onended();
- }
- };
- /**
- * Stop the sound
- * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
- */
- Sound.prototype.stop = function (time) {
- if (this.isPlaying) {
- if (this._streaming) {
- this._htmlAudioElement.pause();
- // Test needed for Firefox or it will generate an Invalid State Error
- if (this._htmlAudioElement.currentTime > 0) {
- this._htmlAudioElement.currentTime = 0;
- }
- }
- else {
- var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
- this._soundSource.stop(stopTime);
- if (!this.isPaused) {
- this._startOffset = 0;
- }
- }
- this.isPlaying = false;
- }
- };
- Sound.prototype.pause = function () {
- if (this.isPlaying) {
- this.isPaused = true;
- if (this._streaming) {
- this._htmlAudioElement.pause();
- }
- else {
- this.stop(0);
- this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
- }
- }
- };
- Sound.prototype.setVolume = function (newVolume, time) {
- if (BABYLON.Engine.audioEngine.canUseWebAudio) {
- if (time) {
- this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
- this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
- this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
- }
- else {
- this._soundGain.gain.value = newVolume;
- }
- }
- this._volume = newVolume;
- };
- Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
- this._playbackRate = newPlaybackRate;
- if (this.isPlaying) {
- if (this._streaming) {
- this._htmlAudioElement.playbackRate = this._playbackRate;
- }
- else {
- this._soundSource.playbackRate.value = this._playbackRate;
- }
- }
- };
- Sound.prototype.getVolume = function () {
- return this._volume;
- };
- Sound.prototype.attachToMesh = function (meshToConnectTo) {
- var _this = this;
- if (this._connectedMesh) {
- this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
- this._registerFunc = null;
- }
- this._connectedMesh = meshToConnectTo;
- if (!this.spatialSound) {
- this.spatialSound = true;
- this._createSpatialParameters();
- if (this.isPlaying && this.loop) {
- this.stop();
- this.play();
- }
- }
- this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
- this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
- meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
- };
- Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
- this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
- if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
- this._updateDirection();
- }
- };
- Sound.prototype.clone = function () {
- var _this = this;
- if (!this._streaming) {
- var setBufferAndRun = function () {
- if (_this._isReadyToPlay) {
- clonedSound._audioBuffer = _this.getAudioBuffer();
- clonedSound._isReadyToPlay = true;
- if (clonedSound.autoplay) {
- clonedSound.play();
- }
- }
- else {
- window.setTimeout(setBufferAndRun, 300);
- }
- };
- var currentOptions = {
- autoplay: this.autoplay, loop: this.loop,
- volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
- useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
- refDistance: this.refDistance, distanceModel: this.distanceModel
- };
- var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
- if (this.useCustomAttenuation) {
- clonedSound.setAttenuationFunction(this._customAttenuationFunction);
- }
- clonedSound.setPosition(this._position);
- clonedSound.setPlaybackRate(this._playbackRate);
- setBufferAndRun();
- return clonedSound;
- }
- else {
- return null;
- }
- };
- Sound.prototype.getAudioBuffer = function () {
- return this._audioBuffer;
- };
- Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
- var soundName = parsedSound.name;
- var soundUrl;
- if (parsedSound.url) {
- soundUrl = rootUrl + parsedSound.url;
- }
- else {
- soundUrl = rootUrl + soundName;
- }
- var options = {
- autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
- spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
- rolloffFactor: parsedSound.rolloffFactor,
- refDistance: parsedSound.refDistance,
- distanceModel: parsedSound.distanceModel,
- playbackRate: parsedSound.playbackRate
- };
- var newSound;
- if (!sourceSound) {
- newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
- scene._addPendingData(newSound);
- }
- else {
- var setBufferAndRun = function () {
- if (sourceSound._isReadyToPlay) {
- newSound._audioBuffer = sourceSound.getAudioBuffer();
- newSound._isReadyToPlay = true;
- if (newSound.autoplay) {
- newSound.play();
- }
- }
- else {
- window.setTimeout(setBufferAndRun, 300);
- }
- };
- newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
- setBufferAndRun();
- }
- if (parsedSound.position) {
- var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
- newSound.setPosition(soundPosition);
- }
- if (parsedSound.isDirectional) {
- newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
- if (parsedSound.localDirectionToMesh) {
- var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
- newSound.setLocalDirectionToMesh(localDirectionToMesh);
- }
- }
- if (parsedSound.connectedMeshId) {
- var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
- if (connectedMesh) {
- newSound.attachToMesh(connectedMesh);
- }
- }
- return newSound;
- };
- return Sound;
- })();
- BABYLON.Sound = Sound;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var SoundTrack = (function () {
- function SoundTrack(scene, options) {
- this.id = -1;
- this._isMainTrack = false;
- this._isInitialized = false;
- this._scene = scene;
- this.soundCollection = new Array();
- this._options = options;
- if (!this._isMainTrack) {
- this._scene.soundTracks.push(this);
- this.id = this._scene.soundTracks.length - 1;
- }
- }
- SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
- if (BABYLON.Engine.audioEngine.canUseWebAudio) {
- this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
- this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
- if (this._options) {
- if (this._options.volume) {
- this._outputAudioNode.gain.value = this._options.volume;
- }
- if (this._options.mainTrack) {
- this._isMainTrack = this._options.mainTrack;
- }
- }
- this._isInitialized = true;
- }
- };
- SoundTrack.prototype.dispose = function () {
- if (BABYLON.Engine.audioEngine.canUseWebAudio) {
- if (this._connectedAnalyser) {
- this._connectedAnalyser.stopDebugCanvas();
- }
- while (this.soundCollection.length) {
- this.soundCollection[0].dispose();
- }
- if (this._outputAudioNode) {
- this._outputAudioNode.disconnect();
- }
- this._outputAudioNode = null;
- }
- };
- SoundTrack.prototype.AddSound = function (sound) {
- if (!this._isInitialized) {
- this._initializeSoundTrackAudioGraph();
- }
- if (BABYLON.Engine.audioEngine.canUseWebAudio) {
- sound.connectToSoundTrackAudioNode(this._outputAudioNode);
- }
- if (sound.soundTrackId) {
- if (sound.soundTrackId === -1) {
- this._scene.mainSoundTrack.RemoveSound(sound);
- }
- else {
- this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
- }
- }
- this.soundCollection.push(sound);
- sound.soundTrackId = this.id;
- };
- SoundTrack.prototype.RemoveSound = function (sound) {
- var index = this.soundCollection.indexOf(sound);
- if (index !== -1) {
- this.soundCollection.splice(index, 1);
- }
- };
- SoundTrack.prototype.setVolume = function (newVolume) {
- if (BABYLON.Engine.audioEngine.canUseWebAudio) {
- this._outputAudioNode.gain.value = newVolume;
- }
- };
- SoundTrack.prototype.switchPanningModelToHRTF = function () {
- if (BABYLON.Engine.audioEngine.canUseWebAudio) {
- for (var i = 0; i < this.soundCollection.length; i++) {
- this.soundCollection[i].switchPanningModelToHRTF();
- }
- }
- };
- SoundTrack.prototype.switchPanningModelToEqualPower = function () {
- if (BABYLON.Engine.audioEngine.canUseWebAudio) {
- for (var i = 0; i < this.soundCollection.length; i++) {
- this.soundCollection[i].switchPanningModelToEqualPower();
- }
- }
- };
- SoundTrack.prototype.connectToAnalyser = function (analyser) {
- if (this._connectedAnalyser) {
- this._connectedAnalyser.stopDebugCanvas();
- }
- this._connectedAnalyser = analyser;
- if (BABYLON.Engine.audioEngine.canUseWebAudio) {
- this._outputAudioNode.disconnect();
- this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
- }
- };
- return SoundTrack;
- })();
- BABYLON.SoundTrack = SoundTrack;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var SIMDVector3 = (function () {
- function SIMDVector3() {
- }
- SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
- var v = SIMD.float32x4.loadXYZ(vector._data, 0);
- var m0 = SIMD.float32x4.load(transformation.m, 0);
- var m1 = SIMD.float32x4.load(transformation.m, 4);
- var m2 = SIMD.float32x4.load(transformation.m, 8);
- var m3 = SIMD.float32x4.load(transformation.m, 12);
- var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 0, 0, 0, 0), m0), SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 1, 1, 1, 1), m1)), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 2, 2, 2, 2), m2), m3));
- r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
- SIMD.float32x4.storeXYZ(result._data, 0, r);
- };
- SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
- var v0 = SIMD.float32x4.splat(x);
- var v1 = SIMD.float32x4.splat(y);
- var v2 = SIMD.float32x4.splat(z);
- var m0 = SIMD.float32x4.load(transformation.m, 0);
- var m1 = SIMD.float32x4.load(transformation.m, 4);
- var m2 = SIMD.float32x4.load(transformation.m, 8);
- var m3 = SIMD.float32x4.load(transformation.m, 12);
- var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(v0, m0), SIMD.float32x4.mul(v1, m1)), SIMD.float32x4.add(SIMD.float32x4.mul(v2, m2), m3));
- r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
- SIMD.float32x4.storeXYZ(result._data, 0, r);
- };
- return SIMDVector3;
- })();
- BABYLON.SIMDVector3 = SIMDVector3;
- var SIMDMatrix = (function () {
- function SIMDMatrix() {
- }
- SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
- if (offset === void 0) { offset = 0; }
- var tm = this.m;
- var om = other.m;
- var om0 = SIMD.float32x4.load(om, 0);
- var om1 = SIMD.float32x4.load(om, 4);
- var om2 = SIMD.float32x4.load(om, 8);
- var om3 = SIMD.float32x4.load(om, 12);
- var tm0 = SIMD.float32x4.load(tm, 0);
- SIMD.float32x4.store(result, offset + 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 3, 3, 3, 3), om3)))));
- var tm1 = SIMD.float32x4.load(tm, 4);
- SIMD.float32x4.store(result, offset + 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 3, 3, 3, 3), om3)))));
- var tm2 = SIMD.float32x4.load(tm, 8);
- SIMD.float32x4.store(result, offset + 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 3, 3, 3, 3), om3)))));
- var tm3 = SIMD.float32x4.load(tm, 12);
- SIMD.float32x4.store(result, offset + 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 3, 3, 3, 3), om3)))));
- };
- SIMDMatrix.prototype.invertToRefSIMD = function (other) {
- var src = this.m;
- var dest = other.m;
- var row0, row1, row2, row3;
- var tmp1;
- var minor0, minor1, minor2, minor3;
- var det;
- // Load the 4 rows
- var src0 = SIMD.float32x4.load(src, 0);
- var src1 = SIMD.float32x4.load(src, 4);
- var src2 = SIMD.float32x4.load(src, 8);
- var src3 = SIMD.float32x4.load(src, 12);
- // Transpose the source matrix. Sort of. Not a true transpose operation
- tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
- row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
- row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
- row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
- tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
- row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
- row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
- row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
- // This is a true transposition, but it will lead to an incorrect result
- //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
- //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
- //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
- //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
- //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
- //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
- //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
- //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
- // ----
- tmp1 = SIMD.float32x4.mul(row2, row3);
- tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
- minor0 = SIMD.float32x4.mul(row1, tmp1);
- minor1 = SIMD.float32x4.mul(row0, tmp1);
- tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
- minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
- minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
- minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
- // ----
- tmp1 = SIMD.float32x4.mul(row1, row2);
- tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
- minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
- minor3 = SIMD.float32x4.mul(row0, tmp1);
- tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
- minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
- minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
- minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
- // ----
- tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
- tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
- row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
- minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
- minor2 = SIMD.float32x4.mul(row0, tmp1);
- tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
- minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
- minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
- minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
- // ----
- tmp1 = SIMD.float32x4.mul(row0, row1);
- tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
- minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
- minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
- tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
- minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
- minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
- // ----
- tmp1 = SIMD.float32x4.mul(row0, row3);
- tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
- minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
- minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
- tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
- minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
- minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
- // ----
- tmp1 = SIMD.float32x4.mul(row0, row2);
- tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
- minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
- minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
- tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
- minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
- minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
- // Compute determinant
- det = SIMD.float32x4.mul(row0, minor0);
- det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
- det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
- tmp1 = SIMD.float32x4.reciprocalApproximation(det);
- det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
- det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
- // These shuffles aren't necessary if the faulty transposition is done
- // up at the top of this function.
- //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
- //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
- //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
- //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
- // Compute final values by multiplying with 1/det
- minor0 = SIMD.float32x4.mul(det, minor0);
- minor1 = SIMD.float32x4.mul(det, minor1);
- minor2 = SIMD.float32x4.mul(det, minor2);
- minor3 = SIMD.float32x4.mul(det, minor3);
- SIMD.float32x4.store(dest, 0, minor0);
- SIMD.float32x4.store(dest, 4, minor1);
- SIMD.float32x4.store(dest, 8, minor2);
- SIMD.float32x4.store(dest, 12, minor3);
- return this;
- };
- SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
- var out = result.m;
- var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
- var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
- var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
- // cc.kmVec3Subtract(f, pCenter, pEye);
- var f = SIMD.float32x4.sub(center, eye);
- // cc.kmVec3Normalize(f, f);
- var tmp = SIMD.float32x4.mul(f, f);
- tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
- f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
- // cc.kmVec3Assign(up, pUp);
- // cc.kmVec3Normalize(up, up);
- tmp = SIMD.float32x4.mul(up, up);
- tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
- up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
- // cc.kmVec3Cross(s, f, up);
- 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)));
- // cc.kmVec3Normalize(s, s);
- tmp = SIMD.float32x4.mul(s, s);
- tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
- s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
- // cc.kmVec3Cross(u, s, f);
- 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)));
- // cc.kmVec3Normalize(s, s);
- tmp = SIMD.float32x4.mul(s, s);
- tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
- s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
- var zero = SIMD.float32x4.splat(0.0);
- s = SIMD.float32x4.neg(s);
- var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
- var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
- var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
- var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
- tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
- tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
- var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
- var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
- var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
- var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
- var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
- var b3 = SIMD.float32x4.neg(eye);
- b3 = SIMD.float32x4.withW(b3, 1.0);
- SIMD.float32x4.store(out, 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
- SIMD.float32x4.store(out, 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
- SIMD.float32x4.store(out, 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
- SIMD.float32x4.store(out, 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
- };
- return SIMDMatrix;
- })();
- BABYLON.SIMDMatrix = SIMDMatrix;
- var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
- var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
- var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
- var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
- var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
- var SIMDHelper = (function () {
- function SIMDHelper() {
- }
- Object.defineProperty(SIMDHelper, "IsEnabled", {
- get: function () {
- return SIMDHelper._isEnabled;
- },
- enumerable: true,
- configurable: true
- });
- SIMDHelper.DisableSIMD = function () {
- // Replace functions
- BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
- BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
- BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
- BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
- BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
- SIMDHelper._isEnabled = false;
- };
- SIMDHelper.EnableSIMD = function () {
- if (window.SIMD === undefined) {
- return;
- }
- // Replace functions
- BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
- BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
- BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
- BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
- BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
- Object.defineProperty(BABYLON.Vector3.prototype, "x", {
- get: function () { return this._data[0]; },
- set: function (value) {
- if (!this._data) {
- this._data = new Float32Array(3);
- }
- this._data[0] = value;
- }
- });
- Object.defineProperty(BABYLON.Vector3.prototype, "y", {
- get: function () { return this._data[1]; },
- set: function (value) {
- this._data[1] = value;
- }
- });
- Object.defineProperty(BABYLON.Vector3.prototype, "z", {
- get: function () { return this._data[2]; },
- set: function (value) {
- this._data[2] = value;
- }
- });
- SIMDHelper._isEnabled = true;
- };
- SIMDHelper._isEnabled = false;
- return SIMDHelper;
- })();
- BABYLON.SIMDHelper = SIMDHelper;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var ShaderMaterial = (function (_super) {
- __extends(ShaderMaterial, _super);
- function ShaderMaterial(name, scene, shaderPath, options) {
- _super.call(this, name, scene);
- this._textures = {};
- this._floats = {};
- this._floatsArrays = {};
- this._colors3 = {};
- this._colors4 = {};
- this._vectors2 = {};
- this._vectors3 = {};
- this._vectors4 = {};
- this._matrices = {};
- this._matrices3x3 = {};
- this._matrices2x2 = {};
- this._cachedWorldViewMatrix = new BABYLON.Matrix();
- this._shaderPath = shaderPath;
- options.needAlphaBlending = options.needAlphaBlending || false;
- options.needAlphaTesting = options.needAlphaTesting || false;
- options.attributes = options.attributes || ["position", "normal", "uv"];
- options.uniforms = options.uniforms || ["worldViewProjection"];
- options.samplers = options.samplers || [];
- options.defines = options.defines || [];
- this._options = options;
- }
- ShaderMaterial.prototype.needAlphaBlending = function () {
- return this._options.needAlphaBlending;
- };
- ShaderMaterial.prototype.needAlphaTesting = function () {
- return this._options.needAlphaTesting;
- };
- ShaderMaterial.prototype._checkUniform = function (uniformName) {
- if (this._options.uniforms.indexOf(uniformName) === -1) {
- this._options.uniforms.push(uniformName);
- }
- };
- ShaderMaterial.prototype.setTexture = function (name, texture) {
- if (this._options.samplers.indexOf(name) === -1) {
- this._options.samplers.push(name);
- }
- this._textures[name] = texture;
- return this;
- };
- ShaderMaterial.prototype.setFloat = function (name, value) {
- this._checkUniform(name);
- this._floats[name] = value;
- return this;
- };
- ShaderMaterial.prototype.setFloats = function (name, value) {
- this._checkUniform(name);
- this._floatsArrays[name] = value;
- return this;
- };
- ShaderMaterial.prototype.setColor3 = function (name, value) {
- this._checkUniform(name);
- this._colors3[name] = value;
- return this;
- };
- ShaderMaterial.prototype.setColor4 = function (name, value) {
- this._checkUniform(name);
- this._colors4[name] = value;
- return this;
- };
- ShaderMaterial.prototype.setVector2 = function (name, value) {
- this._checkUniform(name);
- this._vectors2[name] = value;
- return this;
- };
- ShaderMaterial.prototype.setVector3 = function (name, value) {
- this._checkUniform(name);
- this._vectors3[name] = value;
- return this;
- };
- ShaderMaterial.prototype.setVector4 = function (name, value) {
- this._checkUniform(name);
- this._vectors4[name] = value;
- return this;
- };
- ShaderMaterial.prototype.setMatrix = function (name, value) {
- this._checkUniform(name);
- this._matrices[name] = value;
- return this;
- };
- ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
- this._checkUniform(name);
- this._matrices3x3[name] = value;
- return this;
- };
- ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
- this._checkUniform(name);
- this._matrices2x2[name] = value;
- return this;
- };
- ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
- var scene = this.getScene();
- var engine = scene.getEngine();
- if (!this.checkReadyOnEveryCall) {
- if (this._renderId === scene.getRenderId()) {
- return true;
- }
- }
- // Instances
- var defines = [];
- var fallbacks = new BABYLON.EffectFallbacks();
- if (useInstances) {
- defines.push("#define INSTANCES");
- }
- for (var index = 0; index < this._options.defines.length; index++) {
- defines.push(this._options.defines[index]);
- }
- // Bones
- if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
- defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
- defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
- fallbacks.addCPUSkinningFallback(0, mesh);
- }
- // Alpha test
- if (engine.getAlphaTesting()) {
- defines.push("#define ALPHATEST");
- }
- var previousEffect = this._effect;
- var join = defines.join("\n");
- this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
- if (!this._effect.isReady()) {
- return false;
- }
- if (previousEffect !== this._effect) {
- scene.resetCachedMaterial();
- }
- this._renderId = scene.getRenderId();
- return true;
- };
- ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
- var scene = this.getScene();
- if (this._options.uniforms.indexOf("world") !== -1) {
- this._effect.setMatrix("world", world);
- }
- if (this._options.uniforms.indexOf("worldView") !== -1) {
- world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
- this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
- }
- if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
- this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
- }
- };
- ShaderMaterial.prototype.bind = function (world, mesh) {
- // Std values
- this.bindOnlyWorldMatrix(world);
- if (this.getScene().getCachedMaterial() !== this) {
- if (this._options.uniforms.indexOf("view") !== -1) {
- this._effect.setMatrix("view", this.getScene().getViewMatrix());
- }
- if (this._options.uniforms.indexOf("projection") !== -1) {
- this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
- }
- if (this._options.uniforms.indexOf("viewProjection") !== -1) {
- this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
- }
- // Bones
- if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
- this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
- }
- // Texture
- for (var name in this._textures) {
- this._effect.setTexture(name, this._textures[name]);
- }
- // Float
- for (name in this._floats) {
- this._effect.setFloat(name, this._floats[name]);
- }
- // Float s
- for (name in this._floatsArrays) {
- this._effect.setArray(name, this._floatsArrays[name]);
- }
- // Color3
- for (name in this._colors3) {
- this._effect.setColor3(name, this._colors3[name]);
- }
- // Color4
- for (name in this._colors4) {
- var color = this._colors4[name];
- this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
- }
- // Vector2
- for (name in this._vectors2) {
- this._effect.setVector2(name, this._vectors2[name]);
- }
- // Vector3
- for (name in this._vectors3) {
- this._effect.setVector3(name, this._vectors3[name]);
- }
- // Vector4
- for (name in this._vectors4) {
- this._effect.setVector4(name, this._vectors4[name]);
- }
- // Matrix
- for (name in this._matrices) {
- this._effect.setMatrix(name, this._matrices[name]);
- }
- // Matrix 3x3
- for (name in this._matrices3x3) {
- this._effect.setMatrix3x3(name, this._matrices3x3[name]);
- }
- // Matrix 2x2
- for (name in this._matrices2x2) {
- this._effect.setMatrix2x2(name, this._matrices2x2[name]);
- }
- }
- _super.prototype.bind.call(this, world, mesh);
- };
- ShaderMaterial.prototype.clone = function (name) {
- var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
- return newShaderMaterial;
- };
- ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
- if (forceDisposeTextures) {
- for (var name in this._textures) {
- this._textures[name].dispose();
- }
- }
- this._textures = {};
- _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
- };
- ShaderMaterial.prototype.serialize = function () {
- var serializationObject = BABYLON.SerializationHelper.Serialize(this);
- serializationObject.customType = "BABYLON.ShaderMaterial";
- serializationObject.options = this._options;
- serializationObject.shaderPath = this._shaderPath;
- // Texture
- serializationObject.textures = {};
- for (var name in this._textures) {
- serializationObject.textures[name] = this._textures[name].serialize();
- }
- // Float
- serializationObject.floats = {};
- for (name in this._floats) {
- serializationObject.floats[name] = this._floats[name];
- }
- // Float s
- serializationObject.floatArrays = {};
- for (name in this._floatsArrays) {
- serializationObject.floatArrays[name] = this._floatsArrays[name];
- }
- // Color3
- serializationObject.colors3 = {};
- for (name in this._colors3) {
- serializationObject.colors3[name] = this._colors3[name].asArray();
- }
- // Color4
- serializationObject.colors4 = {};
- for (name in this._colors4) {
- serializationObject.colors4[name] = this._colors4[name].asArray();
- }
- // Vector2
- serializationObject.vectors2 = {};
- for (name in this._vectors2) {
- serializationObject.vectors2[name] = this._vectors2[name].asArray();
- }
- // Vector3
- serializationObject.vectors3 = {};
- for (name in this._vectors3) {
- serializationObject.vectors3[name] = this._vectors3[name].asArray();
- }
- // Vector4
- serializationObject.vectors4 = {};
- for (name in this._vectors4) {
- serializationObject.vectors4[name] = this._vectors4[name].asArray();
- }
- // Matrix
- serializationObject.matrices = {};
- for (name in this._matrices) {
- serializationObject.matrices[name] = this._matrices[name].asArray();
- }
- // Matrix 3x3
- serializationObject.matrices3x3 = {};
- for (name in this._matrices3x3) {
- serializationObject.matrices3x3[name] = this._matrices3x3[name];
- }
- // Matrix 2x2
- serializationObject.matrices2x2 = {};
- for (name in this._matrices2x2) {
- serializationObject.matrices2x2[name] = this._matrices2x2[name];
- }
- return serializationObject;
- };
- ShaderMaterial.Parse = function (source, scene, rootUrl) {
- var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
- // Texture
- for (var name in source.textures) {
- material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
- }
- // Float
- for (name in source.floats) {
- material.setFloat(name, source.floats[name]);
- }
- // Float s
- for (name in source.floatsArrays) {
- material.setFloats(name, source.floatsArrays[name]);
- }
- // Color3
- for (name in source.colors3) {
- material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
- }
- // Color4
- for (name in source.colors4) {
- material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
- }
- // Vector2
- for (name in source.vectors2) {
- material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
- }
- // Vector3
- for (name in source.vectors3) {
- material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
- }
- // Vector4
- for (name in source.vectors4) {
- material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
- }
- // Matrix
- for (name in source.matrices) {
- material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
- }
- // Matrix 3x3
- for (name in source.matrices3x3) {
- material.setMatrix3x3(name, source.matrices3x3[name]);
- }
- // Matrix 2x2
- for (name in source.matrices2x2) {
- material.setMatrix2x2(name, source.matrices2x2[name]);
- }
- return material;
- };
- return ShaderMaterial;
- })(BABYLON.Material);
- BABYLON.ShaderMaterial = ShaderMaterial;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Internals;
- (function (Internals) {
- // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
- // All values and structures referenced from:
- // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
- var DDS_MAGIC = 0x20534444;
- 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;
- var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
- 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;
- var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
- function FourCCToInt32(value) {
- return value.charCodeAt(0) +
- (value.charCodeAt(1) << 8) +
- (value.charCodeAt(2) << 16) +
- (value.charCodeAt(3) << 24);
- }
- function Int32ToFourCC(value) {
- return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
- }
- var FOURCC_DXT1 = FourCCToInt32("DXT1");
- var FOURCC_DXT3 = FourCCToInt32("DXT3");
- var FOURCC_DXT5 = FourCCToInt32("DXT5");
- var headerLengthInt = 31; // The header length in 32 bit ints
- // Offsets into the header array
- var off_magic = 0;
- var off_size = 1;
- var off_flags = 2;
- var off_height = 3;
- var off_width = 4;
- var off_mipmapCount = 7;
- var off_pfFlags = 20;
- var off_pfFourCC = 21;
- var off_RGBbpp = 22;
- var off_RMask = 23;
- var off_GMask = 24;
- var off_BMask = 25;
- var off_AMask = 26;
- var off_caps1 = 27;
- var off_caps2 = 28;
- ;
- var DDSTools = (function () {
- function DDSTools() {
- }
- DDSTools.GetDDSInfo = function (arrayBuffer) {
- var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
- var mipmapCount = 1;
- if (header[off_flags] & DDSD_MIPMAPCOUNT) {
- mipmapCount = Math.max(1, header[off_mipmapCount]);
- }
- return {
- width: header[off_width],
- height: header[off_height],
- mipmapCount: mipmapCount,
- isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
- isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
- isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
- isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
- };
- };
- DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
- var byteArray = new Uint8Array(dataLength);
- var srcData = new Uint8Array(arrayBuffer);
- var index = 0;
- for (var y = height - 1; y >= 0; y--) {
- for (var x = 0; x < width; x++) {
- var srcPos = dataOffset + (x + y * width) * 4;
- byteArray[index + 2] = srcData[srcPos];
- byteArray[index + 1] = srcData[srcPos + 1];
- byteArray[index] = srcData[srcPos + 2];
- byteArray[index + 3] = srcData[srcPos + 3];
- index += 4;
- }
- }
- return byteArray;
- };
- DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
- var byteArray = new Uint8Array(dataLength);
- var srcData = new Uint8Array(arrayBuffer);
- var index = 0;
- for (var y = height - 1; y >= 0; y--) {
- for (var x = 0; x < width; x++) {
- var srcPos = dataOffset + (x + y * width) * 3;
- byteArray[index + 2] = srcData[srcPos];
- byteArray[index + 1] = srcData[srcPos + 1];
- byteArray[index] = srcData[srcPos + 2];
- index += 3;
- }
- }
- return byteArray;
- };
- DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
- var byteArray = new Uint8Array(dataLength);
- var srcData = new Uint8Array(arrayBuffer);
- var index = 0;
- for (var y = height - 1; y >= 0; y--) {
- for (var x = 0; x < width; x++) {
- var srcPos = dataOffset + (x + y * width);
- byteArray[index] = srcData[srcPos];
- index++;
- }
- }
- return byteArray;
- };
- DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
- var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
- if (header[off_magic] != DDS_MAGIC) {
- BABYLON.Tools.Error("Invalid magic number in DDS header");
- return;
- }
- if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
- BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
- return;
- }
- if (info.isFourCC) {
- fourCC = header[off_pfFourCC];
- switch (fourCC) {
- case FOURCC_DXT1:
- blockBytes = 8;
- internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
- break;
- case FOURCC_DXT3:
- blockBytes = 16;
- internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
- break;
- case FOURCC_DXT5:
- blockBytes = 16;
- internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
- break;
- default:
- console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
- return;
- }
- }
- mipmapCount = 1;
- if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
- mipmapCount = Math.max(1, header[off_mipmapCount]);
- }
- var bpp = header[off_RGBbpp];
- for (var face = 0; face < faces; face++) {
- var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
- width = header[off_width];
- height = header[off_height];
- dataOffset = header[off_size] + 4;
- for (i = 0; i < mipmapCount; ++i) {
- if (info.isRGB) {
- if (bpp === 24) {
- dataLength = width * height * 3;
- byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
- gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
- }
- else {
- dataLength = width * height * 4;
- byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
- gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
- }
- }
- else if (info.isLuminance) {
- var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
- var unpaddedRowSize = width;
- var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
- dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
- byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
- gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
- }
- else {
- dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
- byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
- gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
- }
- dataOffset += dataLength;
- width *= 0.5;
- height *= 0.5;
- width = Math.max(1.0, width);
- height = Math.max(1.0, height);
- }
- }
- };
- return DDSTools;
- })();
- Internals.DDSTools = DDSTools;
- })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var CannonJSPlugin = (function () {
- function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
- if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
- if (iterations === void 0) { iterations = 10; }
- this._useDeltaForWorldStep = _useDeltaForWorldStep;
- this.name = "CannonJSPlugin";
- this._physicsMaterials = [];
- this._fixedTimeStep = 1 / 60;
- //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
- this._currentCollisionGroup = 2;
- this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
- this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
- this._tmpPosition = BABYLON.Vector3.Zero();
- this._tmpQuaternion = new BABYLON.Quaternion();
- this._tmpDeltaPosition = BABYLON.Vector3.Zero();
- this._tmpDeltaRotation = new BABYLON.Quaternion();
- this._tmpUnityRotation = new BABYLON.Quaternion();
- if (!this.isSupported()) {
- BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
- return;
- }
- this.world = new CANNON.World();
- this.world.broadphase = new CANNON.NaiveBroadphase();
- this.world.solver.iterations = iterations;
- }
- CannonJSPlugin.prototype.setGravity = function (gravity) {
- this.world.gravity.copy(gravity);
- };
- CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
- this._fixedTimeStep = timeStep;
- };
- CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
- this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
- };
- CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
- var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
- var impulse = new CANNON.Vec3(force.x, force.y, force.z);
- impostor.physicsBody.applyImpulse(impulse, worldPoint);
- };
- CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
- var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
- var impulse = new CANNON.Vec3(force.x, force.y, force.z);
- impostor.physicsBody.applyImpulse(impulse, worldPoint);
- };
- CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
- //parent-child relationship. Does this impostor has a parent impostor?
- if (impostor.parent) {
- if (impostor.physicsBody) {
- this.removePhysicsBody(impostor);
- //TODO is that needed?
- impostor.forceUpdate();
- }
- return;
- }
- //should a new body be created for this impostor?
- if (impostor.isBodyInitRequired()) {
- var shape = this._createShape(impostor);
- //unregister events, if body is being changed
- var oldBody = impostor.physicsBody;
- if (oldBody) {
- this.removePhysicsBody(impostor);
- }
- //create the body and material
- var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
- var bodyCreationObject = {
- mass: impostor.getParam("mass"),
- material: material
- };
- // A simple extend, in case native options were used.
- var nativeOptions = impostor.getParam("nativeOptions");
- for (var key in nativeOptions) {
- if (nativeOptions.hasOwnProperty(key)) {
- bodyCreationObject[key] = nativeOptions[key];
- }
- }
- impostor.physicsBody = new CANNON.Body(bodyCreationObject);
- impostor.physicsBody.addEventListener("collide", impostor.onCollide);
- this.world.addEventListener("preStep", impostor.beforeStep);
- this.world.addEventListener("postStep", impostor.afterStep);
- impostor.physicsBody.addShape(shape);
- this.world.add(impostor.physicsBody);
- //try to keep the body moving in the right direction by taking old properties.
- //Should be tested!
- if (oldBody) {
- ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
- impostor.physicsBody[param].copy(oldBody[param]);
- });
- }
- this._processChildMeshes(impostor);
- }
- //now update the body's transformation
- this._updatePhysicsBodyTransformation(impostor);
- };
- CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
- var _this = this;
- var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
- if (meshChildren.length) {
- var processMesh = function (localPosition, mesh) {
- var childImpostor = mesh.getPhysicsImpostor();
- if (childImpostor) {
- var parent = childImpostor.parent;
- if (parent !== mainImpostor) {
- var localPosition = mesh.position;
- if (childImpostor.physicsBody) {
- _this.removePhysicsBody(childImpostor);
- childImpostor.physicsBody = null;
- }
- childImpostor.parent = mainImpostor;
- childImpostor.resetUpdateFlags();
- mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
- //Add the mass of the children.
- mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
- }
- }
- mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
- };
- meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
- }
- };
- CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
- impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
- this.world.removeEventListener("preStep", impostor.beforeStep);
- this.world.removeEventListener("postStep", impostor.afterStep);
- this.world.remove(impostor.physicsBody);
- };
- CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
- var mainBody = impostorJoint.mainImpostor.physicsBody;
- var connectedBody = impostorJoint.connectedImpostor.physicsBody;
- if (!mainBody || !connectedBody) {
- return;
- }
- var constraint;
- var jointData = impostorJoint.joint.jointData;
- //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
- var constraintData = {
- pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
- pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
- axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
- axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
- maxForce: jointData.nativeParams.maxForce,
- collideConnected: !!jointData.collision
- };
- //Not needed, Cannon has a collideConnected flag
- /*if (!jointData.collision) {
- //add 1st body to a collision group of its own, if it is not in 1
- if (mainBody.collisionFilterGroup === 1) {
- mainBody.collisionFilterGroup = this._currentCollisionGroup;
- this._currentCollisionGroup <<= 1;
- }
- if (connectedBody.collisionFilterGroup === 1) {
- connectedBody.collisionFilterGroup = this._currentCollisionGroup;
- this._currentCollisionGroup <<= 1;
- }
- //add their mask to the collisionFilterMask of each other:
- connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
- mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
- }*/
- switch (impostorJoint.joint.type) {
- case BABYLON.PhysicsJoint.HingeJoint:
- case BABYLON.PhysicsJoint.Hinge2Joint:
- constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
- break;
- case BABYLON.PhysicsJoint.DistanceJoint:
- constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
- break;
- case BABYLON.PhysicsJoint.SpringJoint:
- var springData = jointData;
- constraint = new CANNON.Spring(mainBody, connectedBody, {
- restLength: springData.length,
- stiffness: springData.stiffness,
- damping: springData.damping,
- localAnchorA: constraintData.pivotA,
- localAnchorB: constraintData.pivotB
- });
- break;
- case BABYLON.PhysicsJoint.PointToPointJoint:
- case BABYLON.PhysicsJoint.BallAndSocketJoint:
- default:
- constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
- break;
- }
- //set the collideConnected flag after the creation, since DistanceJoint ignores it.
- constraint.collideConnected = !!jointData.collision;
- impostorJoint.joint.physicsJoint = constraint;
- //don't add spring as constraint, as it is not one.
- if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
- this.world.addConstraint(constraint);
- }
- else {
- impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
- constraint.applyForce();
- });
- }
- };
- CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
- this.world.removeConstraint(impostorJoint.joint.physicsJoint);
- };
- CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
- var index;
- var mat;
- for (index = 0; index < this._physicsMaterials.length; index++) {
- mat = this._physicsMaterials[index];
- if (mat.friction === friction && mat.restitution === restitution) {
- return mat;
- }
- }
- var currentMat = new CANNON.Material(name);
- currentMat.friction = friction;
- currentMat.restitution = restitution;
- this._physicsMaterials.push(currentMat);
- return currentMat;
- };
- CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
- return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
- };
- CannonJSPlugin.prototype._createShape = function (impostor) {
- var object = impostor.object;
- var returnValue;
- var extendSize = impostor.getObjectExtendSize();
- switch (impostor.type) {
- case BABYLON.PhysicsEngine.SphereImpostor:
- var radiusX = extendSize.x;
- var radiusY = extendSize.y;
- var radiusZ = extendSize.z;
- returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
- break;
- //TMP also for cylinder - TODO Cannon supports cylinder natively.
- case BABYLON.PhysicsImpostor.CylinderImpostor:
- returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
- break;
- case BABYLON.PhysicsImpostor.BoxImpostor:
- var box = extendSize.scale(0.5);
- returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
- break;
- case BABYLON.PhysicsImpostor.PlaneImpostor:
- BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
- returnValue = new CANNON.Plane();
- break;
- case BABYLON.PhysicsImpostor.MeshImpostor:
- var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
- var rawFaces = object.getIndices ? object.getIndices() : [];
- BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
- returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
- break;
- case BABYLON.PhysicsImpostor.HeightmapImpostor:
- returnValue = this._createHeightmap(object);
- break;
- case BABYLON.PhysicsImpostor.ParticleImpostor:
- returnValue = new CANNON.Particle();
- break;
- }
- return returnValue;
- };
- CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
- var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- var matrix = [];
- //For now pointDepth will not be used and will be automatically calculated.
- //Future reference - try and find the best place to add a reference to the pointDepth variable.
- var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
- var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
- var elementSize = dim * 2 / arraySize;
- var minY = object.getBoundingInfo().boundingBox.extendSize.y;
- for (var i = 0; i < pos.length; i = i + 3) {
- var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
- var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
- var y = pos[i + 1] + minY;
- if (!matrix[x]) {
- matrix[x] = [];
- }
- if (!matrix[x][z]) {
- matrix[x][z] = y;
- }
- matrix[x][z] = Math.max(y, matrix[x][z]);
- }
- for (var x = 0; x <= arraySize; ++x) {
- if (!matrix[x]) {
- var loc = 1;
- while (!matrix[(x + loc) % arraySize]) {
- loc++;
- }
- matrix[x] = matrix[(x + loc) % arraySize].slice();
- }
- for (var z = 0; z <= arraySize; ++z) {
- if (!matrix[x][z]) {
- var loc = 1;
- var newValue;
- while (newValue === undefined) {
- newValue = matrix[x][(z + loc++) % arraySize];
- }
- matrix[x][z] = newValue;
- }
- }
- }
- var shape = new CANNON.Heightfield(matrix, {
- elementSize: elementSize
- });
- //For future reference, needed for body transformation
- shape.minY = minY;
- return shape;
- };
- CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
- var object = impostor.object;
- //make sure it is updated...
- object.computeWorldMatrix && object.computeWorldMatrix(true);
- // The delta between the mesh position and the mesh bounding box center
- var center = impostor.getObjectCenter();
- var extendSize = impostor.getObjectExtendSize();
- this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
- this._tmpPosition.copyFrom(center);
- var quaternion = object.rotationQuaternion;
- //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
- if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
- //-90 DEG in X, precalculated
- quaternion = quaternion.multiply(this._minus90X);
- //Invert! (Precalculated, 90 deg in X)
- //No need to clone. this will never change.
- impostor.setDeltaRotation(this._plus90X);
- }
- //If it is a heightfield, if should be centered.
- if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
- var mesh = object;
- //calculate the correct body position:
- var rotationQuaternion = mesh.rotationQuaternion;
- mesh.rotationQuaternion = this._tmpUnityRotation;
- mesh.computeWorldMatrix(true);
- //get original center with no rotation
- var c = center.clone();
- var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
- //rotation is back
- mesh.rotationQuaternion = rotationQuaternion;
- //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
- var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
- mesh.setPivotMatrix(p);
- mesh.computeWorldMatrix(true);
- //calculate the translation
- var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
- this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
- //add it inverted to the delta
- this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
- this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
- mesh.setPivotMatrix(oldPivot);
- mesh.computeWorldMatrix(true);
- }
- else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
- this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
- this._tmpPosition.copyFrom(object.position);
- }
- impostor.setDeltaPosition(this._tmpDeltaPosition);
- //Now update the impostor object
- impostor.physicsBody.position.copy(this._tmpPosition);
- impostor.physicsBody.quaternion.copy(quaternion);
- };
- CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
- impostor.object.position.copyFrom(impostor.physicsBody.position);
- impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
- };
- CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
- impostor.physicsBody.position.copy(newPosition);
- impostor.physicsBody.quaternion.copy(newRotation);
- };
- CannonJSPlugin.prototype.isSupported = function () {
- return window.CANNON !== undefined;
- };
- CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
- impostor.physicsBody.velocity.copy(velocity);
- };
- CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
- impostor.physicsBody.angularVelocity.copy(velocity);
- };
- CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
- var v = impostor.physicsBody.velocity;
- if (!v)
- return null;
- return new BABYLON.Vector3(v.x, v.y, v.z);
- };
- CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
- var v = impostor.physicsBody.angularVelocity;
- if (!v)
- return null;
- return new BABYLON.Vector3(v.x, v.y, v.z);
- };
- CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
- impostor.physicsBody.mass = mass;
- impostor.physicsBody.updateMassProperties();
- };
- CannonJSPlugin.prototype.sleepBody = function (impostor) {
- impostor.physicsBody.sleep();
- };
- CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
- impostor.physicsBody.wakeUp();
- };
- CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
- joint.physicsJoint.distance = maxDistance;
- };
- CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
- if (!motorIndex) {
- joint.physicsJoint.enableMotor();
- }
- };
- CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
- if (!motorIndex) {
- joint.physicsJoint.disableMotor();
- }
- };
- CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
- if (!motorIndex) {
- joint.physicsJoint.enableMotor();
- joint.physicsJoint.setMotorSpeed(speed);
- if (maxForce) {
- this.setLimit(joint, maxForce);
- }
- }
- };
- CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
- joint.physicsJoint.motorEquation.maxForce = upperLimit;
- joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
- };
- CannonJSPlugin.prototype.dispose = function () {
- //nothing to do, actually.
- };
- return CannonJSPlugin;
- })();
- BABYLON.CannonJSPlugin = CannonJSPlugin;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var OimoJSPlugin = (function () {
- function OimoJSPlugin(iterations) {
- this.name = "OimoJSPlugin";
- this._tmpImpostorsArray = [];
- this._tmpPositionVector = BABYLON.Vector3.Zero();
- this.world = new OIMO.World(1 / 60, 2, iterations, true);
- this.world.clear();
- //making sure no stats are calculated
- this.world.isNoStat = true;
- }
- OimoJSPlugin.prototype.setGravity = function (gravity) {
- this.world.gravity.copy(gravity);
- };
- OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
- this.world.timeStep = timeStep;
- };
- OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
- var _this = this;
- impostors.forEach(function (impostor) {
- impostor.beforeStep();
- });
- this.world.step();
- impostors.forEach(function (impostor) {
- impostor.afterStep();
- //update the ordered impostors array
- _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
- });
- //check for collisions
- var contact = this.world.contacts;
- while (contact !== null) {
- if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
- contact = contact.next;
- continue;
- }
- //is this body colliding with any other? get the impostor
- var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
- var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
- if (!mainImpostor || !collidingImpostor) {
- contact = contact.next;
- continue;
- }
- mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
- collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
- contact = contact.next;
- }
- };
- OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
- var mass = impostor.physicsBody.massInfo.mass;
- impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
- };
- OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
- BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
- this.applyImpulse(impostor, force, contactPoint);
- };
- OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
- var _this = this;
- //parent-child relationship. Does this impostor has a parent impostor?
- if (impostor.parent) {
- if (impostor.physicsBody) {
- this.removePhysicsBody(impostor);
- //TODO is that needed?
- impostor.forceUpdate();
- }
- return;
- }
- if (impostor.isBodyInitRequired()) {
- var bodyConfig = {
- name: impostor.uniqueId,
- //Oimo must have mass, also for static objects.
- config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
- size: [],
- type: [],
- pos: [],
- rot: [],
- move: impostor.getParam("mass") !== 0,
- //Supporting older versions of Oimo
- world: this.world
- };
- var impostors = [impostor];
- function addToArray(parent) {
- if (!parent.getChildMeshes)
- return;
- parent.getChildMeshes().forEach(function (m) {
- if (m.physicsImpostor) {
- impostors.push(m.physicsImpostor);
- m.physicsImpostor._init();
- }
- });
- }
- addToArray(impostor.object);
- function checkWithEpsilon(value) {
- return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
- }
- impostors.forEach(function (i) {
- //get the correct bounding box
- var oldQuaternion = i.object.rotationQuaternion;
- var rot = new OIMO.Euler().setFromQuaternion({
- x: impostor.object.rotationQuaternion.x,
- y: impostor.object.rotationQuaternion.y,
- z: impostor.object.rotationQuaternion.z,
- s: impostor.object.rotationQuaternion.w
- });
- var extendSize = i.getObjectExtendSize();
- if (i === impostor) {
- var center = impostor.getObjectCenter();
- impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
- //Can also use Array.prototype.push.apply
- bodyConfig.pos.push(center.x);
- bodyConfig.pos.push(center.y);
- bodyConfig.pos.push(center.z);
- //tmp solution
- bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
- bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
- bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
- }
- else {
- bodyConfig.pos.push(i.object.position.x);
- bodyConfig.pos.push(i.object.position.y);
- bodyConfig.pos.push(i.object.position.z);
- //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
- bodyConfig.rot.push(0);
- bodyConfig.rot.push(0);
- bodyConfig.rot.push(0);
- }
- // register mesh
- switch (i.type) {
- case BABYLON.PhysicsImpostor.ParticleImpostor:
- BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
- case BABYLON.PhysicsImpostor.SphereImpostor:
- var radiusX = extendSize.x;
- var radiusY = extendSize.y;
- var radiusZ = extendSize.z;
- var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
- bodyConfig.type.push('sphere');
- //due to the way oimo works with compounds, add 3 times
- bodyConfig.size.push(size);
- bodyConfig.size.push(size);
- bodyConfig.size.push(size);
- break;
- case BABYLON.PhysicsImpostor.CylinderImpostor:
- var sizeX = checkWithEpsilon(extendSize.x) / 2;
- var sizeY = checkWithEpsilon(extendSize.y);
- bodyConfig.type.push('cylinder');
- bodyConfig.size.push(sizeX);
- bodyConfig.size.push(sizeY);
- //due to the way oimo works with compounds, add one more value.
- bodyConfig.size.push(sizeY);
- break;
- case BABYLON.PhysicsImpostor.PlaneImpostor:
- case BABYLON.PhysicsImpostor.BoxImpostor:
- default:
- var sizeX = checkWithEpsilon(extendSize.x);
- var sizeY = checkWithEpsilon(extendSize.y);
- var sizeZ = checkWithEpsilon(extendSize.z);
- bodyConfig.type.push('box');
- bodyConfig.size.push(sizeX);
- bodyConfig.size.push(sizeY);
- bodyConfig.size.push(sizeZ);
- break;
- }
- //actually not needed, but hey...
- i.object.rotationQuaternion = oldQuaternion;
- });
- impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
- }
- else {
- this._tmpPositionVector.copyFromFloats(0, 0, 0);
- }
- impostor.setDeltaPosition(this._tmpPositionVector);
- //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
- //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
- };
- OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
- //impostor.physicsBody.dispose();
- //Same as : (older oimo versions)
- this.world.removeRigidBody(impostor.physicsBody);
- };
- OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
- var mainBody = impostorJoint.mainImpostor.physicsBody;
- var connectedBody = impostorJoint.connectedImpostor.physicsBody;
- if (!mainBody || !connectedBody) {
- return;
- }
- var jointData = impostorJoint.joint.jointData;
- var options = jointData.nativeParams || {};
- var type;
- var nativeJointData = {
- body1: mainBody,
- body2: connectedBody,
- axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
- axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
- pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
- pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
- min: options.min,
- max: options.max,
- collision: options.collision || jointData.collision,
- spring: options.spring,
- //supporting older version of Oimo
- world: this.world
- };
- switch (impostorJoint.joint.type) {
- case BABYLON.PhysicsJoint.BallAndSocketJoint:
- type = "jointBall";
- break;
- case BABYLON.PhysicsJoint.SpringJoint:
- BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
- var springData = jointData;
- nativeJointData.min = springData.length || nativeJointData.min;
- //Max should also be set, just make sure it is at least min
- nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
- case BABYLON.PhysicsJoint.DistanceJoint:
- type = "jointDistance";
- nativeJointData.max = jointData.maxDistance;
- break;
- case BABYLON.PhysicsJoint.PrismaticJoint:
- type = "jointPrisme";
- break;
- case BABYLON.PhysicsJoint.SliderJoint:
- type = "jointSlide";
- break;
- case BABYLON.PhysicsJoint.WheelJoint:
- type = "jointWheel";
- break;
- case BABYLON.PhysicsJoint.HingeJoint:
- default:
- type = "jointHinge";
- break;
- }
- nativeJointData.type = type;
- impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
- };
- OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
- //Bug in Oimo prevents us from disposing a joint in the playground
- //joint.joint.physicsJoint.dispose();
- //So we will bruteforce it!
- try {
- this.world.removeJoint(impostorJoint.joint.physicsJoint);
- }
- catch (e) {
- BABYLON.Tools.Warn(e);
- }
- };
- OimoJSPlugin.prototype.isSupported = function () {
- return OIMO !== undefined;
- };
- OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
- if (!impostor.physicsBody.sleeping) {
- //TODO check that
- if (impostor.physicsBody.shapes.next) {
- var parentShape = this._getLastShape(impostor.physicsBody);
- impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
- impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
- impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
- }
- else {
- impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
- }
- impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
- }
- };
- OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
- var body = impostor.physicsBody;
- body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
- body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
- body.syncShapes();
- body.awake();
- };
- OimoJSPlugin.prototype._getLastShape = function (body) {
- var lastShape = body.shapes;
- while (lastShape.next) {
- lastShape = lastShape.next;
- }
- return lastShape;
- };
- OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
- impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
- };
- OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
- impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
- };
- OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
- var v = impostor.physicsBody.linearVelocity;
- if (!v)
- return null;
- return new BABYLON.Vector3(v.x, v.y, v.z);
- };
- OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
- var v = impostor.physicsBody.angularVelocity;
- if (!v)
- return null;
- return new BABYLON.Vector3(v.x, v.y, v.z);
- };
- OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
- var staticBody = mass === 0;
- //this will actually set the body's density and not its mass.
- //But this is how oimo treats the mass variable.
- impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
- impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
- };
- OimoJSPlugin.prototype.sleepBody = function (impostor) {
- impostor.physicsBody.sleep();
- };
- OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
- impostor.physicsBody.awake();
- };
- OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
- joint.physicsJoint.limitMotoe.upperLimit = maxDistance;
- if (minDistance !== void 0) {
- joint.physicsJoint.limitMotoe.lowerLimit = minDistance;
- }
- };
- OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
- //TODO separate rotational and transational motors.
- var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
- if (motor) {
- motor.setMotor(speed, maxForce);
- }
- };
- OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
- //TODO separate rotational and transational motors.
- var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
- if (motor) {
- motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
- }
- };
- OimoJSPlugin.prototype.dispose = function () {
- this.world.clear();
- };
- return OimoJSPlugin;
- })();
- BABYLON.OimoJSPlugin = OimoJSPlugin;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var DisplayPassPostProcess = (function (_super) {
- __extends(DisplayPassPostProcess, _super);
- function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
- _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
- }
- return DisplayPassPostProcess;
- })(BABYLON.PostProcess);
- BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var SimplificationSettings = (function () {
- function SimplificationSettings(quality, distance, optimizeMesh) {
- this.quality = quality;
- this.distance = distance;
- this.optimizeMesh = optimizeMesh;
- }
- return SimplificationSettings;
- })();
- BABYLON.SimplificationSettings = SimplificationSettings;
- var SimplificationQueue = (function () {
- function SimplificationQueue() {
- this.running = false;
- this._simplificationArray = [];
- }
- SimplificationQueue.prototype.addTask = function (task) {
- this._simplificationArray.push(task);
- };
- SimplificationQueue.prototype.executeNext = function () {
- var task = this._simplificationArray.pop();
- if (task) {
- this.running = true;
- this.runSimplification(task);
- }
- else {
- this.running = false;
- }
- };
- SimplificationQueue.prototype.runSimplification = function (task) {
- var _this = this;
- if (task.parallelProcessing) {
- //parallel simplifier
- task.settings.forEach(function (setting) {
- var simplifier = _this.getSimplifier(task);
- simplifier.simplify(setting, function (newMesh) {
- task.mesh.addLODLevel(setting.distance, newMesh);
- newMesh.isVisible = true;
- //check if it is the last
- if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
- //all done, run the success callback.
- task.successCallback();
- }
- _this.executeNext();
- });
- });
- }
- else {
- //single simplifier.
- var simplifier = this.getSimplifier(task);
- var runDecimation = function (setting, callback) {
- simplifier.simplify(setting, function (newMesh) {
- task.mesh.addLODLevel(setting.distance, newMesh);
- newMesh.isVisible = true;
- //run the next quality level
- callback();
- });
- };
- BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
- runDecimation(task.settings[loop.index], function () {
- loop.executeNext();
- });
- }, function () {
- //execution ended, run the success callback.
- if (task.successCallback) {
- task.successCallback();
- }
- _this.executeNext();
- });
- }
- };
- SimplificationQueue.prototype.getSimplifier = function (task) {
- switch (task.simplificationType) {
- case SimplificationType.QUADRATIC:
- default:
- return new QuadraticErrorSimplification(task.mesh);
- }
- };
- return SimplificationQueue;
- })();
- BABYLON.SimplificationQueue = SimplificationQueue;
- /**
- * The implemented types of simplification.
- * At the moment only Quadratic Error Decimation is implemented.
- */
- (function (SimplificationType) {
- SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
- })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
- var SimplificationType = BABYLON.SimplificationType;
- var DecimationTriangle = (function () {
- function DecimationTriangle(vertices) {
- this.vertices = vertices;
- this.error = new Array(4);
- this.deleted = false;
- this.isDirty = false;
- this.deletePending = false;
- this.borderFactor = 0;
- }
- return DecimationTriangle;
- })();
- BABYLON.DecimationTriangle = DecimationTriangle;
- var DecimationVertex = (function () {
- function DecimationVertex(position, id) {
- this.position = position;
- this.id = id;
- this.isBorder = true;
- this.q = new QuadraticMatrix();
- this.triangleCount = 0;
- this.triangleStart = 0;
- this.originalOffsets = [];
- }
- DecimationVertex.prototype.updatePosition = function (newPosition) {
- this.position.copyFrom(newPosition);
- };
- return DecimationVertex;
- })();
- BABYLON.DecimationVertex = DecimationVertex;
- var QuadraticMatrix = (function () {
- function QuadraticMatrix(data) {
- this.data = new Array(10);
- for (var i = 0; i < 10; ++i) {
- if (data && data[i]) {
- this.data[i] = data[i];
- }
- else {
- this.data[i] = 0;
- }
- }
- }
- QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
- var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
- this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
- this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
- return det;
- };
- QuadraticMatrix.prototype.addInPlace = function (matrix) {
- for (var i = 0; i < 10; ++i) {
- this.data[i] += matrix.data[i];
- }
- };
- QuadraticMatrix.prototype.addArrayInPlace = function (data) {
- for (var i = 0; i < 10; ++i) {
- this.data[i] += data[i];
- }
- };
- QuadraticMatrix.prototype.add = function (matrix) {
- var m = new QuadraticMatrix();
- for (var i = 0; i < 10; ++i) {
- m.data[i] = this.data[i] + matrix.data[i];
- }
- return m;
- };
- QuadraticMatrix.FromData = function (a, b, c, d) {
- return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
- };
- //returning an array to avoid garbage collection
- QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
- return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
- };
- return QuadraticMatrix;
- })();
- BABYLON.QuadraticMatrix = QuadraticMatrix;
- var Reference = (function () {
- function Reference(vertexId, triangleId) {
- this.vertexId = vertexId;
- this.triangleId = triangleId;
- }
- return Reference;
- })();
- BABYLON.Reference = Reference;
- /**
- * An implementation of the Quadratic Error simplification algorithm.
- * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
- * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
- * @author RaananW
- */
- var QuadraticErrorSimplification = (function () {
- function QuadraticErrorSimplification(_mesh) {
- this._mesh = _mesh;
- this.initialized = false;
- this.syncIterations = 5000;
- this.aggressiveness = 7;
- this.decimationIterations = 100;
- this.boundingBoxEpsilon = BABYLON.Epsilon;
- }
- QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
- var _this = this;
- this.initDecimatedMesh();
- //iterating through the submeshes array, one after the other.
- BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
- _this.initWithMesh(loop.index, function () {
- _this.runDecimation(settings, loop.index, function () {
- loop.executeNext();
- });
- }, settings.optimizeMesh);
- }, function () {
- setTimeout(function () {
- successCallback(_this._reconstructedMesh);
- }, 0);
- });
- };
- QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
- var _this = this;
- var gCount = 0;
- triangle.vertices.forEach(function (vertex) {
- var count = 0;
- var vPos = vertex.position;
- var bbox = _this._mesh.getBoundingInfo().boundingBox;
- if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
- ++count;
- if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
- ++count;
- if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
- ++count;
- if (count > 1) {
- ++gCount;
- }
- ;
- });
- if (gCount > 1) {
- console.log(triangle, gCount);
- }
- return gCount > 1;
- };
- QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
- var _this = this;
- var targetCount = ~~(this.triangles.length * settings.quality);
- var deletedTriangles = 0;
- var triangleCount = this.triangles.length;
- var iterationFunction = function (iteration, callback) {
- setTimeout(function () {
- if (iteration % 5 === 0) {
- _this.updateMesh(iteration === 0);
- }
- for (var i = 0; i < _this.triangles.length; ++i) {
- _this.triangles[i].isDirty = false;
- }
- var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
- var trianglesIterator = function (i) {
- var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
- var t = _this.triangles[tIdx];
- if (!t)
- return;
- if (t.error[3] > threshold || t.deleted || t.isDirty) {
- return;
- }
- for (var j = 0; j < 3; ++j) {
- if (t.error[j] < threshold) {
- var deleted0 = [];
- var deleted1 = [];
- var v0 = t.vertices[j];
- var v1 = t.vertices[(j + 1) % 3];
- if (v0.isBorder || v1.isBorder)
- continue;
- var p = BABYLON.Vector3.Zero();
- var n = BABYLON.Vector3.Zero();
- var uv = BABYLON.Vector2.Zero();
- var color = new BABYLON.Color4(0, 0, 0, 1);
- _this.calculateError(v0, v1, p, n, uv, color);
- var delTr = [];
- if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
- continue;
- if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
- continue;
- if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
- continue;
- var uniqueArray = [];
- delTr.forEach(function (deletedT) {
- if (uniqueArray.indexOf(deletedT) === -1) {
- deletedT.deletePending = true;
- uniqueArray.push(deletedT);
- }
- });
- if (uniqueArray.length % 2 !== 0) {
- continue;
- }
- v0.q = v1.q.add(v0.q);
- v0.updatePosition(p);
- var tStart = _this.references.length;
- deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
- deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
- var tCount = _this.references.length - tStart;
- if (tCount <= v0.triangleCount) {
- if (tCount) {
- for (var c = 0; c < tCount; c++) {
- _this.references[v0.triangleStart + c] = _this.references[tStart + c];
- }
- }
- }
- else {
- v0.triangleStart = tStart;
- }
- v0.triangleCount = tCount;
- break;
- }
- }
- };
- BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
- }, 0);
- };
- BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
- if (triangleCount - deletedTriangles <= targetCount)
- loop.breakLoop();
- else {
- iterationFunction(loop.index, function () {
- loop.executeNext();
- });
- }
- }, function () {
- setTimeout(function () {
- //reconstruct this part of the mesh
- _this.reconstructMesh(submeshIndex);
- successCallback();
- }, 0);
- });
- };
- QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
- var _this = this;
- this.vertices = [];
- this.triangles = [];
- var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- var indices = this._mesh.getIndices();
- var submesh = this._mesh.subMeshes[submeshIndex];
- var findInVertices = function (positionToSearch) {
- if (optimizeMesh) {
- for (var ii = 0; ii < _this.vertices.length; ++ii) {
- if (_this.vertices[ii].position.equals(positionToSearch)) {
- return _this.vertices[ii];
- }
- }
- }
- return null;
- };
- var vertexReferences = [];
- var vertexInit = function (i) {
- var offset = i + submesh.verticesStart;
- var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
- var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
- vertex.originalOffsets.push(offset);
- if (vertex.id === _this.vertices.length) {
- _this.vertices.push(vertex);
- }
- vertexReferences.push(vertex.id);
- };
- //var totalVertices = mesh.getTotalVertices();
- var totalVertices = submesh.verticesCount;
- BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
- var indicesInit = function (i) {
- var offset = (submesh.indexStart / 3) + i;
- var pos = (offset * 3);
- var i0 = indices[pos + 0];
- var i1 = indices[pos + 1];
- var i2 = indices[pos + 2];
- var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
- var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
- var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
- var triangle = new DecimationTriangle([v0, v1, v2]);
- triangle.originalOffset = pos;
- _this.triangles.push(triangle);
- };
- BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
- _this.init(callback);
- });
- });
- };
- QuadraticErrorSimplification.prototype.init = function (callback) {
- var _this = this;
- var triangleInit1 = function (i) {
- var t = _this.triangles[i];
- t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
- for (var j = 0; j < 3; j++) {
- 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))));
- }
- };
- BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
- var triangleInit2 = function (i) {
- var t = _this.triangles[i];
- for (var j = 0; j < 3; ++j) {
- t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
- }
- t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
- };
- BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
- _this.initialized = true;
- callback();
- });
- });
- };
- QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
- var newTriangles = [];
- var i;
- for (i = 0; i < this.vertices.length; ++i) {
- this.vertices[i].triangleCount = 0;
- }
- var t;
- var j;
- for (i = 0; i < this.triangles.length; ++i) {
- if (!this.triangles[i].deleted) {
- t = this.triangles[i];
- for (j = 0; j < 3; ++j) {
- t.vertices[j].triangleCount = 1;
- }
- newTriangles.push(t);
- }
- }
- var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
- var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
- var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
- var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
- var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
- var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
- var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
- var vertexCount = 0;
- for (i = 0; i < this.vertices.length; ++i) {
- var vertex = this.vertices[i];
- vertex.id = vertexCount;
- if (vertex.triangleCount) {
- vertex.originalOffsets.forEach(function (originalOffset) {
- newPositionData.push(vertex.position.x);
- newPositionData.push(vertex.position.y);
- newPositionData.push(vertex.position.z);
- newNormalData.push(normalData[originalOffset * 3]);
- newNormalData.push(normalData[(originalOffset * 3) + 1]);
- newNormalData.push(normalData[(originalOffset * 3) + 2]);
- if (uvs && uvs.length) {
- newUVsData.push(uvs[(originalOffset * 2)]);
- newUVsData.push(uvs[(originalOffset * 2) + 1]);
- }
- else if (colorsData && colorsData.length) {
- newColorsData.push(colorsData[(originalOffset * 4)]);
- newColorsData.push(colorsData[(originalOffset * 4) + 1]);
- newColorsData.push(colorsData[(originalOffset * 4) + 2]);
- newColorsData.push(colorsData[(originalOffset * 4) + 3]);
- }
- ++vertexCount;
- });
- }
- }
- var startingIndex = this._reconstructedMesh.getTotalIndices();
- var startingVertex = this._reconstructedMesh.getTotalVertices();
- var submeshesArray = this._reconstructedMesh.subMeshes;
- this._reconstructedMesh.subMeshes = [];
- var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
- var originalIndices = this._mesh.getIndices();
- for (i = 0; i < newTriangles.length; ++i) {
- t = newTriangles[i]; //now get the new referencing point for each vertex
- [0, 1, 2].forEach(function (idx) {
- var id = originalIndices[t.originalOffset + idx];
- var offset = t.vertices[idx].originalOffsets.indexOf(id);
- if (offset < 0)
- offset = 0;
- newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
- });
- }
- //overwriting the old vertex buffers and indices.
- this._reconstructedMesh.setIndices(newIndicesArray);
- this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
- this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
- if (newUVsData.length > 0)
- this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
- if (newColorsData.length > 0)
- this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
- //create submesh
- var originalSubmesh = this._mesh.subMeshes[submeshIndex];
- if (submeshIndex > 0) {
- this._reconstructedMesh.subMeshes = [];
- submeshesArray.forEach(function (submesh) {
- new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
- });
- var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
- }
- };
- QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
- this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
- this._reconstructedMesh.material = this._mesh.material;
- this._reconstructedMesh.parent = this._mesh.parent;
- this._reconstructedMesh.isVisible = false;
- this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
- };
- QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
- for (var i = 0; i < vertex1.triangleCount; ++i) {
- var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
- if (t.deleted)
- continue;
- var s = this.references[vertex1.triangleStart + i].vertexId;
- var v1 = t.vertices[(s + 1) % 3];
- var v2 = t.vertices[(s + 2) % 3];
- if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
- deletedArray[i] = true;
- delTr.push(t);
- continue;
- }
- var d1 = v1.position.subtract(point);
- d1 = d1.normalize();
- var d2 = v2.position.subtract(point);
- d2 = d2.normalize();
- if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
- return true;
- var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
- deletedArray[i] = false;
- if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
- return true;
- }
- return false;
- };
- QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
- var newDeleted = deletedTriangles;
- for (var i = 0; i < vertex.triangleCount; ++i) {
- var ref = this.references[vertex.triangleStart + i];
- var t = this.triangles[ref.triangleId];
- if (t.deleted)
- continue;
- if (deletedArray[i] && t.deletePending) {
- t.deleted = true;
- newDeleted++;
- continue;
- }
- t.vertices[ref.vertexId] = origVertex;
- t.isDirty = true;
- t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
- t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
- t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
- t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
- this.references.push(ref);
- }
- return newDeleted;
- };
- QuadraticErrorSimplification.prototype.identifyBorder = function () {
- for (var i = 0; i < this.vertices.length; ++i) {
- var vCount = [];
- var vId = [];
- var v = this.vertices[i];
- var j;
- for (j = 0; j < v.triangleCount; ++j) {
- var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
- for (var ii = 0; ii < 3; ii++) {
- var ofs = 0;
- var vv = triangle.vertices[ii];
- while (ofs < vCount.length) {
- if (vId[ofs] === vv.id)
- break;
- ++ofs;
- }
- if (ofs === vCount.length) {
- vCount.push(1);
- vId.push(vv.id);
- }
- else {
- vCount[ofs]++;
- }
- }
- }
- for (j = 0; j < vCount.length; ++j) {
- if (vCount[j] === 1) {
- this.vertices[vId[j]].isBorder = true;
- }
- else {
- this.vertices[vId[j]].isBorder = false;
- }
- }
- }
- };
- QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
- if (identifyBorders === void 0) { identifyBorders = false; }
- var i;
- if (!identifyBorders) {
- var newTrianglesVector = [];
- for (i = 0; i < this.triangles.length; ++i) {
- if (!this.triangles[i].deleted) {
- newTrianglesVector.push(this.triangles[i]);
- }
- }
- this.triangles = newTrianglesVector;
- }
- for (i = 0; i < this.vertices.length; ++i) {
- this.vertices[i].triangleCount = 0;
- this.vertices[i].triangleStart = 0;
- }
- var t;
- var j;
- var v;
- for (i = 0; i < this.triangles.length; ++i) {
- t = this.triangles[i];
- for (j = 0; j < 3; ++j) {
- v = t.vertices[j];
- v.triangleCount++;
- }
- }
- var tStart = 0;
- for (i = 0; i < this.vertices.length; ++i) {
- this.vertices[i].triangleStart = tStart;
- tStart += this.vertices[i].triangleCount;
- this.vertices[i].triangleCount = 0;
- }
- var newReferences = new Array(this.triangles.length * 3);
- for (i = 0; i < this.triangles.length; ++i) {
- t = this.triangles[i];
- for (j = 0; j < 3; ++j) {
- v = t.vertices[j];
- newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
- v.triangleCount++;
- }
- }
- this.references = newReferences;
- if (identifyBorders) {
- this.identifyBorder();
- }
- };
- QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
- var x = point.x;
- var y = point.y;
- var z = point.z;
- 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
- + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
- };
- QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
- var q = vertex1.q.add(vertex2.q);
- var border = vertex1.isBorder && vertex2.isBorder;
- var error = 0;
- var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
- if (qDet !== 0 && !border) {
- if (!pointResult) {
- pointResult = BABYLON.Vector3.Zero();
- }
- pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
- pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
- pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
- error = this.vertexError(q, pointResult);
- }
- else {
- var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
- //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
- var error1 = this.vertexError(q, vertex1.position);
- var error2 = this.vertexError(q, vertex2.position);
- var error3 = this.vertexError(q, p3);
- error = Math.min(error1, error2, error3);
- if (error === error1) {
- if (pointResult) {
- pointResult.copyFrom(vertex1.position);
- }
- }
- else if (error === error2) {
- if (pointResult) {
- pointResult.copyFrom(vertex2.position);
- }
- }
- else {
- if (pointResult) {
- pointResult.copyFrom(p3);
- }
- }
- }
- return error;
- };
- return QuadraticErrorSimplification;
- })();
- BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var serializedGeometries = [];
- var serializeGeometry = function (geometry, serializationGeometries) {
- if (serializedGeometries[geometry.id]) {
- return;
- }
- if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
- serializationGeometries.boxes.push(geometry.serialize());
- }
- else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
- serializationGeometries.spheres.push(geometry.serialize());
- }
- else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
- serializationGeometries.cylinders.push(geometry.serialize());
- }
- else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
- serializationGeometries.toruses.push(geometry.serialize());
- }
- else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
- serializationGeometries.grounds.push(geometry.serialize());
- }
- else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
- serializationGeometries.planes.push(geometry.serialize());
- }
- else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
- serializationGeometries.torusKnots.push(geometry.serialize());
- }
- else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
- throw new Error("Unknown primitive type");
- }
- else {
- serializationGeometries.vertexData.push(geometry.serializeVerticeData());
- }
- serializedGeometries[geometry.id] = true;
- };
- var serializeMesh = function (mesh, serializationScene) {
- var serializationObject = {};
- serializationObject.name = mesh.name;
- serializationObject.id = mesh.id;
- if (BABYLON.Tags.HasTags(mesh)) {
- serializationObject.tags = BABYLON.Tags.GetTags(mesh);
- }
- serializationObject.position = mesh.position.asArray();
- if (mesh.rotationQuaternion) {
- serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
- }
- else if (mesh.rotation) {
- serializationObject.rotation = mesh.rotation.asArray();
- }
- serializationObject.scaling = mesh.scaling.asArray();
- serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
- serializationObject.isEnabled = mesh.isEnabled();
- serializationObject.isVisible = mesh.isVisible;
- serializationObject.infiniteDistance = mesh.infiniteDistance;
- serializationObject.pickable = mesh.isPickable;
- serializationObject.receiveShadows = mesh.receiveShadows;
- serializationObject.billboardMode = mesh.billboardMode;
- serializationObject.visibility = mesh.visibility;
- serializationObject.checkCollisions = mesh.checkCollisions;
- // Parent
- if (mesh.parent) {
- serializationObject.parentId = mesh.parent.id;
- }
- // Geometry
- var geometry = mesh._geometry;
- if (geometry) {
- var geometryId = geometry.id;
- serializationObject.geometryId = geometryId;
- if (!mesh.getScene().getGeometryByID(geometryId)) {
- // 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
- serializeGeometry(geometry, serializationScene.geometries);
- }
- // SubMeshes
- serializationObject.subMeshes = [];
- for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
- var subMesh = mesh.subMeshes[subIndex];
- serializationObject.subMeshes.push({
- materialIndex: subMesh.materialIndex,
- verticesStart: subMesh.verticesStart,
- verticesCount: subMesh.verticesCount,
- indexStart: subMesh.indexStart,
- indexCount: subMesh.indexCount
- });
- }
- }
- // Material
- if (mesh.material) {
- serializationObject.materialId = mesh.material.id;
- }
- else {
- mesh.material = null;
- }
- // Skeleton
- if (mesh.skeleton) {
- serializationObject.skeletonId = mesh.skeleton.id;
- }
- // Physics
- //TODO implement correct serialization for physics impostors.
- if (mesh.getPhysicsImpostor()) {
- serializationObject.physicsMass = mesh.getPhysicsMass();
- serializationObject.physicsFriction = mesh.getPhysicsFriction();
- serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
- serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
- }
- // Instances
- serializationObject.instances = [];
- for (var index = 0; index < mesh.instances.length; index++) {
- var instance = mesh.instances[index];
- var serializationInstance = {
- name: instance.name,
- position: instance.position.asArray(),
- scaling: instance.scaling.asArray()
- };
- if (instance.rotationQuaternion) {
- serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
- }
- else if (instance.rotation) {
- serializationInstance.rotation = instance.rotation.asArray();
- }
- serializationObject.instances.push(serializationInstance);
- // Animations
- BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
- serializationInstance.ranges = instance.serializeAnimationRanges();
- }
- // Animations
- BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
- serializationObject.ranges = mesh.serializeAnimationRanges();
- // Layer mask
- serializationObject.layerMask = mesh.layerMask;
- // Action Manager
- if (mesh.actionManager) {
- serializationObject.actions = mesh.actionManager.serialize(mesh.name);
- }
- return serializationObject;
- };
- var finalizeSingleMesh = function (mesh, serializationObject) {
- //only works if the mesh is already loaded
- if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
- //serialize material
- if (mesh.material) {
- if (mesh.material instanceof BABYLON.StandardMaterial) {
- serializationObject.materials = serializationObject.materials || [];
- if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
- serializationObject.materials.push(mesh.material.serialize());
- }
- }
- else if (mesh.material instanceof BABYLON.MultiMaterial) {
- serializationObject.multiMaterials = serializationObject.multiMaterials || [];
- if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
- serializationObject.multiMaterials.push(mesh.material.serialize());
- }
- }
- }
- //serialize geometry
- var geometry = mesh._geometry;
- if (geometry) {
- if (!serializationObject.geometries) {
- serializationObject.geometries = {};
- serializationObject.geometries.boxes = [];
- serializationObject.geometries.spheres = [];
- serializationObject.geometries.cylinders = [];
- serializationObject.geometries.toruses = [];
- serializationObject.geometries.grounds = [];
- serializationObject.geometries.planes = [];
- serializationObject.geometries.torusKnots = [];
- serializationObject.geometries.vertexData = [];
- }
- serializeGeometry(geometry, serializationObject.geometries);
- }
- // Skeletons
- if (mesh.skeleton) {
- serializationObject.skeletons = serializationObject.skeletons || [];
- serializationObject.skeletons.push(mesh.skeleton.serialize());
- }
- //serialize the actual mesh
- serializationObject.meshes = serializationObject.meshes || [];
- serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
- }
- };
- var SceneSerializer = (function () {
- function SceneSerializer() {
- }
- SceneSerializer.ClearCache = function () {
- serializedGeometries = [];
- };
- SceneSerializer.Serialize = function (scene) {
- var serializationObject = {};
- // Scene
- serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
- serializationObject.autoClear = scene.autoClear;
- serializationObject.clearColor = scene.clearColor.asArray();
- serializationObject.ambientColor = scene.ambientColor.asArray();
- serializationObject.gravity = scene.gravity.asArray();
- serializationObject.collisionsEnabled = scene.collisionsEnabled;
- serializationObject.workerCollisions = scene.workerCollisions;
- // Fog
- if (scene.fogMode && scene.fogMode !== 0) {
- serializationObject.fogMode = scene.fogMode;
- serializationObject.fogColor = scene.fogColor.asArray();
- serializationObject.fogStart = scene.fogStart;
- serializationObject.fogEnd = scene.fogEnd;
- serializationObject.fogDensity = scene.fogDensity;
- }
- //Physics
- if (scene.isPhysicsEnabled()) {
- serializationObject.physicsEnabled = true;
- serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
- serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
- }
- // Lights
- serializationObject.lights = [];
- var index;
- var light;
- for (index = 0; index < scene.lights.length; index++) {
- light = scene.lights[index];
- serializationObject.lights.push(light.serialize());
- }
- // Cameras
- serializationObject.cameras = [];
- for (index = 0; index < scene.cameras.length; index++) {
- var camera = scene.cameras[index];
- serializationObject.cameras.push(camera.serialize());
- }
- if (scene.activeCamera) {
- serializationObject.activeCameraID = scene.activeCamera.id;
- }
- // Animations
- BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
- // Materials
- serializationObject.materials = [];
- serializationObject.multiMaterials = [];
- var material;
- for (index = 0; index < scene.materials.length; index++) {
- material = scene.materials[index];
- serializationObject.materials.push(material.serialize());
- }
- // MultiMaterials
- serializationObject.multiMaterials = [];
- for (index = 0; index < scene.multiMaterials.length; index++) {
- var multiMaterial = scene.multiMaterials[index];
- serializationObject.multiMaterials.push(multiMaterial.serialize());
- }
- // Skeletons
- serializationObject.skeletons = [];
- for (index = 0; index < scene.skeletons.length; index++) {
- serializationObject.skeletons.push(scene.skeletons[index].serialize());
- }
- // Geometries
- serializationObject.geometries = {};
- serializationObject.geometries.boxes = [];
- serializationObject.geometries.spheres = [];
- serializationObject.geometries.cylinders = [];
- serializationObject.geometries.toruses = [];
- serializationObject.geometries.grounds = [];
- serializationObject.geometries.planes = [];
- serializationObject.geometries.torusKnots = [];
- serializationObject.geometries.vertexData = [];
- serializedGeometries = [];
- var geometries = scene.getGeometries();
- for (index = 0; index < geometries.length; index++) {
- var geometry = geometries[index];
- if (geometry.isReady()) {
- serializeGeometry(geometry, serializationObject.geometries);
- }
- }
- // Meshes
- serializationObject.meshes = [];
- for (index = 0; index < scene.meshes.length; index++) {
- var abstractMesh = scene.meshes[index];
- if (abstractMesh instanceof BABYLON.Mesh) {
- var mesh = abstractMesh;
- if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
- serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
- }
- }
- }
- // Particles Systems
- serializationObject.particleSystems = [];
- for (index = 0; index < scene.particleSystems.length; index++) {
- serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
- }
- // Lens flares
- serializationObject.lensFlareSystems = [];
- for (index = 0; index < scene.lensFlareSystems.length; index++) {
- serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
- }
- // Shadows
- serializationObject.shadowGenerators = [];
- for (index = 0; index < scene.lights.length; index++) {
- light = scene.lights[index];
- if (light.getShadowGenerator()) {
- serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
- }
- }
- // Action Manager
- if (scene.actionManager) {
- serializationObject.actions = scene.actionManager.serialize("scene");
- }
- return serializationObject;
- };
- SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
- if (withParents === void 0) { withParents = false; }
- if (withChildren === void 0) { withChildren = false; }
- var serializationObject = {};
- toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
- if (withParents || withChildren) {
- //deliberate for loop! not for each, appended should be processed as well.
- for (var i = 0; i < toSerialize.length; ++i) {
- if (withChildren) {
- toSerialize[i].getDescendants().forEach(function (node) {
- if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
- toSerialize.push(node);
- }
- });
- }
- //make sure the array doesn't contain the object already
- if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
- toSerialize.push(toSerialize[i].parent);
- }
- }
- }
- toSerialize.forEach(function (mesh) {
- finalizeSingleMesh(mesh, serializationObject);
- });
- return serializationObject;
- };
- return SceneSerializer;
- })();
- BABYLON.SceneSerializer = SceneSerializer;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- // Unique ID when we import meshes from Babylon to CSG
- var currentCSGMeshId = 0;
- // # class Vertex
- // Represents a vertex of a polygon. Use your own vertex class instead of this
- // one to provide additional features like texture coordinates and vertex
- // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
- // `flip()`, and `interpolate()` methods that behave analogous to the ones
- // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
- // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
- // is not used anywhere else.
- // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
- var Vertex = (function () {
- function Vertex(pos, normal, uv) {
- this.pos = pos;
- this.normal = normal;
- this.uv = uv;
- }
- Vertex.prototype.clone = function () {
- return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
- };
- // Invert all orientation-specific data (e.g. vertex normal). Called when the
- // orientation of a polygon is flipped.
- Vertex.prototype.flip = function () {
- this.normal = this.normal.scale(-1);
- };
- // Create a new vertex between this vertex and `other` by linearly
- // interpolating all properties using a parameter of `t`. Subclasses should
- // override this to interpolate additional properties.
- Vertex.prototype.interpolate = function (other, t) {
- 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));
- };
- return Vertex;
- })();
- // # class Plane
- // Represents a plane in 3D space.
- var Plane = (function () {
- function Plane(normal, w) {
- this.normal = normal;
- this.w = w;
- }
- Plane.FromPoints = function (a, b, c) {
- var v0 = c.subtract(a);
- var v1 = b.subtract(a);
- if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
- return null;
- }
- var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
- return new Plane(n, BABYLON.Vector3.Dot(n, a));
- };
- Plane.prototype.clone = function () {
- return new Plane(this.normal.clone(), this.w);
- };
- Plane.prototype.flip = function () {
- this.normal.scaleInPlace(-1);
- this.w = -this.w;
- };
- // Split `polygon` by this plane if needed, then put the polygon or polygon
- // fragments in the appropriate lists. Coplanar polygons go into either
- // `coplanarFront` or `coplanarBack` depending on their orientation with
- // respect to this plane. Polygons in front or in back of this plane go into
- // either `front` or `back`.
- Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
- var COPLANAR = 0;
- var FRONT = 1;
- var BACK = 2;
- var SPANNING = 3;
- // Classify each point as well as the entire polygon into one of the above
- // four classes.
- var polygonType = 0;
- var types = [];
- var i;
- var t;
- for (i = 0; i < polygon.vertices.length; i++) {
- t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
- var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
- polygonType |= type;
- types.push(type);
- }
- // Put the polygon in the correct list, splitting it when necessary.
- switch (polygonType) {
- case COPLANAR:
- (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
- break;
- case FRONT:
- front.push(polygon);
- break;
- case BACK:
- back.push(polygon);
- break;
- case SPANNING:
- var f = [], b = [];
- for (i = 0; i < polygon.vertices.length; i++) {
- var j = (i + 1) % polygon.vertices.length;
- var ti = types[i], tj = types[j];
- var vi = polygon.vertices[i], vj = polygon.vertices[j];
- if (ti !== BACK)
- f.push(vi);
- if (ti !== FRONT)
- b.push(ti !== BACK ? vi.clone() : vi);
- if ((ti | tj) === SPANNING) {
- t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
- var v = vi.interpolate(vj, t);
- f.push(v);
- b.push(v.clone());
- }
- }
- var poly;
- if (f.length >= 3) {
- poly = new Polygon(f, polygon.shared);
- if (poly.plane)
- front.push(poly);
- }
- if (b.length >= 3) {
- poly = new Polygon(b, polygon.shared);
- if (poly.plane)
- back.push(poly);
- }
- break;
- }
- };
- // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
- // point is on the plane.
- Plane.EPSILON = 1e-5;
- return Plane;
- })();
- // # class Polygon
- // Represents a convex polygon. The vertices used to initialize a polygon must
- // be coplanar and form a convex loop.
- //
- // Each convex polygon has a `shared` property, which is shared between all
- // polygons that are clones of each other or were split from the same polygon.
- // This can be used to define per-polygon properties (such as surface color).
- var Polygon = (function () {
- function Polygon(vertices, shared) {
- this.vertices = vertices;
- this.shared = shared;
- this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
- }
- Polygon.prototype.clone = function () {
- var vertices = this.vertices.map(function (v) { return v.clone(); });
- return new Polygon(vertices, this.shared);
- };
- Polygon.prototype.flip = function () {
- this.vertices.reverse().map(function (v) { v.flip(); });
- this.plane.flip();
- };
- return Polygon;
- })();
- // # class Node
- // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
- // by picking a polygon to split along. That polygon (and all other coplanar
- // polygons) are added directly to that node and the other polygons are added to
- // the front and/or back subtrees. This is not a leafy BSP tree since there is
- // no distinction between internal and leaf nodes.
- var Node = (function () {
- function Node(polygons) {
- this.plane = null;
- this.front = null;
- this.back = null;
- this.polygons = [];
- if (polygons) {
- this.build(polygons);
- }
- }
- Node.prototype.clone = function () {
- var node = new Node();
- node.plane = this.plane && this.plane.clone();
- node.front = this.front && this.front.clone();
- node.back = this.back && this.back.clone();
- node.polygons = this.polygons.map(function (p) { return p.clone(); });
- return node;
- };
- // Convert solid space to empty space and empty space to solid space.
- Node.prototype.invert = function () {
- for (var i = 0; i < this.polygons.length; i++) {
- this.polygons[i].flip();
- }
- if (this.plane) {
- this.plane.flip();
- }
- if (this.front) {
- this.front.invert();
- }
- if (this.back) {
- this.back.invert();
- }
- var temp = this.front;
- this.front = this.back;
- this.back = temp;
- };
- // Recursively remove all polygons in `polygons` that are inside this BSP
- // tree.
- Node.prototype.clipPolygons = function (polygons) {
- if (!this.plane)
- return polygons.slice();
- var front = [], back = [];
- for (var i = 0; i < polygons.length; i++) {
- this.plane.splitPolygon(polygons[i], front, back, front, back);
- }
- if (this.front) {
- front = this.front.clipPolygons(front);
- }
- if (this.back) {
- back = this.back.clipPolygons(back);
- }
- else {
- back = [];
- }
- return front.concat(back);
- };
- // Remove all polygons in this BSP tree that are inside the other BSP tree
- // `bsp`.
- Node.prototype.clipTo = function (bsp) {
- this.polygons = bsp.clipPolygons(this.polygons);
- if (this.front)
- this.front.clipTo(bsp);
- if (this.back)
- this.back.clipTo(bsp);
- };
- // Return a list of all polygons in this BSP tree.
- Node.prototype.allPolygons = function () {
- var polygons = this.polygons.slice();
- if (this.front)
- polygons = polygons.concat(this.front.allPolygons());
- if (this.back)
- polygons = polygons.concat(this.back.allPolygons());
- return polygons;
- };
- // Build a BSP tree out of `polygons`. When called on an existing tree, the
- // new polygons are filtered down to the bottom of the tree and become new
- // nodes there. Each set of polygons is partitioned using the first polygon
- // (no heuristic is used to pick a good split).
- Node.prototype.build = function (polygons) {
- if (!polygons.length)
- return;
- if (!this.plane)
- this.plane = polygons[0].plane.clone();
- var front = [], back = [];
- for (var i = 0; i < polygons.length; i++) {
- this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
- }
- if (front.length) {
- if (!this.front)
- this.front = new Node();
- this.front.build(front);
- }
- if (back.length) {
- if (!this.back)
- this.back = new Node();
- this.back.build(back);
- }
- };
- return Node;
- })();
- var CSG = (function () {
- function CSG() {
- this.polygons = new Array();
- }
- // Convert BABYLON.Mesh to BABYLON.CSG
- CSG.FromMesh = function (mesh) {
- var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
- var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
- if (mesh instanceof BABYLON.Mesh) {
- mesh.computeWorldMatrix(true);
- matrix = mesh.getWorldMatrix();
- meshPosition = mesh.position.clone();
- meshRotation = mesh.rotation.clone();
- if (mesh.rotationQuaternion) {
- meshRotationQuaternion = mesh.rotationQuaternion.clone();
- }
- meshScaling = mesh.scaling.clone();
- }
- else {
- throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
- }
- var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
- var subMeshes = mesh.subMeshes;
- for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
- for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
- vertices = [];
- for (var j = 0; j < 3; j++) {
- var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
- uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
- var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
- position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
- normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
- vertex = new Vertex(position, normal, uv);
- vertices.push(vertex);
- }
- polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
- // To handle the case of degenerated triangle
- // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
- if (polygon.plane)
- polygons.push(polygon);
- }
- }
- var csg = CSG.FromPolygons(polygons);
- csg.matrix = matrix;
- csg.position = meshPosition;
- csg.rotation = meshRotation;
- csg.scaling = meshScaling;
- csg.rotationQuaternion = meshRotationQuaternion;
- currentCSGMeshId++;
- return csg;
- };
- // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
- CSG.FromPolygons = function (polygons) {
- var csg = new CSG();
- csg.polygons = polygons;
- return csg;
- };
- CSG.prototype.clone = function () {
- var csg = new CSG();
- csg.polygons = this.polygons.map(function (p) { return p.clone(); });
- csg.copyTransformAttributes(this);
- return csg;
- };
- CSG.prototype.toPolygons = function () {
- return this.polygons;
- };
- CSG.prototype.union = function (csg) {
- var a = new Node(this.clone().polygons);
- var b = new Node(csg.clone().polygons);
- a.clipTo(b);
- b.clipTo(a);
- b.invert();
- b.clipTo(a);
- b.invert();
- a.build(b.allPolygons());
- return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
- };
- CSG.prototype.unionInPlace = function (csg) {
- var a = new Node(this.polygons);
- var b = new Node(csg.polygons);
- a.clipTo(b);
- b.clipTo(a);
- b.invert();
- b.clipTo(a);
- b.invert();
- a.build(b.allPolygons());
- this.polygons = a.allPolygons();
- };
- CSG.prototype.subtract = function (csg) {
- var a = new Node(this.clone().polygons);
- var b = new Node(csg.clone().polygons);
- a.invert();
- a.clipTo(b);
- b.clipTo(a);
- b.invert();
- b.clipTo(a);
- b.invert();
- a.build(b.allPolygons());
- a.invert();
- return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
- };
- CSG.prototype.subtractInPlace = function (csg) {
- var a = new Node(this.polygons);
- var b = new Node(csg.polygons);
- a.invert();
- a.clipTo(b);
- b.clipTo(a);
- b.invert();
- b.clipTo(a);
- b.invert();
- a.build(b.allPolygons());
- a.invert();
- this.polygons = a.allPolygons();
- };
- CSG.prototype.intersect = function (csg) {
- var a = new Node(this.clone().polygons);
- var b = new Node(csg.clone().polygons);
- a.invert();
- b.clipTo(a);
- b.invert();
- a.clipTo(b);
- b.clipTo(a);
- a.build(b.allPolygons());
- a.invert();
- return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
- };
- CSG.prototype.intersectInPlace = function (csg) {
- var a = new Node(this.polygons);
- var b = new Node(csg.polygons);
- a.invert();
- b.clipTo(a);
- b.invert();
- a.clipTo(b);
- b.clipTo(a);
- a.build(b.allPolygons());
- a.invert();
- this.polygons = a.allPolygons();
- };
- // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
- // not modified.
- CSG.prototype.inverse = function () {
- var csg = this.clone();
- csg.inverseInPlace();
- return csg;
- };
- CSG.prototype.inverseInPlace = function () {
- this.polygons.map(function (p) { p.flip(); });
- };
- // This is used to keep meshes transformations so they can be restored
- // when we build back a Babylon Mesh
- // NB : All CSG operations are performed in world coordinates
- CSG.prototype.copyTransformAttributes = function (csg) {
- this.matrix = csg.matrix;
- this.position = csg.position;
- this.rotation = csg.rotation;
- this.scaling = csg.scaling;
- this.rotationQuaternion = csg.rotationQuaternion;
- return this;
- };
- // Build Raw mesh from CSG
- // Coordinates here are in world space
- CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
- var matrix = this.matrix.clone();
- matrix.invert();
- 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;
- if (keepSubMeshes) {
- // Sort Polygons, since subMeshes are indices range
- polygons.sort(function (a, b) {
- if (a.shared.meshId === b.shared.meshId) {
- return a.shared.subMeshId - b.shared.subMeshId;
- }
- else {
- return a.shared.meshId - b.shared.meshId;
- }
- });
- }
- for (var i = 0, il = polygons.length; i < il; i++) {
- polygon = polygons[i];
- // Building SubMeshes
- if (!subMesh_dict[polygon.shared.meshId]) {
- subMesh_dict[polygon.shared.meshId] = {};
- }
- if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
- subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
- indexStart: +Infinity,
- indexEnd: -Infinity,
- materialIndex: polygon.shared.materialIndex
- };
- }
- subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
- for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
- polygonIndices[0] = 0;
- polygonIndices[1] = j - 1;
- polygonIndices[2] = j;
- for (var k = 0; k < 3; k++) {
- vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
- normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
- uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
- var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
- var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
- vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
- // Check if 2 points can be merged
- if (!(typeof vertex_idx !== 'undefined' &&
- normals[vertex_idx * 3] === localNormal.x &&
- normals[vertex_idx * 3 + 1] === localNormal.y &&
- normals[vertex_idx * 3 + 2] === localNormal.z &&
- uvs[vertex_idx * 2] === uv.x &&
- uvs[vertex_idx * 2 + 1] === uv.y)) {
- vertices.push(localVertex.x, localVertex.y, localVertex.z);
- uvs.push(uv.x, uv.y);
- normals.push(normal.x, normal.y, normal.z);
- vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
- }
- indices.push(vertex_idx);
- subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
- subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
- currentIndex++;
- }
- }
- }
- mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
- mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
- mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
- mesh.setIndices(indices);
- if (keepSubMeshes) {
- // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
- var materialIndexOffset = 0, materialMaxIndex;
- mesh.subMeshes = new Array();
- for (var m in subMesh_dict) {
- materialMaxIndex = -1;
- for (var sm in subMesh_dict[m]) {
- subMesh_obj = subMesh_dict[m][sm];
- BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
- materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
- }
- materialIndexOffset += ++materialMaxIndex;
- }
- }
- return mesh;
- };
- // Build Mesh from CSG taking material and transforms into account
- CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
- var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
- mesh.material = material;
- mesh.position.copyFrom(this.position);
- mesh.rotation.copyFrom(this.rotation);
- if (this.rotationQuaternion) {
- mesh.rotationQuaternion = this.rotationQuaternion.clone();
- }
- mesh.scaling.copyFrom(this.scaling);
- mesh.computeWorldMatrix(true);
- return mesh;
- };
- return CSG;
- })();
- BABYLON.CSG = CSG;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var VRDistortionCorrectionPostProcess = (function (_super) {
- __extends(VRDistortionCorrectionPostProcess, _super);
- //ANY
- function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
- var _this = this;
- _super.call(this, name, "vrDistortionCorrection", [
- 'LensCenter',
- 'Scale',
- 'ScaleIn',
- 'HmdWarpParam'
- ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
- this._isRightEye = isRightEye;
- this._distortionFactors = vrMetrics.distortionK;
- this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
- this._lensCenterOffset = vrMetrics.lensCenterOffset;
- this.onSizeChanged = function () {
- _this.aspectRatio = _this.width * .5 / _this.height;
- _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
- _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
- _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
- };
- this.onApply = function (effect) {
- effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
- effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
- effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
- effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
- };
- }
- return VRDistortionCorrectionPostProcess;
- })(BABYLON.PostProcess);
- BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
- })(BABYLON || (BABYLON = {}));
- // Mainly based on these 2 articles :
- // 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
- // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
- var BABYLON;
- (function (BABYLON) {
- (function (JoystickAxis) {
- JoystickAxis[JoystickAxis["X"] = 0] = "X";
- JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
- JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
- })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
- var JoystickAxis = BABYLON.JoystickAxis;
- var VirtualJoystick = (function () {
- function VirtualJoystick(leftJoystick) {
- var _this = this;
- if (leftJoystick) {
- this._leftJoystick = true;
- }
- else {
- this._leftJoystick = false;
- }
- this._joystickIndex = VirtualJoystick._globalJoystickIndex;
- VirtualJoystick._globalJoystickIndex++;
- // By default left & right arrow keys are moving the X
- // and up & down keys are moving the Y
- this._axisTargetedByLeftAndRight = JoystickAxis.X;
- this._axisTargetedByUpAndDown = JoystickAxis.Y;
- this.reverseLeftRight = false;
- this.reverseUpDown = false;
- // collections of pointers
- this._touches = new BABYLON.StringDictionary();
- this.deltaPosition = BABYLON.Vector3.Zero();
- this._joystickSensibility = 25;
- this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
- this._rotationSpeed = 25;
- this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
- this._rotateOnAxisRelativeToMesh = false;
- this._onResize = function (evt) {
- VirtualJoystick.vjCanvasWidth = window.innerWidth;
- VirtualJoystick.vjCanvasHeight = window.innerHeight;
- VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
- VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
- VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
- VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
- };
- // injecting a canvas element on top of the canvas 3D game
- if (!VirtualJoystick.vjCanvas) {
- window.addEventListener("resize", this._onResize, false);
- VirtualJoystick.vjCanvas = document.createElement("canvas");
- VirtualJoystick.vjCanvasWidth = window.innerWidth;
- VirtualJoystick.vjCanvasHeight = window.innerHeight;
- VirtualJoystick.vjCanvas.width = window.innerWidth;
- VirtualJoystick.vjCanvas.height = window.innerHeight;
- VirtualJoystick.vjCanvas.style.width = "100%";
- VirtualJoystick.vjCanvas.style.height = "100%";
- VirtualJoystick.vjCanvas.style.position = "absolute";
- VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
- VirtualJoystick.vjCanvas.style.top = "0px";
- VirtualJoystick.vjCanvas.style.left = "0px";
- VirtualJoystick.vjCanvas.style.zIndex = "5";
- VirtualJoystick.vjCanvas.style.msTouchAction = "none";
- // Support for jQuery PEP polyfill
- VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
- VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
- VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
- VirtualJoystick.vjCanvasContext.lineWidth = 2;
- document.body.appendChild(VirtualJoystick.vjCanvas);
- }
- VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
- VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
- this.pressed = false;
- // default joystick color
- this._joystickColor = "cyan";
- this._joystickPointerID = -1;
- // current joystick position
- this._joystickPointerPos = new BABYLON.Vector2(0, 0);
- this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
- // origin joystick position
- this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
- this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
- this._onPointerDownHandlerRef = function (evt) {
- _this._onPointerDown(evt);
- };
- this._onPointerMoveHandlerRef = function (evt) {
- _this._onPointerMove(evt);
- };
- this._onPointerOutHandlerRef = function (evt) {
- _this._onPointerUp(evt);
- };
- this._onPointerUpHandlerRef = function (evt) {
- _this._onPointerUp(evt);
- };
- VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
- VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
- VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
- VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
- VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
- evt.preventDefault(); // Disables system menu
- }, false);
- requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
- }
- VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
- this._joystickSensibility = newJoystickSensibility;
- this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
- };
- VirtualJoystick.prototype._onPointerDown = function (e) {
- var positionOnScreenCondition;
- e.preventDefault();
- if (this._leftJoystick === true) {
- positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
- }
- else {
- positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
- }
- if (positionOnScreenCondition && this._joystickPointerID < 0) {
- // First contact will be dedicated to the virtual joystick
- this._joystickPointerID = e.pointerId;
- this._joystickPointerStartPos.x = e.clientX;
- this._joystickPointerStartPos.y = e.clientY;
- this._joystickPointerPos = this._joystickPointerStartPos.clone();
- this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
- this._deltaJoystickVector.x = 0;
- this._deltaJoystickVector.y = 0;
- this.pressed = true;
- this._touches.add(e.pointerId.toString(), e);
- }
- else {
- // You can only trigger the action buttons with a joystick declared
- if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
- this._action();
- this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
- }
- }
- };
- VirtualJoystick.prototype._onPointerMove = function (e) {
- // If the current pointer is the one associated to the joystick (first touch contact)
- if (this._joystickPointerID == e.pointerId) {
- this._joystickPointerPos.x = e.clientX;
- this._joystickPointerPos.y = e.clientY;
- this._deltaJoystickVector = this._joystickPointerPos.clone();
- this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
- var directionLeftRight = this.reverseLeftRight ? -1 : 1;
- var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
- switch (this._axisTargetedByLeftAndRight) {
- case JoystickAxis.X:
- this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
- break;
- case JoystickAxis.Y:
- this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
- break;
- case JoystickAxis.Z:
- this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
- break;
- }
- var directionUpDown = this.reverseUpDown ? 1 : -1;
- var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
- switch (this._axisTargetedByUpAndDown) {
- case JoystickAxis.X:
- this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
- break;
- case JoystickAxis.Y:
- this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
- break;
- case JoystickAxis.Z:
- this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
- break;
- }
- }
- else {
- var data = this._touches.get(e.pointerId.toString());
- if (data) {
- data.x = e.clientX;
- data.y = e.clientY;
- }
- }
- };
- VirtualJoystick.prototype._onPointerUp = function (e) {
- if (this._joystickPointerID == e.pointerId) {
- VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
- VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
- this._joystickPointerID = -1;
- this.pressed = false;
- }
- else {
- var touch = this._touches.get(e.pointerId.toString());
- if (touch) {
- VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
- }
- }
- this._deltaJoystickVector.x = 0;
- this._deltaJoystickVector.y = 0;
- this._touches.remove(e.pointerId.toString());
- };
- /**
- * Change the color of the virtual joystick
- * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
- */
- VirtualJoystick.prototype.setJoystickColor = function (newColor) {
- this._joystickColor = newColor;
- };
- VirtualJoystick.prototype.setActionOnTouch = function (action) {
- this._action = action;
- };
- // Define which axis you'd like to control for left & right
- VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
- switch (axis) {
- case JoystickAxis.X:
- case JoystickAxis.Y:
- case JoystickAxis.Z:
- this._axisTargetedByLeftAndRight = axis;
- break;
- default:
- this._axisTargetedByLeftAndRight = JoystickAxis.X;
- break;
- }
- };
- // Define which axis you'd like to control for up & down
- VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
- switch (axis) {
- case JoystickAxis.X:
- case JoystickAxis.Y:
- case JoystickAxis.Z:
- this._axisTargetedByUpAndDown = axis;
- break;
- default:
- this._axisTargetedByUpAndDown = JoystickAxis.Y;
- break;
- }
- };
- VirtualJoystick.prototype._clearCanvas = function () {
- if (this._leftJoystick) {
- VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
- }
- else {
- VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
- }
- };
- VirtualJoystick.prototype._drawVirtualJoystick = function () {
- var _this = this;
- if (this.pressed) {
- this._touches.forEach(function (touch) {
- if (touch.pointerId === _this._joystickPointerID) {
- VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
- VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
- VirtualJoystick.vjCanvasContext.beginPath();
- VirtualJoystick.vjCanvasContext.lineWidth = 6;
- VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
- VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
- VirtualJoystick.vjCanvasContext.stroke();
- VirtualJoystick.vjCanvasContext.closePath();
- VirtualJoystick.vjCanvasContext.beginPath();
- VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
- VirtualJoystick.vjCanvasContext.lineWidth = 2;
- VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
- VirtualJoystick.vjCanvasContext.stroke();
- VirtualJoystick.vjCanvasContext.closePath();
- VirtualJoystick.vjCanvasContext.beginPath();
- VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
- VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
- VirtualJoystick.vjCanvasContext.stroke();
- VirtualJoystick.vjCanvasContext.closePath();
- _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
- }
- else {
- VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
- VirtualJoystick.vjCanvasContext.beginPath();
- VirtualJoystick.vjCanvasContext.fillStyle = "white";
- VirtualJoystick.vjCanvasContext.beginPath();
- VirtualJoystick.vjCanvasContext.strokeStyle = "red";
- VirtualJoystick.vjCanvasContext.lineWidth = 6;
- VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
- VirtualJoystick.vjCanvasContext.stroke();
- VirtualJoystick.vjCanvasContext.closePath();
- touch.prevX = touch.x;
- touch.prevY = touch.y;
- }
- ;
- });
- }
- requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
- };
- VirtualJoystick.prototype.releaseCanvas = function () {
- if (VirtualJoystick.vjCanvas) {
- VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
- VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
- VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
- VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
- window.removeEventListener("resize", this._onResize);
- document.body.removeChild(VirtualJoystick.vjCanvas);
- VirtualJoystick.vjCanvas = null;
- }
- };
- // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
- VirtualJoystick._globalJoystickIndex = 0;
- return VirtualJoystick;
- })();
- BABYLON.VirtualJoystick = VirtualJoystick;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- // We're mainly based on the logic defined into the FreeCamera code
- var VirtualJoysticksCamera = (function (_super) {
- __extends(VirtualJoysticksCamera, _super);
- function VirtualJoysticksCamera(name, position, scene) {
- _super.call(this, name, position, scene);
- this.inputs.addVirtualJoystick();
- }
- return VirtualJoysticksCamera;
- })(BABYLON.FreeCamera);
- BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var AnaglyphPostProcess = (function (_super) {
- __extends(AnaglyphPostProcess, _super);
- function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
- _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
- }
- return AnaglyphPostProcess;
- })(BABYLON.PostProcess);
- BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var OutlineRenderer = (function () {
- function OutlineRenderer(scene) {
- this._scene = scene;
- }
- OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
- var _this = this;
- if (useOverlay === void 0) { useOverlay = false; }
- var scene = this._scene;
- var engine = this._scene.getEngine();
- var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
- if (!this.isReady(subMesh, hardwareInstancedRendering)) {
- return;
- }
- var mesh = subMesh.getRenderingMesh();
- var material = subMesh.getMaterial();
- engine.enableEffect(this._effect);
- this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
- this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
- this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
- // Bones
- if (mesh.useBones && mesh.computeBonesUsingShaders) {
- this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
- }
- mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
- // Alpha test
- if (material && material.needAlphaTesting()) {
- var alphaTexture = material.getAlphaTestTexture();
- this._effect.setTexture("diffuseSampler", alphaTexture);
- this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
- }
- mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
- };
- OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
- var defines = [];
- var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
- var mesh = subMesh.getMesh();
- var material = subMesh.getMaterial();
- // Alpha test
- if (material && material.needAlphaTesting()) {
- defines.push("#define ALPHATEST");
- if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
- attribs.push(BABYLON.VertexBuffer.UVKind);
- defines.push("#define UV1");
- }
- if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
- attribs.push(BABYLON.VertexBuffer.UV2Kind);
- defines.push("#define UV2");
- }
- }
- // Bones
- if (mesh.useBones && mesh.computeBonesUsingShaders) {
- attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
- attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
- if (mesh.numBoneInfluencers > 4) {
- attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
- attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
- }
- defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
- defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
- }
- else {
- defines.push("#define NUM_BONE_INFLUENCERS 0");
- }
- // Instances
- if (useInstances) {
- defines.push("#define INSTANCES");
- attribs.push("world0");
- attribs.push("world1");
- attribs.push("world2");
- attribs.push("world3");
- }
- // Get correct effect
- var join = defines.join("\n");
- if (this._cachedDefines !== join) {
- this._cachedDefines = join;
- this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
- }
- return this._effect.isReady();
- };
- return OutlineRenderer;
- })();
- BABYLON.OutlineRenderer = OutlineRenderer;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var MeshAssetTask = (function () {
- function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
- this.name = name;
- this.meshesNames = meshesNames;
- this.rootUrl = rootUrl;
- this.sceneFilename = sceneFilename;
- this.isCompleted = false;
- }
- MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
- var _this = this;
- BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
- _this.loadedMeshes = meshes;
- _this.loadedParticleSystems = particleSystems;
- _this.loadedSkeletons = skeletons;
- _this.isCompleted = true;
- if (_this.onSuccess) {
- _this.onSuccess(_this);
- }
- onSuccess();
- }, null, function () {
- if (_this.onError) {
- _this.onError(_this);
- }
- onError();
- });
- };
- return MeshAssetTask;
- })();
- BABYLON.MeshAssetTask = MeshAssetTask;
- var TextFileAssetTask = (function () {
- function TextFileAssetTask(name, url) {
- this.name = name;
- this.url = url;
- this.isCompleted = false;
- }
- TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
- var _this = this;
- BABYLON.Tools.LoadFile(this.url, function (data) {
- _this.text = data;
- _this.isCompleted = true;
- if (_this.onSuccess) {
- _this.onSuccess(_this);
- }
- onSuccess();
- }, null, scene.database, false, function () {
- if (_this.onError) {
- _this.onError(_this);
- }
- onError();
- });
- };
- return TextFileAssetTask;
- })();
- BABYLON.TextFileAssetTask = TextFileAssetTask;
- var BinaryFileAssetTask = (function () {
- function BinaryFileAssetTask(name, url) {
- this.name = name;
- this.url = url;
- this.isCompleted = false;
- }
- BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
- var _this = this;
- BABYLON.Tools.LoadFile(this.url, function (data) {
- _this.data = data;
- _this.isCompleted = true;
- if (_this.onSuccess) {
- _this.onSuccess(_this);
- }
- onSuccess();
- }, null, scene.database, true, function () {
- if (_this.onError) {
- _this.onError(_this);
- }
- onError();
- });
- };
- return BinaryFileAssetTask;
- })();
- BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
- var ImageAssetTask = (function () {
- function ImageAssetTask(name, url) {
- this.name = name;
- this.url = url;
- this.isCompleted = false;
- }
- ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
- var _this = this;
- var img = new Image();
- img.onload = function () {
- _this.image = img;
- _this.isCompleted = true;
- if (_this.onSuccess) {
- _this.onSuccess(_this);
- }
- onSuccess();
- };
- img.onerror = function () {
- if (_this.onError) {
- _this.onError(_this);
- }
- onError();
- };
- img.src = this.url;
- };
- return ImageAssetTask;
- })();
- BABYLON.ImageAssetTask = ImageAssetTask;
- var TextureAssetTask = (function () {
- function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
- this.name = name;
- this.url = url;
- this.noMipmap = noMipmap;
- this.invertY = invertY;
- this.samplingMode = samplingMode;
- this.isCompleted = false;
- }
- TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
- var _this = this;
- var onload = function () {
- _this.isCompleted = true;
- if (_this.onSuccess) {
- _this.onSuccess(_this);
- }
- onSuccess();
- };
- var onerror = function () {
- if (_this.onError) {
- _this.onError(_this);
- }
- onError();
- };
- this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
- };
- return TextureAssetTask;
- })();
- BABYLON.TextureAssetTask = TextureAssetTask;
- var AssetsManager = (function () {
- function AssetsManager(scene) {
- this._tasks = new Array();
- this._waitingTasksCount = 0;
- this.useDefaultLoadingScreen = true;
- this._scene = scene;
- }
- AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
- var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
- this._tasks.push(task);
- return task;
- };
- AssetsManager.prototype.addTextFileTask = function (taskName, url) {
- var task = new TextFileAssetTask(taskName, url);
- this._tasks.push(task);
- return task;
- };
- AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
- var task = new BinaryFileAssetTask(taskName, url);
- this._tasks.push(task);
- return task;
- };
- AssetsManager.prototype.addImageTask = function (taskName, url) {
- var task = new ImageAssetTask(taskName, url);
- this._tasks.push(task);
- return task;
- };
- AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
- var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
- this._tasks.push(task);
- return task;
- };
- AssetsManager.prototype._decreaseWaitingTasksCount = function () {
- this._waitingTasksCount--;
- if (this._waitingTasksCount === 0) {
- if (this.onFinish) {
- this.onFinish(this._tasks);
- }
- this._scene.getEngine().hideLoadingUI();
- }
- };
- AssetsManager.prototype._runTask = function (task) {
- var _this = this;
- task.run(this._scene, function () {
- if (_this.onTaskSuccess) {
- _this.onTaskSuccess(task);
- }
- _this._decreaseWaitingTasksCount();
- }, function () {
- if (_this.onTaskError) {
- _this.onTaskError(task);
- }
- _this._decreaseWaitingTasksCount();
- });
- };
- AssetsManager.prototype.reset = function () {
- this._tasks = new Array();
- return this;
- };
- AssetsManager.prototype.load = function () {
- this._waitingTasksCount = this._tasks.length;
- if (this._waitingTasksCount === 0) {
- if (this.onFinish) {
- this.onFinish(this._tasks);
- }
- return this;
- }
- if (this.useDefaultLoadingScreen) {
- this._scene.getEngine().displayLoadingUI();
- }
- for (var index = 0; index < this._tasks.length; index++) {
- var task = this._tasks[index];
- this._runTask(task);
- }
- return this;
- };
- return AssetsManager;
- })();
- BABYLON.AssetsManager = AssetsManager;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var VRCameraMetrics = (function () {
- function VRCameraMetrics() {
- this.compensateDistortion = true;
- }
- Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
- get: function () {
- return this.hResolution / (2 * this.vResolution);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
- get: function () {
- return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
- get: function () {
- var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
- var h = (4 * meters) / this.hScreenSize;
- return BABYLON.Matrix.Translation(h, 0, 0);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
- get: function () {
- var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
- var h = (4 * meters) / this.hScreenSize;
- return BABYLON.Matrix.Translation(-h, 0, 0);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
- get: function () {
- return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
- get: function () {
- return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
- },
- enumerable: true,
- configurable: true
- });
- VRCameraMetrics.GetDefault = function () {
- var result = new VRCameraMetrics();
- result.hResolution = 1280;
- result.vResolution = 800;
- result.hScreenSize = 0.149759993;
- result.vScreenSize = 0.0935999975;
- result.vScreenCenter = 0.0467999987,
- result.eyeToScreenDistance = 0.0410000011;
- result.lensSeparationDistance = 0.0635000020;
- result.interpupillaryDistance = 0.0640000030;
- result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
- result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
- result.postProcessScaleFactor = 1.714605507808412;
- result.lensCenterOffset = 0.151976421;
- return result;
- };
- return VRCameraMetrics;
- })();
- BABYLON.VRCameraMetrics = VRCameraMetrics;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var VRDeviceOrientationFreeCamera = (function (_super) {
- __extends(VRDeviceOrientationFreeCamera, _super);
- function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
- if (compensateDistortion === void 0) { compensateDistortion = true; }
- _super.call(this, name, position, scene);
- var metrics = BABYLON.VRCameraMetrics.GetDefault();
- metrics.compensateDistortion = compensateDistortion;
- this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
- this.inputs.addVRDeviceOrientation();
- }
- VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
- return "VRDeviceOrientationFreeCamera";
- };
- return VRDeviceOrientationFreeCamera;
- })(BABYLON.FreeCamera);
- BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
- var VRDeviceOrientationArcRotateCamera = (function (_super) {
- __extends(VRDeviceOrientationArcRotateCamera, _super);
- function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion) {
- if (compensateDistortion === void 0) { compensateDistortion = true; }
- _super.call(this, name, alpha, beta, radius, target, scene);
- var metrics = BABYLON.VRCameraMetrics.GetDefault();
- metrics.compensateDistortion = compensateDistortion;
- this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
- this.inputs.addVRDeviceOrientation();
- }
- VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
- return "VRDeviceOrientationArcRotateCamera";
- };
- return VRDeviceOrientationArcRotateCamera;
- })(BABYLON.ArcRotateCamera);
- BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var WebVRFreeCamera = (function (_super) {
- __extends(WebVRFreeCamera, _super);
- function WebVRFreeCamera(name, position, scene, compensateDistortion) {
- if (compensateDistortion === void 0) { compensateDistortion = true; }
- _super.call(this, name, position, scene);
- this._hmdDevice = null;
- this._sensorDevice = null;
- this._cacheState = null;
- this._cacheQuaternion = new BABYLON.Quaternion();
- this._cacheRotation = BABYLON.Vector3.Zero();
- this._vrEnabled = false;
- var metrics = BABYLON.VRCameraMetrics.GetDefault();
- metrics.compensateDistortion = compensateDistortion;
- this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
- this._getWebVRDevices = this._getWebVRDevices.bind(this);
- }
- WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
- var size = devices.length;
- var i = 0;
- // Reset devices.
- this._sensorDevice = null;
- this._hmdDevice = null;
- // Search for a HmdDevice.
- while (i < size && this._hmdDevice === null) {
- if (devices[i] instanceof HMDVRDevice) {
- this._hmdDevice = devices[i];
- }
- i++;
- }
- i = 0;
- while (i < size && this._sensorDevice === null) {
- if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
- this._sensorDevice = devices[i];
- }
- i++;
- }
- this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
- };
- WebVRFreeCamera.prototype._checkInputs = function () {
- if (this._vrEnabled) {
- this._cacheState = this._sensorDevice.getState();
- this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
- this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
- this.rotation.x = -this._cacheRotation.x;
- this.rotation.y = -this._cacheRotation.y;
- this.rotation.z = this._cacheRotation.z;
- }
- _super.prototype._checkInputs.call(this);
- };
- WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
- _super.prototype.attachControl.call(this, element, noPreventDefault);
- noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
- if (navigator.getVRDevices) {
- navigator.getVRDevices().then(this._getWebVRDevices);
- }
- else if (navigator.mozGetVRDevices) {
- navigator.mozGetVRDevices(this._getWebVRDevices);
- }
- };
- WebVRFreeCamera.prototype.detachControl = function (element) {
- _super.prototype.detachControl.call(this, element);
- this._vrEnabled = false;
- };
- WebVRFreeCamera.prototype.getTypeName = function () {
- return "WebVRFreeCamera";
- };
- return WebVRFreeCamera;
- })(BABYLON.FreeCamera);
- BABYLON.WebVRFreeCamera = WebVRFreeCamera;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- // Standard optimizations
- var SceneOptimization = (function () {
- function SceneOptimization(priority) {
- if (priority === void 0) { priority = 0; }
- this.priority = priority;
- this.apply = function (scene) {
- return true; // Return true if everything that can be done was applied
- };
- }
- return SceneOptimization;
- })();
- BABYLON.SceneOptimization = SceneOptimization;
- var TextureOptimization = (function (_super) {
- __extends(TextureOptimization, _super);
- function TextureOptimization(priority, maximumSize) {
- var _this = this;
- if (priority === void 0) { priority = 0; }
- if (maximumSize === void 0) { maximumSize = 1024; }
- _super.call(this, priority);
- this.priority = priority;
- this.maximumSize = maximumSize;
- this.apply = function (scene) {
- var allDone = true;
- for (var index = 0; index < scene.textures.length; index++) {
- var texture = scene.textures[index];
- if (!texture.canRescale) {
- continue;
- }
- var currentSize = texture.getSize();
- var maxDimension = Math.max(currentSize.width, currentSize.height);
- if (maxDimension > _this.maximumSize) {
- texture.scale(0.5);
- allDone = false;
- }
- }
- return allDone;
- };
- }
- return TextureOptimization;
- })(SceneOptimization);
- BABYLON.TextureOptimization = TextureOptimization;
- var HardwareScalingOptimization = (function (_super) {
- __extends(HardwareScalingOptimization, _super);
- function HardwareScalingOptimization(priority, maximumScale) {
- var _this = this;
- if (priority === void 0) { priority = 0; }
- if (maximumScale === void 0) { maximumScale = 2; }
- _super.call(this, priority);
- this.priority = priority;
- this.maximumScale = maximumScale;
- this._currentScale = 1;
- this.apply = function (scene) {
- _this._currentScale++;
- scene.getEngine().setHardwareScalingLevel(_this._currentScale);
- return _this._currentScale >= _this.maximumScale;
- };
- }
- return HardwareScalingOptimization;
- })(SceneOptimization);
- BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
- var ShadowsOptimization = (function (_super) {
- __extends(ShadowsOptimization, _super);
- function ShadowsOptimization() {
- _super.apply(this, arguments);
- this.apply = function (scene) {
- scene.shadowsEnabled = false;
- return true;
- };
- }
- return ShadowsOptimization;
- })(SceneOptimization);
- BABYLON.ShadowsOptimization = ShadowsOptimization;
- var PostProcessesOptimization = (function (_super) {
- __extends(PostProcessesOptimization, _super);
- function PostProcessesOptimization() {
- _super.apply(this, arguments);
- this.apply = function (scene) {
- scene.postProcessesEnabled = false;
- return true;
- };
- }
- return PostProcessesOptimization;
- })(SceneOptimization);
- BABYLON.PostProcessesOptimization = PostProcessesOptimization;
- var LensFlaresOptimization = (function (_super) {
- __extends(LensFlaresOptimization, _super);
- function LensFlaresOptimization() {
- _super.apply(this, arguments);
- this.apply = function (scene) {
- scene.lensFlaresEnabled = false;
- return true;
- };
- }
- return LensFlaresOptimization;
- })(SceneOptimization);
- BABYLON.LensFlaresOptimization = LensFlaresOptimization;
- var ParticlesOptimization = (function (_super) {
- __extends(ParticlesOptimization, _super);
- function ParticlesOptimization() {
- _super.apply(this, arguments);
- this.apply = function (scene) {
- scene.particlesEnabled = false;
- return true;
- };
- }
- return ParticlesOptimization;
- })(SceneOptimization);
- BABYLON.ParticlesOptimization = ParticlesOptimization;
- var RenderTargetsOptimization = (function (_super) {
- __extends(RenderTargetsOptimization, _super);
- function RenderTargetsOptimization() {
- _super.apply(this, arguments);
- this.apply = function (scene) {
- scene.renderTargetsEnabled = false;
- return true;
- };
- }
- return RenderTargetsOptimization;
- })(SceneOptimization);
- BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
- var MergeMeshesOptimization = (function (_super) {
- __extends(MergeMeshesOptimization, _super);
- function MergeMeshesOptimization() {
- var _this = this;
- _super.apply(this, arguments);
- this._canBeMerged = function (abstractMesh) {
- if (!(abstractMesh instanceof BABYLON.Mesh)) {
- return false;
- }
- var mesh = abstractMesh;
- if (!mesh.isVisible || !mesh.isEnabled()) {
- return false;
- }
- if (mesh.instances.length > 0) {
- return false;
- }
- if (mesh.skeleton || mesh.hasLODLevels) {
- return false;
- }
- if (mesh.parent) {
- return false;
- }
- return true;
- };
- this.apply = function (scene, updateSelectionTree) {
- var globalPool = scene.meshes.slice(0);
- var globalLength = globalPool.length;
- for (var index = 0; index < globalLength; index++) {
- var currentPool = new Array();
- var current = globalPool[index];
- // Checks
- if (!_this._canBeMerged(current)) {
- continue;
- }
- currentPool.push(current);
- // Find compatible meshes
- for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
- var otherMesh = globalPool[subIndex];
- if (!_this._canBeMerged(otherMesh)) {
- continue;
- }
- if (otherMesh.material !== current.material) {
- continue;
- }
- if (otherMesh.checkCollisions !== current.checkCollisions) {
- continue;
- }
- currentPool.push(otherMesh);
- globalLength--;
- globalPool.splice(subIndex, 1);
- subIndex--;
- }
- if (currentPool.length < 2) {
- continue;
- }
- // Merge meshes
- BABYLON.Mesh.MergeMeshes(currentPool);
- }
- if (updateSelectionTree != undefined) {
- if (updateSelectionTree) {
- scene.createOrUpdateSelectionOctree();
- }
- }
- else if (MergeMeshesOptimization.UpdateSelectionTree) {
- scene.createOrUpdateSelectionOctree();
- }
- return true;
- };
- }
- Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
- get: function () {
- return MergeMeshesOptimization._UpdateSelectionTree;
- },
- set: function (value) {
- MergeMeshesOptimization._UpdateSelectionTree = value;
- },
- enumerable: true,
- configurable: true
- });
- MergeMeshesOptimization._UpdateSelectionTree = false;
- return MergeMeshesOptimization;
- })(SceneOptimization);
- BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
- // Options
- var SceneOptimizerOptions = (function () {
- function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
- if (targetFrameRate === void 0) { targetFrameRate = 60; }
- if (trackerDuration === void 0) { trackerDuration = 2000; }
- this.targetFrameRate = targetFrameRate;
- this.trackerDuration = trackerDuration;
- this.optimizations = new Array();
- }
- SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
- var result = new SceneOptimizerOptions(targetFrameRate);
- var priority = 0;
- result.optimizations.push(new MergeMeshesOptimization(priority));
- result.optimizations.push(new ShadowsOptimization(priority));
- result.optimizations.push(new LensFlaresOptimization(priority));
- // Next priority
- priority++;
- result.optimizations.push(new PostProcessesOptimization(priority));
- result.optimizations.push(new ParticlesOptimization(priority));
- // Next priority
- priority++;
- result.optimizations.push(new TextureOptimization(priority, 1024));
- return result;
- };
- SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
- var result = new SceneOptimizerOptions(targetFrameRate);
- var priority = 0;
- result.optimizations.push(new MergeMeshesOptimization(priority));
- result.optimizations.push(new ShadowsOptimization(priority));
- result.optimizations.push(new LensFlaresOptimization(priority));
- // Next priority
- priority++;
- result.optimizations.push(new PostProcessesOptimization(priority));
- result.optimizations.push(new ParticlesOptimization(priority));
- // Next priority
- priority++;
- result.optimizations.push(new TextureOptimization(priority, 512));
- // Next priority
- priority++;
- result.optimizations.push(new RenderTargetsOptimization(priority));
- // Next priority
- priority++;
- result.optimizations.push(new HardwareScalingOptimization(priority, 2));
- return result;
- };
- SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
- var result = new SceneOptimizerOptions(targetFrameRate);
- var priority = 0;
- result.optimizations.push(new MergeMeshesOptimization(priority));
- result.optimizations.push(new ShadowsOptimization(priority));
- result.optimizations.push(new LensFlaresOptimization(priority));
- // Next priority
- priority++;
- result.optimizations.push(new PostProcessesOptimization(priority));
- result.optimizations.push(new ParticlesOptimization(priority));
- // Next priority
- priority++;
- result.optimizations.push(new TextureOptimization(priority, 256));
- // Next priority
- priority++;
- result.optimizations.push(new RenderTargetsOptimization(priority));
- // Next priority
- priority++;
- result.optimizations.push(new HardwareScalingOptimization(priority, 4));
- return result;
- };
- return SceneOptimizerOptions;
- })();
- BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
- // Scene optimizer tool
- var SceneOptimizer = (function () {
- function SceneOptimizer() {
- }
- SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
- // TODO: add an epsilon
- if (scene.getEngine().getFps() >= options.targetFrameRate) {
- if (onSuccess) {
- onSuccess();
- }
- return;
- }
- // Apply current level of optimizations
- var allDone = true;
- var noOptimizationApplied = true;
- for (var index = 0; index < options.optimizations.length; index++) {
- var optimization = options.optimizations[index];
- if (optimization.priority === currentPriorityLevel) {
- noOptimizationApplied = false;
- allDone = allDone && optimization.apply(scene);
- }
- }
- // If no optimization was applied, this is a failure :(
- if (noOptimizationApplied) {
- if (onFailure) {
- onFailure();
- }
- return;
- }
- // If all optimizations were done, move to next level
- if (allDone) {
- currentPriorityLevel++;
- }
- // Let's the system running for a specific amount of time before checking FPS
- scene.executeWhenReady(function () {
- setTimeout(function () {
- SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
- }, options.trackerDuration);
- });
- };
- SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
- if (!options) {
- options = SceneOptimizerOptions.ModerateDegradationAllowed();
- }
- // Let's the system running for a specific amount of time before checking FPS
- scene.executeWhenReady(function () {
- setTimeout(function () {
- SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
- }, options.trackerDuration);
- });
- };
- return SceneOptimizer;
- })();
- BABYLON.SceneOptimizer = SceneOptimizer;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Internals;
- (function (Internals) {
- var MeshLODLevel = (function () {
- function MeshLODLevel(distance, mesh) {
- this.distance = distance;
- this.mesh = mesh;
- }
- return MeshLODLevel;
- })();
- Internals.MeshLODLevel = MeshLODLevel;
- })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var RawTexture = (function (_super) {
- __extends(RawTexture, _super);
- function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
- if (generateMipMaps === void 0) { generateMipMaps = true; }
- if (invertY === void 0) { invertY = false; }
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
- _super.call(this, null, scene, !generateMipMaps, invertY);
- this.format = format;
- this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
- this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
- this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
- }
- RawTexture.prototype.update = function (data) {
- this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
- };
- // Statics
- RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
- if (generateMipMaps === void 0) { generateMipMaps = true; }
- if (invertY === void 0) { invertY = false; }
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
- return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
- };
- RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
- if (generateMipMaps === void 0) { generateMipMaps = true; }
- if (invertY === void 0) { invertY = false; }
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
- return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
- };
- RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
- if (generateMipMaps === void 0) { generateMipMaps = true; }
- if (invertY === void 0) { invertY = false; }
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
- return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
- };
- RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
- if (generateMipMaps === void 0) { generateMipMaps = true; }
- if (invertY === void 0) { invertY = false; }
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
- return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
- };
- RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
- if (generateMipMaps === void 0) { generateMipMaps = true; }
- if (invertY === void 0) { invertY = false; }
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
- return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
- };
- return RawTexture;
- })(BABYLON.Texture);
- BABYLON.RawTexture = RawTexture;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var IndexedVector2 = (function (_super) {
- __extends(IndexedVector2, _super);
- function IndexedVector2(original, index) {
- _super.call(this, original.x, original.y);
- this.index = index;
- }
- return IndexedVector2;
- })(BABYLON.Vector2);
- var PolygonPoints = (function () {
- function PolygonPoints() {
- this.elements = new Array();
- }
- PolygonPoints.prototype.add = function (originalPoints) {
- var _this = this;
- var result = new Array();
- originalPoints.forEach(function (point) {
- if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
- var newPoint = new IndexedVector2(point, _this.elements.length);
- result.push(newPoint);
- _this.elements.push(newPoint);
- }
- });
- return result;
- };
- PolygonPoints.prototype.computeBounds = function () {
- var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
- var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
- this.elements.forEach(function (point) {
- // x
- if (point.x < lmin.x) {
- lmin.x = point.x;
- }
- else if (point.x > lmax.x) {
- lmax.x = point.x;
- }
- // y
- if (point.y < lmin.y) {
- lmin.y = point.y;
- }
- else if (point.y > lmax.y) {
- lmax.y = point.y;
- }
- });
- return {
- min: lmin,
- max: lmax,
- width: lmax.x - lmin.x,
- height: lmax.y - lmin.y
- };
- };
- return PolygonPoints;
- })();
- var Polygon = (function () {
- function Polygon() {
- }
- Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
- return [
- new BABYLON.Vector2(xmin, ymin),
- new BABYLON.Vector2(xmax, ymin),
- new BABYLON.Vector2(xmax, ymax),
- new BABYLON.Vector2(xmin, ymax)
- ];
- };
- Polygon.Circle = function (radius, cx, cy, numberOfSides) {
- if (cx === void 0) { cx = 0; }
- if (cy === void 0) { cy = 0; }
- if (numberOfSides === void 0) { numberOfSides = 32; }
- var result = new Array();
- var angle = 0;
- var increment = (Math.PI * 2) / numberOfSides;
- for (var i = 0; i < numberOfSides; i++) {
- result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
- angle -= increment;
- }
- return result;
- };
- Polygon.Parse = function (input) {
- var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
- var i, result = [];
- for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
- result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
- }
- return result;
- };
- Polygon.StartingAt = function (x, y) {
- return BABYLON.Path2.StartingAt(x, y);
- };
- return Polygon;
- })();
- BABYLON.Polygon = Polygon;
- var PolygonMeshBuilder = (function () {
- function PolygonMeshBuilder(name, contours, scene) {
- this._points = new PolygonPoints();
- this._outlinepoints = new PolygonPoints();
- this._holes = [];
- if (!("poly2tri" in window)) {
- throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
- }
- this._name = name;
- this._scene = scene;
- var points;
- if (contours instanceof BABYLON.Path2) {
- points = contours.getPoints();
- }
- else {
- points = contours;
- }
- this._swctx = new poly2tri.SweepContext(this._points.add(points));
- this._outlinepoints.add(points);
- }
- PolygonMeshBuilder.prototype.addHole = function (hole) {
- this._swctx.addHole(this._points.add(hole));
- var holepoints = new PolygonPoints();
- holepoints.add(hole);
- this._holes.push(holepoints);
- return this;
- };
- PolygonMeshBuilder.prototype.build = function (updatable, depth) {
- var _this = this;
- if (updatable === void 0) { updatable = false; }
- var result = new BABYLON.Mesh(this._name, this._scene);
- var normals = [];
- var positions = [];
- var uvs = [];
- var bounds = this._points.computeBounds();
- this._points.elements.forEach(function (p) {
- normals.push(0, 1.0, 0);
- positions.push(p.x, 0, p.y);
- uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
- });
- var indices = [];
- this._swctx.triangulate();
- this._swctx.getTriangles().forEach(function (triangle) {
- triangle.getPoints().forEach(function (point) {
- indices.push(point.index);
- });
- });
- if (depth > 0) {
- var positionscount = (positions.length / 3); //get the current pointcount
- this._points.elements.forEach(function (p) {
- normals.push(0, -1.0, 0);
- positions.push(p.x, -depth, p.y);
- uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
- });
- var p1; //we need to change order of point so the triangles are made in the rigth way.
- var p2;
- var poscounter = 0;
- this._swctx.getTriangles().forEach(function (triangle) {
- triangle.getPoints().forEach(function (point) {
- switch (poscounter) {
- case 0:
- p1 = point;
- break;
- case 1:
- p2 = point;
- break;
- case 2:
- indices.push(point.index + positionscount);
- indices.push(p2.index + positionscount);
- indices.push(p1.index + positionscount);
- poscounter = -1;
- break;
- }
- poscounter++;
- //indices.push((<IndexedVector2>point).index + positionscount);
- });
- });
- //Add the sides
- this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
- this._holes.forEach(function (hole) {
- _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
- });
- }
- result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
- result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
- result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
- result.setIndices(indices);
- return result;
- };
- PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
- var StartIndex = positions.length / 3;
- var ulength = 0;
- for (var i = 0; i < points.elements.length; i++) {
- var p = points.elements[i];
- var p1;
- if ((i + 1) > points.elements.length - 1) {
- p1 = points.elements[0];
- }
- else {
- p1 = points.elements[i + 1];
- }
- positions.push(p.x, 0, p.y);
- positions.push(p.x, -depth, p.y);
- positions.push(p1.x, 0, p1.y);
- positions.push(p1.x, -depth, p1.y);
- var v1 = new BABYLON.Vector3(p.x, 0, p.y);
- var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
- var v3 = v2.subtract(v1);
- var v4 = new BABYLON.Vector3(0, 1, 0);
- var vn = BABYLON.Vector3.Cross(v3, v4);
- vn = vn.normalize();
- uvs.push(ulength / bounds.width, 0);
- uvs.push(ulength / bounds.width, 1);
- ulength += v3.length();
- uvs.push((ulength / bounds.width), 0);
- uvs.push((ulength / bounds.width), 1);
- if (!flip) {
- normals.push(-vn.x, -vn.y, -vn.z);
- normals.push(-vn.x, -vn.y, -vn.z);
- normals.push(-vn.x, -vn.y, -vn.z);
- normals.push(-vn.x, -vn.y, -vn.z);
- indices.push(StartIndex);
- indices.push(StartIndex + 1);
- indices.push(StartIndex + 2);
- indices.push(StartIndex + 1);
- indices.push(StartIndex + 3);
- indices.push(StartIndex + 2);
- }
- else {
- normals.push(vn.x, vn.y, vn.z);
- normals.push(vn.x, vn.y, vn.z);
- normals.push(vn.x, vn.y, vn.z);
- normals.push(vn.x, vn.y, vn.z);
- indices.push(StartIndex);
- indices.push(StartIndex + 2);
- indices.push(StartIndex + 1);
- indices.push(StartIndex + 1);
- indices.push(StartIndex + 2);
- indices.push(StartIndex + 3);
- }
- StartIndex += 4;
- }
- ;
- };
- return PolygonMeshBuilder;
- })();
- BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Octree = (function () {
- function Octree(creationFunc, maxBlockCapacity, maxDepth) {
- if (maxDepth === void 0) { maxDepth = 2; }
- this.maxDepth = maxDepth;
- this.dynamicContent = new Array();
- this._maxBlockCapacity = maxBlockCapacity || 64;
- this._selectionContent = new BABYLON.SmartArray(1024);
- this._creationFunc = creationFunc;
- }
- // Methods
- Octree.prototype.update = function (worldMin, worldMax, entries) {
- Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
- };
- Octree.prototype.addMesh = function (entry) {
- for (var index = 0; index < this.blocks.length; index++) {
- var block = this.blocks[index];
- block.addEntry(entry);
- }
- };
- Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
- this._selectionContent.reset();
- for (var index = 0; index < this.blocks.length; index++) {
- var block = this.blocks[index];
- block.select(frustumPlanes, this._selectionContent, allowDuplicate);
- }
- if (allowDuplicate) {
- this._selectionContent.concat(this.dynamicContent);
- }
- else {
- this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
- }
- return this._selectionContent;
- };
- Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
- this._selectionContent.reset();
- for (var index = 0; index < this.blocks.length; index++) {
- var block = this.blocks[index];
- block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
- }
- if (allowDuplicate) {
- this._selectionContent.concat(this.dynamicContent);
- }
- else {
- this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
- }
- return this._selectionContent;
- };
- Octree.prototype.intersectsRay = function (ray) {
- this._selectionContent.reset();
- for (var index = 0; index < this.blocks.length; index++) {
- var block = this.blocks[index];
- block.intersectsRay(ray, this._selectionContent);
- }
- this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
- return this._selectionContent;
- };
- Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
- target.blocks = new Array();
- var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
- // Segmenting space
- for (var x = 0; x < 2; x++) {
- for (var y = 0; y < 2; y++) {
- for (var z = 0; z < 2; z++) {
- var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
- var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
- var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
- block.addEntries(entries);
- target.blocks.push(block);
- }
- }
- }
- };
- Octree.CreationFuncForMeshes = function (entry, block) {
- if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
- block.entries.push(entry);
- }
- };
- Octree.CreationFuncForSubMeshes = function (entry, block) {
- if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
- block.entries.push(entry);
- }
- };
- return Octree;
- })();
- BABYLON.Octree = Octree;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var OctreeBlock = (function () {
- function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
- this.entries = new Array();
- this._boundingVectors = new Array();
- this._capacity = capacity;
- this._depth = depth;
- this._maxDepth = maxDepth;
- this._creationFunc = creationFunc;
- this._minPoint = minPoint;
- this._maxPoint = maxPoint;
- this._boundingVectors.push(minPoint.clone());
- this._boundingVectors.push(maxPoint.clone());
- this._boundingVectors.push(minPoint.clone());
- this._boundingVectors[2].x = maxPoint.x;
- this._boundingVectors.push(minPoint.clone());
- this._boundingVectors[3].y = maxPoint.y;
- this._boundingVectors.push(minPoint.clone());
- this._boundingVectors[4].z = maxPoint.z;
- this._boundingVectors.push(maxPoint.clone());
- this._boundingVectors[5].z = minPoint.z;
- this._boundingVectors.push(maxPoint.clone());
- this._boundingVectors[6].x = minPoint.x;
- this._boundingVectors.push(maxPoint.clone());
- this._boundingVectors[7].y = minPoint.y;
- }
- Object.defineProperty(OctreeBlock.prototype, "capacity", {
- // Property
- get: function () {
- return this._capacity;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(OctreeBlock.prototype, "minPoint", {
- get: function () {
- return this._minPoint;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
- get: function () {
- return this._maxPoint;
- },
- enumerable: true,
- configurable: true
- });
- // Methods
- OctreeBlock.prototype.addEntry = function (entry) {
- if (this.blocks) {
- for (var index = 0; index < this.blocks.length; index++) {
- var block = this.blocks[index];
- block.addEntry(entry);
- }
- return;
- }
- this._creationFunc(entry, this);
- if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
- this.createInnerBlocks();
- }
- };
- OctreeBlock.prototype.addEntries = function (entries) {
- for (var index = 0; index < entries.length; index++) {
- var mesh = entries[index];
- this.addEntry(mesh);
- }
- };
- OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
- if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
- if (this.blocks) {
- for (var index = 0; index < this.blocks.length; index++) {
- var block = this.blocks[index];
- block.select(frustumPlanes, selection, allowDuplicate);
- }
- return;
- }
- if (allowDuplicate) {
- selection.concat(this.entries);
- }
- else {
- selection.concatWithNoDuplicate(this.entries);
- }
- }
- };
- OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
- if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
- if (this.blocks) {
- for (var index = 0; index < this.blocks.length; index++) {
- var block = this.blocks[index];
- block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
- }
- return;
- }
- if (allowDuplicate) {
- selection.concat(this.entries);
- }
- else {
- selection.concatWithNoDuplicate(this.entries);
- }
- }
- };
- OctreeBlock.prototype.intersectsRay = function (ray, selection) {
- if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
- if (this.blocks) {
- for (var index = 0; index < this.blocks.length; index++) {
- var block = this.blocks[index];
- block.intersectsRay(ray, selection);
- }
- return;
- }
- selection.concatWithNoDuplicate(this.entries);
- }
- };
- OctreeBlock.prototype.createInnerBlocks = function () {
- BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
- };
- return OctreeBlock;
- })();
- BABYLON.OctreeBlock = OctreeBlock;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var BlurPostProcess = (function (_super) {
- __extends(BlurPostProcess, _super);
- function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
- var _this = this;
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
- _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
- this.direction = direction;
- this.blurWidth = blurWidth;
- this.onApply = function (effect) {
- effect.setFloat2("screenSize", _this.width, _this.height);
- effect.setVector2("direction", _this.direction);
- effect.setFloat("blurWidth", _this.blurWidth);
- };
- }
- return BlurPostProcess;
- })(BABYLON.PostProcess);
- BABYLON.BlurPostProcess = BlurPostProcess;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var RefractionPostProcess = (function (_super) {
- __extends(RefractionPostProcess, _super);
- function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
- var _this = this;
- _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
- this.color = color;
- this.depth = depth;
- this.colorLevel = colorLevel;
- this.onActivate = function (cam) {
- _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
- };
- this.onApply = function (effect) {
- effect.setColor3("baseColor", _this.color);
- effect.setFloat("depth", _this.depth);
- effect.setFloat("colorLevel", _this.colorLevel);
- effect.setTexture("refractionSampler", _this._refRexture);
- };
- }
- // Methods
- RefractionPostProcess.prototype.dispose = function (camera) {
- if (this._refRexture) {
- this._refRexture.dispose();
- }
- _super.prototype.dispose.call(this, camera);
- };
- return RefractionPostProcess;
- })(BABYLON.PostProcess);
- BABYLON.RefractionPostProcess = RefractionPostProcess;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var BlackAndWhitePostProcess = (function (_super) {
- __extends(BlackAndWhitePostProcess, _super);
- function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
- _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
- }
- return BlackAndWhitePostProcess;
- })(BABYLON.PostProcess);
- BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var ConvolutionPostProcess = (function (_super) {
- __extends(ConvolutionPostProcess, _super);
- function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
- var _this = this;
- _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
- this.kernel = kernel;
- this.onApply = function (effect) {
- effect.setFloat2("screenSize", _this.width, _this.height);
- effect.setArray("kernel", _this.kernel);
- };
- }
- // Statics
- // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
- ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
- ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
- ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
- ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
- ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
- ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
- return ConvolutionPostProcess;
- })(BABYLON.PostProcess);
- BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var FilterPostProcess = (function (_super) {
- __extends(FilterPostProcess, _super);
- function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
- var _this = this;
- _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
- this.kernelMatrix = kernelMatrix;
- this.onApply = function (effect) {
- effect.setMatrix("kernelMatrix", _this.kernelMatrix);
- };
- }
- return FilterPostProcess;
- })(BABYLON.PostProcess);
- BABYLON.FilterPostProcess = FilterPostProcess;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var FxaaPostProcess = (function (_super) {
- __extends(FxaaPostProcess, _super);
- function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
- var _this = this;
- _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
- this.onSizeChanged = function () {
- _this.texelWidth = 1.0 / _this.width;
- _this.texelHeight = 1.0 / _this.height;
- };
- this.onApply = function (effect) {
- effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
- };
- }
- return FxaaPostProcess;
- })(BABYLON.PostProcess);
- BABYLON.FxaaPostProcess = FxaaPostProcess;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var StereoscopicInterlacePostProcess = (function (_super) {
- __extends(StereoscopicInterlacePostProcess, _super);
- function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
- var _this = this;
- _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
- this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
- this.onSizeChanged = function () {
- _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
- };
- this.onApply = function (effect) {
- effect.setTextureFromPostProcess("camASampler", postProcessA);
- effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
- };
- }
- return StereoscopicInterlacePostProcess;
- })(BABYLON.PostProcess);
- BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var LensFlare = (function () {
- function LensFlare(size, position, color, imgUrl, system) {
- this.size = size;
- this.position = position;
- this.dispose = function () {
- if (this.texture) {
- this.texture.dispose();
- }
- // Remove from scene
- var index = this._system.lensFlares.indexOf(this);
- this._system.lensFlares.splice(index, 1);
- };
- this.color = color || new BABYLON.Color3(1, 1, 1);
- this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
- this._system = system;
- system.lensFlares.push(this);
- }
- return LensFlare;
- })();
- BABYLON.LensFlare = LensFlare;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var LensFlareSystem = (function () {
- function LensFlareSystem(name, emitter, scene) {
- this.name = name;
- this.lensFlares = new Array();
- this.borderLimit = 300;
- this.layerMask = 0x0FFFFFFF;
- this._vertexDeclaration = [2];
- this._vertexStrideSize = 2 * 4;
- this._isEnabled = true;
- this._scene = scene;
- this._emitter = emitter;
- this.id = name;
- scene.lensFlareSystems.push(this);
- this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
- // VBO
- var vertices = [];
- vertices.push(1, 1);
- vertices.push(-1, 1);
- vertices.push(-1, -1);
- vertices.push(1, -1);
- this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
- // Indices
- var indices = [];
- indices.push(0);
- indices.push(1);
- indices.push(2);
- indices.push(0);
- indices.push(2);
- indices.push(3);
- this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
- // Effects
- this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
- }
- Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
- get: function () {
- return this._isEnabled;
- },
- set: function (value) {
- this._isEnabled = value;
- },
- enumerable: true,
- configurable: true
- });
- LensFlareSystem.prototype.getScene = function () {
- return this._scene;
- };
- LensFlareSystem.prototype.getEmitter = function () {
- return this._emitter;
- };
- LensFlareSystem.prototype.setEmitter = function (newEmitter) {
- this._emitter = newEmitter;
- };
- LensFlareSystem.prototype.getEmitterPosition = function () {
- return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
- };
- LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
- var position = this.getEmitterPosition();
- position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
- this._positionX = position.x;
- this._positionY = position.y;
- position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
- if (position.z > 0) {
- if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
- if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
- return true;
- }
- }
- return false;
- };
- LensFlareSystem.prototype._isVisible = function () {
- if (!this._isEnabled) {
- return false;
- }
- var emitterPosition = this.getEmitterPosition();
- var direction = emitterPosition.subtract(this._scene.activeCamera.position);
- var distance = direction.length();
- direction.normalize();
- var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
- var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
- return !pickInfo.hit || pickInfo.distance > distance;
- };
- LensFlareSystem.prototype.render = function () {
- if (!this._effect.isReady())
- return false;
- var engine = this._scene.getEngine();
- var viewport = this._scene.activeCamera.viewport;
- var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
- // Position
- if (!this.computeEffectivePosition(globalViewport)) {
- return false;
- }
- // Visibility
- if (!this._isVisible()) {
- return false;
- }
- // Intensity
- var awayX;
- var awayY;
- if (this._positionX < this.borderLimit + globalViewport.x) {
- awayX = this.borderLimit + globalViewport.x - this._positionX;
- }
- else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
- awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
- }
- else {
- awayX = 0;
- }
- if (this._positionY < this.borderLimit + globalViewport.y) {
- awayY = this.borderLimit + globalViewport.y - this._positionY;
- }
- else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
- awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
- }
- else {
- awayY = 0;
- }
- var away = (awayX > awayY) ? awayX : awayY;
- if (away > this.borderLimit) {
- away = this.borderLimit;
- }
- var intensity = 1.0 - (away / this.borderLimit);
- if (intensity < 0) {
- return false;
- }
- if (intensity > 1.0) {
- intensity = 1.0;
- }
- // Position
- var centerX = globalViewport.x + globalViewport.width / 2;
- var centerY = globalViewport.y + globalViewport.height / 2;
- var distX = centerX - this._positionX;
- var distY = centerY - this._positionY;
- // Effects
- engine.enableEffect(this._effect);
- engine.setState(false);
- engine.setDepthBuffer(false);
- engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
- // VBOs
- engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
- // Flares
- for (var index = 0; index < this.lensFlares.length; index++) {
- var flare = this.lensFlares[index];
- var x = centerX - (distX * flare.position);
- var y = centerY - (distY * flare.position);
- var cw = flare.size;
- var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
- var cx = 2 * (x / globalViewport.width) - 1.0;
- var cy = 1.0 - 2 * (y / globalViewport.height);
- var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
- this._effect.setMatrix("viewportMatrix", viewportMatrix);
- // Texture
- this._effect.setTexture("textureSampler", flare.texture);
- // Color
- this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
- // Draw order
- engine.draw(true, 0, 6);
- }
- engine.setDepthBuffer(true);
- engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
- return true;
- };
- LensFlareSystem.prototype.dispose = function () {
- if (this._vertexBuffer) {
- this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
- this._vertexBuffer = null;
- }
- if (this._indexBuffer) {
- this._scene.getEngine()._releaseBuffer(this._indexBuffer);
- this._indexBuffer = null;
- }
- while (this.lensFlares.length) {
- this.lensFlares[0].dispose();
- }
- // Remove from scene
- var index = this._scene.lensFlareSystems.indexOf(this);
- this._scene.lensFlareSystems.splice(index, 1);
- };
- LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
- var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
- var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
- var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
- lensFlareSystem.id = parsedLensFlareSystem.id || name;
- lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
- for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
- var parsedFlare = parsedLensFlareSystem.flares[index];
- var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
- }
- return lensFlareSystem;
- };
- LensFlareSystem.prototype.serialize = function () {
- var serializationObject = {};
- serializationObject.id = this.id;
- serializationObject.name = this.name;
- serializationObject.emitterId = this.getEmitter().id;
- serializationObject.borderLimit = this.borderLimit;
- serializationObject.flares = [];
- for (var index = 0; index < this.lensFlares.length; index++) {
- var flare = this.lensFlares[index];
- serializationObject.flares.push({
- size: flare.size,
- position: flare.position,
- color: flare.color.asArray(),
- textureName: BABYLON.Tools.GetFilename(flare.texture.name)
- });
- }
- return serializationObject;
- };
- return LensFlareSystem;
- })();
- BABYLON.LensFlareSystem = LensFlareSystem;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- // We're mainly based on the logic defined into the FreeCamera code
- var DeviceOrientationCamera = (function (_super) {
- __extends(DeviceOrientationCamera, _super);
- //-- end properties for backward compatibility for inputs
- function DeviceOrientationCamera(name, position, scene) {
- _super.call(this, name, position, scene);
- this.inputs.addDeviceOrientation();
- }
- Object.defineProperty(DeviceOrientationCamera.prototype, "angularSensibility", {
- //-- Begin properties for backward compatibility for inputs
- get: function () {
- var gamepad = this.inputs.attached["deviceOrientation"];
- if (gamepad)
- return gamepad.angularSensibility;
- },
- set: function (value) {
- var gamepad = this.inputs.attached["deviceOrientation"];
- if (gamepad)
- gamepad.angularSensibility = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(DeviceOrientationCamera.prototype, "moveSensibility", {
- get: function () {
- var gamepad = this.inputs.attached["deviceOrientation"];
- if (gamepad)
- return gamepad.moveSensibility;
- },
- set: function (value) {
- var gamepad = this.inputs.attached["deviceOrientation"];
- if (gamepad)
- gamepad.moveSensibility = value;
- },
- enumerable: true,
- configurable: true
- });
- DeviceOrientationCamera.prototype.getTypeName = function () {
- return "DeviceOrientationCamera";
- };
- return DeviceOrientationCamera;
- })(BABYLON.FreeCamera);
- BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- // We're mainly based on the logic defined into the FreeCamera code
- var UniversalCamera = (function (_super) {
- __extends(UniversalCamera, _super);
- //-- end properties for backward compatibility for inputs
- function UniversalCamera(name, position, scene) {
- _super.call(this, name, position, scene);
- this.inputs.addGamepad();
- }
- Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
- //-- Begin properties for backward compatibility for inputs
- get: function () {
- var gamepad = this.inputs.attached["gamepad"];
- if (gamepad)
- return gamepad.gamepadAngularSensibility;
- },
- set: function (value) {
- var gamepad = this.inputs.attached["gamepad"];
- if (gamepad)
- gamepad.gamepadAngularSensibility = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
- get: function () {
- var gamepad = this.inputs.attached["gamepad"];
- if (gamepad)
- return gamepad.gamepadMoveSensibility;
- },
- set: function (value) {
- var gamepad = this.inputs.attached["gamepad"];
- if (gamepad)
- gamepad.gamepadMoveSensibility = value;
- },
- enumerable: true,
- configurable: true
- });
- UniversalCamera.prototype.getTypeName = function () {
- return "UniversalCamera";
- };
- return UniversalCamera;
- })(BABYLON.TouchCamera);
- BABYLON.UniversalCamera = UniversalCamera;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Gamepads = (function () {
- function Gamepads(ongamedpadconnected) {
- var _this = this;
- this.babylonGamepads = [];
- this.oneGamepadConnected = false;
- this.isMonitoring = false;
- this.gamepadEventSupported = 'GamepadEvent' in window;
- this.gamepadSupportAvailable = (navigator.getGamepads ||
- !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
- this._callbackGamepadConnected = ongamedpadconnected;
- if (this.gamepadSupportAvailable) {
- // Checking if the gamepad connected event is supported (like in Firefox)
- if (this.gamepadEventSupported) {
- this._onGamepadConnectedEvent = function (evt) {
- _this._onGamepadConnected(evt);
- };
- this._onGamepadDisonnectedEvent = function (evt) {
- _this._onGamepadDisconnected(evt);
- };
- window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
- window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
- }
- else {
- this._startMonitoringGamepads();
- }
- }
- }
- Gamepads.prototype.dispose = function () {
- if (Gamepads.gamepadDOMInfo) {
- document.body.removeChild(Gamepads.gamepadDOMInfo);
- }
- if (this._onGamepadConnectedEvent) {
- window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
- window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
- this._onGamepadConnectedEvent = null;
- this._onGamepadDisonnectedEvent = null;
- }
- };
- Gamepads.prototype._onGamepadConnected = function (evt) {
- var newGamepad = this._addNewGamepad(evt.gamepad);
- if (this._callbackGamepadConnected)
- this._callbackGamepadConnected(newGamepad);
- this._startMonitoringGamepads();
- };
- Gamepads.prototype._addNewGamepad = function (gamepad) {
- if (!this.oneGamepadConnected) {
- this.oneGamepadConnected = true;
- if (Gamepads.gamepadDOMInfo) {
- document.body.removeChild(Gamepads.gamepadDOMInfo);
- Gamepads.gamepadDOMInfo = null;
- }
- }
- var newGamepad;
- if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
- newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
- }
- else {
- newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
- }
- this.babylonGamepads.push(newGamepad);
- return newGamepad;
- };
- Gamepads.prototype._onGamepadDisconnected = function (evt) {
- // Remove the gamepad from the list of gamepads to monitor.
- for (var i in this.babylonGamepads) {
- if (this.babylonGamepads[i].index == evt.gamepad.index) {
- this.babylonGamepads.splice(+i, 1);
- break;
- }
- }
- // If no gamepads are left, stop the polling loop.
- if (this.babylonGamepads.length == 0) {
- this._stopMonitoringGamepads();
- }
- };
- Gamepads.prototype._startMonitoringGamepads = function () {
- if (!this.isMonitoring) {
- this.isMonitoring = true;
- this._checkGamepadsStatus();
- }
- };
- Gamepads.prototype._stopMonitoringGamepads = function () {
- this.isMonitoring = false;
- };
- Gamepads.prototype._checkGamepadsStatus = function () {
- var _this = this;
- // updating gamepad objects
- this._updateGamepadObjects();
- for (var i in this.babylonGamepads) {
- this.babylonGamepads[i].update();
- }
- if (this.isMonitoring) {
- if (window.requestAnimationFrame) {
- window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
- }
- else if (window.mozRequestAnimationFrame) {
- window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
- }
- else if (window.webkitRequestAnimationFrame) {
- window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
- }
- }
- };
- // This function is called only on Chrome, which does not yet support
- // connection/disconnection events, but requires you to monitor
- // an array for changes.
- Gamepads.prototype._updateGamepadObjects = function () {
- var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
- for (var i = 0; i < gamepads.length; i++) {
- if (gamepads[i]) {
- if (!(gamepads[i].index in this.babylonGamepads)) {
- var newGamepad = this._addNewGamepad(gamepads[i]);
- if (this._callbackGamepadConnected) {
- this._callbackGamepadConnected(newGamepad);
- }
- }
- else {
- this.babylonGamepads[i].browserGamepad = gamepads[i];
- }
- }
- }
- };
- return Gamepads;
- })();
- BABYLON.Gamepads = Gamepads;
- var StickValues = (function () {
- function StickValues(x, y) {
- this.x = x;
- this.y = y;
- }
- return StickValues;
- })();
- BABYLON.StickValues = StickValues;
- var Gamepad = (function () {
- function Gamepad(id, index, browserGamepad) {
- this.id = id;
- this.index = index;
- this.browserGamepad = browserGamepad;
- if (this.browserGamepad.axes.length >= 2) {
- this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
- }
- if (this.browserGamepad.axes.length >= 4) {
- this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
- }
- }
- Gamepad.prototype.onleftstickchanged = function (callback) {
- this._onleftstickchanged = callback;
- };
- Gamepad.prototype.onrightstickchanged = function (callback) {
- this._onrightstickchanged = callback;
- };
- Object.defineProperty(Gamepad.prototype, "leftStick", {
- get: function () {
- return this._leftStick;
- },
- set: function (newValues) {
- if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
- this._onleftstickchanged(newValues);
- }
- this._leftStick = newValues;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Gamepad.prototype, "rightStick", {
- get: function () {
- return this._rightStick;
- },
- set: function (newValues) {
- if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
- this._onrightstickchanged(newValues);
- }
- this._rightStick = newValues;
- },
- enumerable: true,
- configurable: true
- });
- Gamepad.prototype.update = function () {
- if (this._leftStick) {
- this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
- }
- if (this._rightStick) {
- this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
- }
- };
- return Gamepad;
- })();
- BABYLON.Gamepad = Gamepad;
- var GenericPad = (function (_super) {
- __extends(GenericPad, _super);
- function GenericPad(id, index, gamepad) {
- _super.call(this, id, index, gamepad);
- this.id = id;
- this.index = index;
- this.gamepad = gamepad;
- this._buttons = new Array(gamepad.buttons.length);
- }
- GenericPad.prototype.onbuttondown = function (callback) {
- this._onbuttondown = callback;
- };
- GenericPad.prototype.onbuttonup = function (callback) {
- this._onbuttonup = callback;
- };
- GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
- if (newValue !== currentValue) {
- if (this._onbuttondown && newValue === 1) {
- this._onbuttondown(buttonIndex);
- }
- if (this._onbuttonup && newValue === 0) {
- this._onbuttonup(buttonIndex);
- }
- }
- return newValue;
- };
- GenericPad.prototype.update = function () {
- _super.prototype.update.call(this);
- for (var index = 0; index < this._buttons.length; index++) {
- this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
- }
- };
- return GenericPad;
- })(Gamepad);
- BABYLON.GenericPad = GenericPad;
- (function (Xbox360Button) {
- Xbox360Button[Xbox360Button["A"] = 0] = "A";
- Xbox360Button[Xbox360Button["B"] = 1] = "B";
- Xbox360Button[Xbox360Button["X"] = 2] = "X";
- Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
- Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
- Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
- Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
- Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
- Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
- Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
- })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
- var Xbox360Button = BABYLON.Xbox360Button;
- (function (Xbox360Dpad) {
- Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
- Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
- Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
- Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
- })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
- var Xbox360Dpad = BABYLON.Xbox360Dpad;
- var Xbox360Pad = (function (_super) {
- __extends(Xbox360Pad, _super);
- function Xbox360Pad() {
- _super.apply(this, arguments);
- this._leftTrigger = 0;
- this._rightTrigger = 0;
- this._buttonA = 0;
- this._buttonB = 0;
- this._buttonX = 0;
- this._buttonY = 0;
- this._buttonBack = 0;
- this._buttonStart = 0;
- this._buttonLB = 0;
- this._buttonRB = 0;
- this._buttonLeftStick = 0;
- this._buttonRightStick = 0;
- this._dPadUp = 0;
- this._dPadDown = 0;
- this._dPadLeft = 0;
- this._dPadRight = 0;
- }
- Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
- this._onlefttriggerchanged = callback;
- };
- Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
- this._onrighttriggerchanged = callback;
- };
- Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
- get: function () {
- return this._leftTrigger;
- },
- set: function (newValue) {
- if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
- this._onlefttriggerchanged(newValue);
- }
- this._leftTrigger = newValue;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
- get: function () {
- return this._rightTrigger;
- },
- set: function (newValue) {
- if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
- this._onrighttriggerchanged(newValue);
- }
- this._rightTrigger = newValue;
- },
- enumerable: true,
- configurable: true
- });
- Xbox360Pad.prototype.onbuttondown = function (callback) {
- this._onbuttondown = callback;
- };
- Xbox360Pad.prototype.onbuttonup = function (callback) {
- this._onbuttonup = callback;
- };
- Xbox360Pad.prototype.ondpaddown = function (callback) {
- this._ondpaddown = callback;
- };
- Xbox360Pad.prototype.ondpadup = function (callback) {
- this._ondpadup = callback;
- };
- Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
- if (newValue !== currentValue) {
- if (this._onbuttondown && newValue === 1) {
- this._onbuttondown(buttonType);
- }
- if (this._onbuttonup && newValue === 0) {
- this._onbuttonup(buttonType);
- }
- }
- return newValue;
- };
- Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
- if (newValue !== currentValue) {
- if (this._ondpaddown && newValue === 1) {
- this._ondpaddown(buttonType);
- }
- if (this._ondpadup && newValue === 0) {
- this._ondpadup(buttonType);
- }
- }
- return newValue;
- };
- Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
- get: function () {
- return this._buttonA;
- },
- set: function (value) {
- this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
- get: function () {
- return this._buttonB;
- },
- set: function (value) {
- this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
- get: function () {
- return this._buttonX;
- },
- set: function (value) {
- this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
- get: function () {
- return this._buttonY;
- },
- set: function (value) {
- this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
- get: function () {
- return this._buttonStart;
- },
- set: function (value) {
- this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
- get: function () {
- return this._buttonBack;
- },
- set: function (value) {
- this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
- get: function () {
- return this._buttonLB;
- },
- set: function (value) {
- this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
- get: function () {
- return this._buttonRB;
- },
- set: function (value) {
- this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
- get: function () {
- return this._buttonLeftStick;
- },
- set: function (value) {
- this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
- get: function () {
- return this._buttonRightStick;
- },
- set: function (value) {
- this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
- get: function () {
- return this._dPadUp;
- },
- set: function (value) {
- this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
- get: function () {
- return this._dPadDown;
- },
- set: function (value) {
- this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
- get: function () {
- return this._dPadLeft;
- },
- set: function (value) {
- this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
- get: function () {
- return this._dPadRight;
- },
- set: function (value) {
- this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
- },
- enumerable: true,
- configurable: true
- });
- Xbox360Pad.prototype.update = function () {
- _super.prototype.update.call(this);
- this.buttonA = this.browserGamepad.buttons[0].value;
- this.buttonB = this.browserGamepad.buttons[1].value;
- this.buttonX = this.browserGamepad.buttons[2].value;
- this.buttonY = this.browserGamepad.buttons[3].value;
- this.buttonLB = this.browserGamepad.buttons[4].value;
- this.buttonRB = this.browserGamepad.buttons[5].value;
- this.leftTrigger = this.browserGamepad.buttons[6].value;
- this.rightTrigger = this.browserGamepad.buttons[7].value;
- this.buttonBack = this.browserGamepad.buttons[8].value;
- this.buttonStart = this.browserGamepad.buttons[9].value;
- this.buttonLeftStick = this.browserGamepad.buttons[10].value;
- this.buttonRightStick = this.browserGamepad.buttons[11].value;
- this.dPadUp = this.browserGamepad.buttons[12].value;
- this.dPadDown = this.browserGamepad.buttons[13].value;
- this.dPadLeft = this.browserGamepad.buttons[14].value;
- this.dPadRight = this.browserGamepad.buttons[15].value;
- };
- return Xbox360Pad;
- })(Gamepad);
- BABYLON.Xbox360Pad = Xbox360Pad;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- // We're mainly based on the logic defined into the FreeCamera code
- var GamepadCamera = (function (_super) {
- __extends(GamepadCamera, _super);
- //-- end properties for backward compatibility for inputs
- function GamepadCamera(name, position, scene) {
- BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
- _super.call(this, name, position, scene);
- }
- Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
- //-- Begin properties for backward compatibility for inputs
- get: function () {
- var gamepad = this.inputs.attached["gamepad"];
- if (gamepad)
- return gamepad.gamepadAngularSensibility;
- },
- set: function (value) {
- var gamepad = this.inputs.attached["gamepad"];
- if (gamepad)
- gamepad.gamepadAngularSensibility = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
- get: function () {
- var gamepad = this.inputs.attached["gamepad"];
- if (gamepad)
- return gamepad.gamepadMoveSensibility;
- },
- set: function (value) {
- var gamepad = this.inputs.attached["gamepad"];
- if (gamepad)
- gamepad.gamepadMoveSensibility = value;
- },
- enumerable: true,
- configurable: true
- });
- GamepadCamera.prototype.getTypeName = function () {
- return "GamepadCamera";
- };
- return GamepadCamera;
- })(BABYLON.UniversalCamera);
- BABYLON.GamepadCamera = GamepadCamera;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Analyser = (function () {
- function Analyser(scene) {
- this.SMOOTHING = 0.75;
- this.FFT_SIZE = 512;
- this.BARGRAPHAMPLITUDE = 256;
- this.DEBUGCANVASPOS = { x: 20, y: 20 };
- this.DEBUGCANVASSIZE = { width: 320, height: 200 };
- this._scene = scene;
- this._audioEngine = BABYLON.Engine.audioEngine;
- if (this._audioEngine.canUseWebAudio) {
- this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
- this._webAudioAnalyser.minDecibels = -140;
- this._webAudioAnalyser.maxDecibels = 0;
- this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
- this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
- this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
- }
- }
- Analyser.prototype.getFrequencyBinCount = function () {
- if (this._audioEngine.canUseWebAudio) {
- return this._webAudioAnalyser.frequencyBinCount;
- }
- else {
- return 0;
- }
- };
- Analyser.prototype.getByteFrequencyData = function () {
- if (this._audioEngine.canUseWebAudio) {
- this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
- this._webAudioAnalyser.fftSize = this.FFT_SIZE;
- this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
- }
- return this._byteFreqs;
- };
- Analyser.prototype.getByteTimeDomainData = function () {
- if (this._audioEngine.canUseWebAudio) {
- this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
- this._webAudioAnalyser.fftSize = this.FFT_SIZE;
- this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
- }
- return this._byteTime;
- };
- Analyser.prototype.getFloatFrequencyData = function () {
- if (this._audioEngine.canUseWebAudio) {
- this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
- this._webAudioAnalyser.fftSize = this.FFT_SIZE;
- this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
- }
- return this._floatFreqs;
- };
- Analyser.prototype.drawDebugCanvas = function () {
- var _this = this;
- if (this._audioEngine.canUseWebAudio) {
- if (!this._debugCanvas) {
- this._debugCanvas = document.createElement("canvas");
- this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
- this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
- this._debugCanvas.style.position = "absolute";
- this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
- this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
- this._debugCanvasContext = this._debugCanvas.getContext("2d");
- document.body.appendChild(this._debugCanvas);
- this._registerFunc = function () {
- _this.drawDebugCanvas();
- };
- this._scene.registerBeforeRender(this._registerFunc);
- }
- if (this._registerFunc) {
- var workingArray = this.getByteFrequencyData();
- this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
- this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
- // Draw the frequency domain chart.
- for (var i = 0; i < this.getFrequencyBinCount(); i++) {
- var value = workingArray[i];
- var percent = value / this.BARGRAPHAMPLITUDE;
- var height = this.DEBUGCANVASSIZE.height * percent;
- var offset = this.DEBUGCANVASSIZE.height - height - 1;
- var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
- var hue = i / this.getFrequencyBinCount() * 360;
- this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
- this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
- }
- }
- }
- };
- Analyser.prototype.stopDebugCanvas = function () {
- if (this._debugCanvas) {
- this._scene.unregisterBeforeRender(this._registerFunc);
- this._registerFunc = null;
- document.body.removeChild(this._debugCanvas);
- this._debugCanvas = null;
- this._debugCanvasContext = null;
- }
- };
- Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
- if (this._audioEngine.canUseWebAudio) {
- inputAudioNode.connect(this._webAudioAnalyser);
- this._webAudioAnalyser.connect(outputAudioNode);
- }
- };
- Analyser.prototype.dispose = function () {
- if (this._audioEngine.canUseWebAudio) {
- this._webAudioAnalyser.disconnect();
- }
- };
- return Analyser;
- })();
- BABYLON.Analyser = Analyser;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var DepthRenderer = (function () {
- function DepthRenderer(scene, type) {
- var _this = this;
- if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
- this._viewMatrix = BABYLON.Matrix.Zero();
- this._projectionMatrix = BABYLON.Matrix.Zero();
- this._transformMatrix = BABYLON.Matrix.Zero();
- this._worldViewProjection = BABYLON.Matrix.Zero();
- this._scene = scene;
- var engine = scene.getEngine();
- // Render target
- this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
- this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
- this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
- this._depthMap.refreshRate = 1;
- this._depthMap.renderParticles = false;
- this._depthMap.renderList = null;
- // set default depth value to 1.0 (far away)
- this._depthMap.onClear = function (engine) {
- engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
- };
- // Custom render function
- var renderSubMesh = function (subMesh) {
- var mesh = subMesh.getRenderingMesh();
- var scene = _this._scene;
- var engine = scene.getEngine();
- // Culling
- engine.setState(subMesh.getMaterial().backFaceCulling);
- // Managing instances
- var batch = mesh._getInstancesRenderList(subMesh._id);
- if (batch.mustReturn) {
- return;
- }
- var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
- if (_this.isReady(subMesh, hardwareInstancedRendering)) {
- engine.enableEffect(_this._effect);
- mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
- var material = subMesh.getMaterial();
- _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
- _this._effect.setFloat("far", scene.activeCamera.maxZ);
- // Alpha test
- if (material && material.needAlphaTesting()) {
- var alphaTexture = material.getAlphaTestTexture();
- _this._effect.setTexture("diffuseSampler", alphaTexture);
- _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
- }
- // Bones
- if (mesh.useBones && mesh.computeBonesUsingShaders) {
- _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
- }
- // Draw
- mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
- }
- };
- this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
- var index;
- for (index = 0; index < opaqueSubMeshes.length; index++) {
- renderSubMesh(opaqueSubMeshes.data[index]);
- }
- for (index = 0; index < alphaTestSubMeshes.length; index++) {
- renderSubMesh(alphaTestSubMeshes.data[index]);
- }
- };
- }
- DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
- var material = subMesh.getMaterial();
- if (material.disableDepthWrite) {
- return false;
- }
- var defines = [];
- var attribs = [BABYLON.VertexBuffer.PositionKind];
- var mesh = subMesh.getMesh();
- var scene = mesh.getScene();
- // Alpha test
- if (material && material.needAlphaTesting()) {
- defines.push("#define ALPHATEST");
- if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
- attribs.push(BABYLON.VertexBuffer.UVKind);
- defines.push("#define UV1");
- }
- if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
- attribs.push(BABYLON.VertexBuffer.UV2Kind);
- defines.push("#define UV2");
- }
- }
- // Bones
- if (mesh.useBones && mesh.computeBonesUsingShaders) {
- attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
- attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
- if (mesh.numBoneInfluencers > 4) {
- attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
- attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
- }
- defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
- defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
- }
- else {
- defines.push("#define NUM_BONE_INFLUENCERS 0");
- }
- // Instances
- if (useInstances) {
- defines.push("#define INSTANCES");
- attribs.push("world0");
- attribs.push("world1");
- attribs.push("world2");
- attribs.push("world3");
- }
- // Get correct effect
- var join = defines.join("\n");
- if (this._cachedDefines !== join) {
- this._cachedDefines = join;
- this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
- }
- return this._effect.isReady();
- };
- DepthRenderer.prototype.getDepthMap = function () {
- return this._depthMap;
- };
- // Methods
- DepthRenderer.prototype.dispose = function () {
- this._depthMap.dispose();
- };
- return DepthRenderer;
- })();
- BABYLON.DepthRenderer = DepthRenderer;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var SSAORenderingPipeline = (function (_super) {
- __extends(SSAORenderingPipeline, _super);
- /**
- * @constructor
- * @param {string} name - The rendering pipeline name
- * @param {BABYLON.Scene} scene - The scene linked to this pipeline
- * @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 }
- * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
- */
- function SSAORenderingPipeline(name, scene, ratio, cameras) {
- var _this = this;
- _super.call(this, scene.getEngine(), name);
- // Members
- /**
- * The PassPostProcess id in the pipeline that contains the original scene color
- * @type {string}
- */
- this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
- /**
- * The SSAO PostProcess id in the pipeline
- * @type {string}
- */
- this.SSAORenderEffect = "SSAORenderEffect";
- /**
- * The horizontal blur PostProcess id in the pipeline
- * @type {string}
- */
- this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
- /**
- * The vertical blur PostProcess id in the pipeline
- * @type {string}
- */
- this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
- /**
- * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
- * @type {string}
- */
- this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
- /**
- * The output strength of the SSAO post-process. Default value is 1.0.
- * @type {number}
- */
- this.totalStrength = 1.0;
- /**
- * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
- * @type {number}
- */
- this.radius = 0.0001;
- /**
- * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
- * Must not be equal to fallOff and superior to fallOff.
- * Default value is 0.975
- * @type {number}
- */
- this.area = 0.0075;
- /**
- * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
- * Must not be equal to area and inferior to area.
- * Default value is 0.0
- * @type {number}
- */
- this.fallOff = 0.000001;
- /**
- * The base color of the SSAO post-process
- * The final result is "base + ssao" between [0, 1]
- * @type {number}
- */
- this.base = 0.5;
- this._firstUpdate = true;
- this._scene = scene;
- // Set up assets
- this._createRandomTexture();
- this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
- var ssaoRatio = ratio.ssaoRatio || ratio;
- var combineRatio = ratio.combineRatio || ratio;
- this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
- this._createSSAOPostProcess(ssaoRatio);
- this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
- this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
- this._createSSAOCombinePostProcess(combineRatio);
- // Set up pipeline
- this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
- this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
- this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
- this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
- this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
- // Finish
- scene.postProcessRenderPipelineManager.addPipeline(this);
- if (cameras)
- scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
- }
- // Public Methods
- /**
- * Returns the horizontal blur PostProcess
- * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
- */
- SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
- return this._blurHPostProcess;
- };
- /**
- * Returns the vertical blur PostProcess
- * @return {BABYLON.BlurPostProcess} The vertical blur post-process
- */
- SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
- return this._blurVPostProcess;
- };
- /**
- * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
- */
- SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
- if (disableDepthRender === void 0) { disableDepthRender = false; }
- this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
- this._originalColorPostProcess = undefined;
- this._ssaoPostProcess = undefined;
- this._blurHPostProcess = undefined;
- this._blurVPostProcess = undefined;
- this._ssaoCombinePostProcess = undefined;
- this._randomTexture.dispose();
- if (disableDepthRender)
- this._scene.disableDepthRenderer();
- };
- // Private Methods
- SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
- var _this = this;
- var numSamples = 16;
- var sampleSphere = [
- 0.5381, 0.1856, -0.4319,
- 0.1379, 0.2486, 0.4430,
- 0.3371, 0.5679, -0.0057,
- -0.6999, -0.0451, -0.0019,
- 0.0689, -0.1598, -0.8547,
- 0.0560, 0.0069, -0.1843,
- -0.0146, 0.1402, 0.0762,
- 0.0100, -0.1924, -0.0344,
- -0.3577, -0.5301, -0.4358,
- -0.3169, 0.1063, 0.0158,
- 0.0103, -0.5869, 0.0046,
- -0.0897, -0.4940, 0.3287,
- 0.7119, -0.0154, -0.0918,
- -0.0533, 0.0596, -0.5411,
- 0.0352, -0.0631, 0.5460,
- -0.4776, 0.2847, -0.0271
- ];
- var samplesFactor = 1.0 / numSamples;
- this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
- "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
- "area", "fallOff", "base"
- ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
- this._ssaoPostProcess.onApply = function (effect) {
- if (_this._firstUpdate) {
- effect.setArray3("sampleSphere", sampleSphere);
- effect.setFloat("samplesFactor", samplesFactor);
- effect.setFloat("randTextureTiles", 4.0);
- _this._firstUpdate = false;
- }
- effect.setFloat("totalStrength", _this.totalStrength);
- effect.setFloat("radius", _this.radius);
- effect.setFloat("area", _this.area);
- effect.setFloat("fallOff", _this.fallOff);
- effect.setFloat("base", _this.base);
- effect.setTexture("textureSampler", _this._depthTexture);
- effect.setTexture("randomSampler", _this._randomTexture);
- };
- };
- SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
- var _this = this;
- this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
- this._ssaoCombinePostProcess.onApply = function (effect) {
- effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
- };
- };
- SSAORenderingPipeline.prototype._createRandomTexture = function () {
- var size = 512;
- this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
- this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
- this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
- var context = this._randomTexture.getContext();
- var rand = function (min, max) {
- return Math.random() * (max - min) + min;
- };
- var randVector = BABYLON.Vector3.Zero();
- for (var x = 0; x < size; x++) {
- for (var y = 0; y < size; y++) {
- randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
- randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
- randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
- context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
- context.fillRect(x, y, 1, 1);
- }
- }
- this._randomTexture.update(false);
- };
- return SSAORenderingPipeline;
- })(BABYLON.PostProcessRenderPipeline);
- BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
- var VolumetricLightScatteringPostProcess = (function (_super) {
- __extends(VolumetricLightScatteringPostProcess, _super);
- /**
- * @constructor
- * @param {string} name - The post-process name
- * @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)
- * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
- * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
- * @param {number} samples - The post-process quality, default 100
- * @param {number} samplingMode - The post-process filtering mode
- * @param {BABYLON.Engine} engine - The babylon engine
- * @param {boolean} reusable - If the post-process is reusable
- * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
- */
- function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
- var _this = this;
- if (samples === void 0) { samples = 100; }
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
- _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
- this._screenCoordinates = BABYLON.Vector2.Zero();
- /**
- * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
- * @type {Vector3}
- */
- this.customMeshPosition = BABYLON.Vector3.Zero();
- /**
- * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
- * @type {boolean}
- */
- this.useCustomMeshPosition = false;
- /**
- * If the post-process should inverse the light scattering direction
- * @type {boolean}
- */
- this.invert = true;
- /**
- * Array containing the excluded meshes not rendered in the internal pass
- */
- this.excludedMeshes = new Array();
- /**
- * Controls the overall intensity of the post-process
- * @type {number}
- */
- this.exposure = 0.3;
- /**
- * Dissipates each sample's contribution in range [0, 1]
- * @type {number}
- */
- this.decay = 0.96815;
- /**
- * Controls the overall intensity of each sample
- * @type {number}
- */
- this.weight = 0.58767;
- /**
- * Controls the density of each sample
- * @type {number}
- */
- this.density = 0.926;
- scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
- var engine = scene.getEngine();
- this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
- // Configure mesh
- this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
- // Configure
- this._createPass(scene, ratio.passRatio || ratio);
- this.onActivate = function (camera) {
- if (!_this.isSupported) {
- _this.dispose(camera);
- }
- _this.onActivate = null;
- };
- this.onApply = function (effect) {
- _this._updateMeshScreenCoordinates(scene);
- effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
- effect.setFloat("exposure", _this.exposure);
- effect.setFloat("decay", _this.decay);
- effect.setFloat("weight", _this.weight);
- effect.setFloat("density", _this.density);
- effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
- };
- }
- Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
- get: function () {
- BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
- return false;
- },
- set: function (useDiffuseColor) {
- BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
- },
- enumerable: true,
- configurable: true
- });
- VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
- var mesh = subMesh.getMesh();
- // Render this.mesh as default
- if (mesh === this.mesh) {
- return mesh.material.isReady(mesh);
- }
- var defines = [];
- var attribs = [BABYLON.VertexBuffer.PositionKind];
- var material = subMesh.getMaterial();
- var needUV = false;
- // Alpha test
- if (material) {
- if (material.needAlphaTesting()) {
- defines.push("#define ALPHATEST");
- }
- if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
- attribs.push(BABYLON.VertexBuffer.UVKind);
- defines.push("#define UV1");
- }
- if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
- attribs.push(BABYLON.VertexBuffer.UV2Kind);
- defines.push("#define UV2");
- }
- }
- // Bones
- if (mesh.useBones && mesh.computeBonesUsingShaders) {
- attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
- attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
- defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
- defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
- }
- else {
- defines.push("#define NUM_BONE_INFLUENCERS 0");
- }
- // Instances
- if (useInstances) {
- defines.push("#define INSTANCES");
- attribs.push("world0");
- attribs.push("world1");
- attribs.push("world2");
- attribs.push("world3");
- }
- // Get correct effect
- var join = defines.join("\n");
- if (this._cachedDefines !== join) {
- this._cachedDefines = join;
- this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
- }
- return this._volumetricLightScatteringPass.isReady();
- };
- /**
- * Sets the new light position for light scattering effect
- * @param {BABYLON.Vector3} The new custom light position
- */
- VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
- this.customMeshPosition = position;
- };
- /**
- * Returns the light position for light scattering effect
- * @return {BABYLON.Vector3} The custom light position
- */
- VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
- return this.customMeshPosition;
- };
- /**
- * Disposes the internal assets and detaches the post-process from the camera
- */
- VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
- var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
- if (rttIndex !== -1) {
- camera.getScene().customRenderTargets.splice(rttIndex, 1);
- }
- this._volumetricLightScatteringRTT.dispose();
- _super.prototype.dispose.call(this, camera);
- };
- /**
- * Returns the render target texture used by the post-process
- * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
- */
- VolumetricLightScatteringPostProcess.prototype.getPass = function () {
- return this._volumetricLightScatteringRTT;
- };
- // Private methods
- VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
- if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
- return true;
- }
- return false;
- };
- VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
- var _this = this;
- var engine = scene.getEngine();
- this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
- this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
- this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
- this._volumetricLightScatteringRTT.renderList = null;
- this._volumetricLightScatteringRTT.renderParticles = false;
- scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
- // Custom render function for submeshes
- var renderSubMesh = function (subMesh) {
- var mesh = subMesh.getRenderingMesh();
- if (_this._meshExcluded(mesh)) {
- return;
- }
- var scene = mesh.getScene();
- var engine = scene.getEngine();
- // Culling
- engine.setState(subMesh.getMaterial().backFaceCulling);
- // Managing instances
- var batch = mesh._getInstancesRenderList(subMesh._id);
- if (batch.mustReturn) {
- return;
- }
- var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
- if (_this.isReady(subMesh, hardwareInstancedRendering)) {
- var effect = _this._volumetricLightScatteringPass;
- if (mesh === _this.mesh) {
- effect = subMesh.getMaterial().getEffect();
- }
- engine.enableEffect(effect);
- mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
- if (mesh === _this.mesh) {
- subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
- }
- else {
- var material = subMesh.getMaterial();
- _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
- // Alpha test
- if (material && material.needAlphaTesting()) {
- var alphaTexture = material.getAlphaTestTexture();
- _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
- if (alphaTexture) {
- _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
- }
- }
- // Bones
- if (mesh.useBones && mesh.computeBonesUsingShaders) {
- _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
- }
- }
- // Draw
- mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
- }
- };
- // Render target texture callbacks
- var savedSceneClearColor;
- var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
- this._volumetricLightScatteringRTT.onBeforeRender = function () {
- savedSceneClearColor = scene.clearColor;
- scene.clearColor = sceneClearColor;
- };
- this._volumetricLightScatteringRTT.onAfterRender = function () {
- scene.clearColor = savedSceneClearColor;
- };
- this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
- var engine = scene.getEngine();
- var index;
- for (index = 0; index < opaqueSubMeshes.length; index++) {
- renderSubMesh(opaqueSubMeshes.data[index]);
- }
- engine.setAlphaTesting(true);
- for (index = 0; index < alphaTestSubMeshes.length; index++) {
- renderSubMesh(alphaTestSubMeshes.data[index]);
- }
- engine.setAlphaTesting(false);
- if (transparentSubMeshes.length) {
- // Sort sub meshes
- for (index = 0; index < transparentSubMeshes.length; index++) {
- var submesh = transparentSubMeshes.data[index];
- submesh._alphaIndex = submesh.getMesh().alphaIndex;
- submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
- }
- var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
- sortedArray.sort(function (a, b) {
- // Alpha index first
- if (a._alphaIndex > b._alphaIndex) {
- return 1;
- }
- if (a._alphaIndex < b._alphaIndex) {
- return -1;
- }
- // Then distance to camera
- if (a._distanceToCamera < b._distanceToCamera) {
- return 1;
- }
- if (a._distanceToCamera > b._distanceToCamera) {
- return -1;
- }
- return 0;
- });
- // Render sub meshes
- engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
- for (index = 0; index < sortedArray.length; index++) {
- renderSubMesh(sortedArray[index]);
- }
- engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
- }
- };
- };
- VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
- var transform = scene.getTransformMatrix();
- var meshPosition;
- if (this.useCustomMeshPosition) {
- meshPosition = this.customMeshPosition;
- }
- else if (this.attachedNode) {
- meshPosition = this.attachedNode.position;
- }
- else {
- meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
- }
- var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
- this._screenCoordinates.x = pos.x / this._viewPort.width;
- this._screenCoordinates.y = pos.y / this._viewPort.height;
- if (this.invert)
- this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
- };
- // Static methods
- /**
- * Creates a default mesh for the Volumeric Light Scattering post-process
- * @param {string} The mesh name
- * @param {BABYLON.Scene} The scene where to create the mesh
- * @return {BABYLON.Mesh} the default mesh
- */
- VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
- var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
- mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
- var material = new BABYLON.StandardMaterial(name + "Material", scene);
- material.emissiveColor = new BABYLON.Color3(1, 1, 1);
- mesh.material = material;
- return mesh;
- };
- __decorate([
- BABYLON.serializeAsVector3()
- ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
- __decorate([
- BABYLON.serialize()
- ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
- __decorate([
- BABYLON.serialize()
- ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
- __decorate([
- BABYLON.serializeAsMeshReference()
- ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
- __decorate([
- BABYLON.serialize()
- ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
- __decorate([
- BABYLON.serialize()
- ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
- __decorate([
- BABYLON.serialize()
- ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
- __decorate([
- BABYLON.serialize()
- ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
- __decorate([
- BABYLON.serialize()
- ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
- return VolumetricLightScatteringPostProcess;
- })(BABYLON.PostProcess);
- BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
- })(BABYLON || (BABYLON = {}));
- // BABYLON.JS Chromatic Aberration GLSL Shader
- // Author: Olivier Guyot
- // Separates very slightly R, G and B colors on the edges of the screen
- // Inspired by Francois Tarlier & Martins Upitis
- var BABYLON;
- (function (BABYLON) {
- var LensRenderingPipeline = (function (_super) {
- __extends(LensRenderingPipeline, _super);
- /**
- * @constructor
- *
- * Effect parameters are as follow:
- * {
- * chromatic_aberration: number; // from 0 to x (1 for realism)
- * edge_blur: number; // from 0 to x (1 for realism)
- * distortion: number; // from 0 to x (1 for realism)
- * grain_amount: number; // from 0 to 1
- * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
- * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
- * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
- * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
- * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
- * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
- * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
- * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
- * }
- * Note: if an effect parameter is unset, effect is disabled
- *
- * @param {string} name - The rendering pipeline name
- * @param {object} parameters - An object containing all parameters (see above)
- * @param {BABYLON.Scene} scene - The scene linked to this pipeline
- * @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)
- * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
- */
- function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
- var _this = this;
- if (ratio === void 0) { ratio = 1.0; }
- _super.call(this, scene.getEngine(), name);
- // Lens effects can be of the following:
- // - chromatic aberration (slight shift of RGB colors)
- // - blur on the edge of the lens
- // - lens distortion
- // - depth-of-field blur & highlights enhancing
- // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
- // - grain effect (noise or custom texture)
- // Two additional texture samplers are needed:
- // - depth map (for depth-of-field)
- // - grain texture
- /**
- * The chromatic aberration PostProcess id in the pipeline
- * @type {string}
- */
- this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
- /**
- * The highlights enhancing PostProcess id in the pipeline
- * @type {string}
- */
- this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
- /**
- * The depth-of-field PostProcess id in the pipeline
- * @type {string}
- */
- this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
- this._scene = scene;
- // Fetch texture samplers
- this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
- if (parameters.grain_texture) {
- this._grainTexture = parameters.grain_texture;
- }
- else {
- this._createGrainTexture();
- }
- // save parameters
- this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
- this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
- this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
- this._distortion = parameters.distortion ? parameters.distortion : 0;
- this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
- this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
- this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
- this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
- this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
- this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
- this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
- // Create effects
- this._createChromaticAberrationPostProcess(ratio);
- this._createHighlightsPostProcess(ratio);
- this._createDepthOfFieldPostProcess(ratio / 4);
- // Set up pipeline
- this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
- this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
- this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
- if (this._highlightsGain === -1) {
- this._disableEffect(this.HighlightsEnhancingEffect, null);
- }
- // Finish
- scene.postProcessRenderPipelineManager.addPipeline(this);
- if (cameras) {
- scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
- }
- }
- // public methods (self explanatory)
- LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
- LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
- LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
- LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
- LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
- LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
- LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
- LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
- LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
- LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
- LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
- LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
- LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
- this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
- };
- LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
- this._highlightsPostProcess.updateEffect();
- };
- LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
- LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
- LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
- this._highlightsGain = amount;
- };
- LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
- if (this._highlightsGain === -1) {
- this._highlightsGain = 1.0;
- }
- this._highlightsThreshold = amount;
- };
- LensRenderingPipeline.prototype.disableHighlights = function () {
- this._highlightsGain = -1;
- };
- /**
- * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
- */
- LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
- if (disableDepthRender === void 0) { disableDepthRender = false; }
- this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
- this._chromaticAberrationPostProcess = undefined;
- this._highlightsPostProcess = undefined;
- this._depthOfFieldPostProcess = undefined;
- this._grainTexture.dispose();
- if (disableDepthRender)
- this._scene.disableDepthRenderer();
- };
- // colors shifting and distortion
- LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
- var _this = this;
- this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
- [], // samplers
- ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
- this._chromaticAberrationPostProcess.onApply = function (effect) {
- effect.setFloat('chromatic_aberration', _this._chromaticAberration);
- effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
- effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
- };
- };
- // highlights enhancing
- LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
- var _this = this;
- this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
- [], // samplers
- ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
- this._highlightsPostProcess.onApply = function (effect) {
- effect.setFloat('gain', _this._highlightsGain);
- effect.setFloat('threshold', _this._highlightsThreshold);
- effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
- effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
- effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
- };
- };
- // colors shifting and distortion
- LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
- var _this = this;
- this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
- "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
- "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
- ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
- this._depthOfFieldPostProcess.onApply = function (effect) {
- effect.setTexture("depthSampler", _this._depthTexture);
- effect.setTexture("grainSampler", _this._grainTexture);
- effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
- effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
- effect.setFloat('grain_amount', _this._grainAmount);
- effect.setBool('blur_noise', _this._blurNoise);
- effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
- effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
- effect.setFloat('distortion', _this._distortion);
- effect.setBool('dof_enabled', (_this._dofDistance !== -1));
- effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
- effect.setFloat('aperture', _this._dofAperture);
- effect.setFloat('darken', _this._dofDarken);
- effect.setFloat('edge_blur', _this._edgeBlur);
- effect.setBool('highlights', (_this._highlightsGain !== -1));
- effect.setFloat('near', _this._scene.activeCamera.minZ);
- effect.setFloat('far', _this._scene.activeCamera.maxZ);
- };
- };
- // creates a black and white random noise texture, 512x512
- LensRenderingPipeline.prototype._createGrainTexture = function () {
- var size = 512;
- this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
- this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
- this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
- var context = this._grainTexture.getContext();
- var rand = function (min, max) {
- return Math.random() * (max - min) + min;
- };
- var value;
- for (var x = 0; x < size; x++) {
- for (var y = 0; y < size; y++) {
- value = Math.floor(rand(0.42, 0.58) * 255);
- context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
- context.fillRect(x, y, 1, 1);
- }
- }
- this._grainTexture.update(false);
- };
- return LensRenderingPipeline;
- })(BABYLON.PostProcessRenderPipeline);
- BABYLON.LensRenderingPipeline = LensRenderingPipeline;
- })(BABYLON || (BABYLON = {}));
- //
- // This post-process allows the modification of rendered colors by using
- // a 'look-up table' (LUT). This effect is also called Color Grading.
- //
- // The object needs to be provided an url to a texture containing the color
- // look-up table: the texture must be 256 pixels wide and 16 pixels high.
- // Use an image editing software to tweak the LUT to match your needs.
- //
- // For an example of a color LUT, see here:
- // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
- // For explanations on color grading, see here:
- // http://udn.epicgames.com/Three/ColorGrading.html
- //
- var BABYLON;
- (function (BABYLON) {
- var ColorCorrectionPostProcess = (function (_super) {
- __extends(ColorCorrectionPostProcess, _super);
- function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
- var _this = this;
- _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
- this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
- this._colorTableTexture.anisotropicFilteringLevel = 1;
- this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
- this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
- this.onApply = function (effect) {
- effect.setTexture("colorTable", _this._colorTableTexture);
- };
- }
- return ColorCorrectionPostProcess;
- })(BABYLON.PostProcess);
- BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var AnaglyphFreeCamera = (function (_super) {
- __extends(AnaglyphFreeCamera, _super);
- function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
- _super.call(this, name, position, scene);
- this.interaxialDistance = interaxialDistance;
- this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
- }
- AnaglyphFreeCamera.prototype.getTypeName = function () {
- return "AnaglyphFreeCamera";
- };
- return AnaglyphFreeCamera;
- })(BABYLON.FreeCamera);
- BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
- var AnaglyphArcRotateCamera = (function (_super) {
- __extends(AnaglyphArcRotateCamera, _super);
- function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
- _super.call(this, name, alpha, beta, radius, target, scene);
- this.interaxialDistance = interaxialDistance;
- this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
- }
- AnaglyphArcRotateCamera.prototype.getTypeName = function () {
- return "AnaglyphArcRotateCamera";
- };
- return AnaglyphArcRotateCamera;
- })(BABYLON.ArcRotateCamera);
- BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
- var AnaglyphGamepadCamera = (function (_super) {
- __extends(AnaglyphGamepadCamera, _super);
- function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
- _super.call(this, name, position, scene);
- this.interaxialDistance = interaxialDistance;
- this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
- }
- AnaglyphGamepadCamera.prototype.getTypeName = function () {
- return "AnaglyphGamepadCamera";
- };
- return AnaglyphGamepadCamera;
- })(BABYLON.GamepadCamera);
- BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
- var AnaglyphUniversalCamera = (function (_super) {
- __extends(AnaglyphUniversalCamera, _super);
- function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
- _super.call(this, name, position, scene);
- this.interaxialDistance = interaxialDistance;
- this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
- }
- AnaglyphUniversalCamera.prototype.getTypeName = function () {
- return "AnaglyphUniversalCamera";
- };
- return AnaglyphUniversalCamera;
- })(BABYLON.UniversalCamera);
- BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
- var StereoscopicFreeCamera = (function (_super) {
- __extends(StereoscopicFreeCamera, _super);
- function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
- _super.call(this, name, position, scene);
- this.interaxialDistance = interaxialDistance;
- this.isStereoscopicSideBySide = isStereoscopicSideBySide;
- this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
- }
- StereoscopicFreeCamera.prototype.getTypeName = function () {
- return "StereoscopicFreeCamera";
- };
- return StereoscopicFreeCamera;
- })(BABYLON.FreeCamera);
- BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
- var StereoscopicArcRotateCamera = (function (_super) {
- __extends(StereoscopicArcRotateCamera, _super);
- function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
- _super.call(this, name, alpha, beta, radius, target, scene);
- this.interaxialDistance = interaxialDistance;
- this.isStereoscopicSideBySide = isStereoscopicSideBySide;
- this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
- }
- StereoscopicArcRotateCamera.prototype.getTypeName = function () {
- return "StereoscopicArcRotateCamera";
- };
- return StereoscopicArcRotateCamera;
- })(BABYLON.ArcRotateCamera);
- BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
- var StereoscopicGamepadCamera = (function (_super) {
- __extends(StereoscopicGamepadCamera, _super);
- function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
- _super.call(this, name, position, scene);
- this.interaxialDistance = interaxialDistance;
- this.isStereoscopicSideBySide = isStereoscopicSideBySide;
- this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
- }
- StereoscopicGamepadCamera.prototype.getTypeName = function () {
- return "StereoscopicGamepadCamera";
- };
- return StereoscopicGamepadCamera;
- })(BABYLON.GamepadCamera);
- BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
- var StereoscopicUniversalCamera = (function (_super) {
- __extends(StereoscopicUniversalCamera, _super);
- function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
- _super.call(this, name, position, scene);
- this.interaxialDistance = interaxialDistance;
- this.isStereoscopicSideBySide = isStereoscopicSideBySide;
- this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
- }
- StereoscopicUniversalCamera.prototype.getTypeName = function () {
- return "StereoscopicUniversalCamera";
- };
- return StereoscopicUniversalCamera;
- })(BABYLON.UniversalCamera);
- BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var HDRRenderingPipeline = (function (_super) {
- __extends(HDRRenderingPipeline, _super);
- /**
- * @constructor
- * @param {string} name - The rendering pipeline name
- * @param {BABYLON.Scene} scene - The scene linked to this pipeline
- * @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)
- * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
- * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
- */
- function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
- var _this = this;
- if (originalPostProcess === void 0) { originalPostProcess = null; }
- _super.call(this, scene.getEngine(), name);
- /**
- * Public members
- */
- // Gaussian Blur
- /**
- * Gaussian blur coefficient
- * @type {number}
- */
- this.gaussCoeff = 0.3;
- /**
- * Gaussian blur mean
- * @type {number}
- */
- this.gaussMean = 1.0;
- /**
- * Gaussian blur standard deviation
- * @type {number}
- */
- this.gaussStandDev = 0.8;
- /**
- * Gaussian blur multiplier. Multiplies the blur effect
- * @type {number}
- */
- this.gaussMultiplier = 4.0;
- // HDR
- /**
- * Exposure, controls the overall intensity of the pipeline
- * @type {number}
- */
- this.exposure = 1.0;
- /**
- * Minimum luminance that the post-process can output. Luminance is >= 0
- * @type {number}
- */
- this.minimumLuminance = 1.0;
- /**
- * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
- * @type {number}
- */
- this.maximumLuminance = 1e20;
- /**
- * Increase rate for luminance: eye adaptation speed to dark
- * @type {number}
- */
- this.luminanceIncreaserate = 0.5;
- /**
- * Decrease rate for luminance: eye adaptation speed to bright
- * @type {number}
- */
- this.luminanceDecreaseRate = 0.5;
- // Bright pass
- /**
- * Minimum luminance needed to compute HDR
- * @type {number}
- */
- this.brightThreshold = 0.8;
- this._needUpdate = true;
- this._scene = scene;
- // Bright pass
- this._createBrightPassPostProcess(scene, ratio);
- // Down sample X4
- this._createDownSampleX4PostProcess(scene, ratio);
- // Create gaussian blur post-processes
- this._createGaussianBlurPostProcess(scene, ratio);
- // Texture adder
- this._createTextureAdderPostProcess(scene, ratio);
- // Luminance generator
- this._createLuminanceGeneratorPostProcess(scene);
- // HDR
- this._createHDRPostProcess(scene, ratio);
- // Pass postprocess
- if (originalPostProcess === null) {
- this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
- }
- else {
- this._originalPostProcess = originalPostProcess;
- }
- // Configure pipeline
- this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
- this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
- this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
- this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
- this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
- this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
- var addDownSamplerPostProcess = function (id) {
- _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
- };
- for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
- addDownSamplerPostProcess(i);
- }
- this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
- // Finish
- scene.postProcessRenderPipelineManager.addPipeline(this);
- if (cameras !== null) {
- scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
- }
- this.update();
- }
- /**
- * Tells the pipeline to update its post-processes
- */
- HDRRenderingPipeline.prototype.update = function () {
- this._needUpdate = true;
- };
- /**
- * Returns the current calculated luminance
- */
- HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
- return this._hdrCurrentLuminance;
- };
- /**
- * Returns the currently drawn luminance
- */
- HDRRenderingPipeline.prototype.getOutputLuminance = function () {
- return this._hdrOutputLuminance;
- };
- /**
- * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
- */
- HDRRenderingPipeline.prototype.dispose = function () {
- this._originalPostProcess = undefined;
- this._brightPassPostProcess = undefined;
- this._downSampleX4PostProcess = undefined;
- this._guassianBlurHPostProcess = undefined;
- this._guassianBlurVPostProcess = undefined;
- this._textureAdderPostProcess = undefined;
- for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
- this._downSamplePostProcesses[i] = undefined;
- }
- this._hdrPostProcess = undefined;
- this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
- };
- /**
- * Creates the HDR post-process and computes the luminance adaptation
- */
- HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
- var _this = this;
- var hdrLastLuminance = 0.0;
- this._hdrOutputLuminance = -1.0;
- this._hdrCurrentLuminance = 1.0;
- this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
- this._hdrPostProcess.onApply = function (effect) {
- if (_this._hdrOutputLuminance < 0.0) {
- _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
- }
- else {
- var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
- if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
- _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
- }
- else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
- _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
- }
- else {
- _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
- }
- }
- _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
- hdrLastLuminance += scene.getEngine().getDeltaTime();
- effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
- effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
- effect.setFloat("exposure", _this.exposure);
- effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
- _this._needUpdate = false;
- };
- };
- /**
- * Texture Adder post-process
- */
- HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
- var _this = this;
- this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
- this._textureAdderPostProcess.onApply = function (effect) {
- effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
- };
- };
- /**
- * Down sample X4 post-process
- */
- HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
- var _this = this;
- var downSampleX4Offsets = new Array(32);
- this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
- this._downSampleX4PostProcess.onApply = function (effect) {
- if (_this._needUpdate) {
- var id = 0;
- for (var i = -2; i < 2; i++) {
- for (var j = -2; j < 2; j++) {
- downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
- downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
- id += 2;
- }
- }
- }
- effect.setArray2("dsOffsets", downSampleX4Offsets);
- };
- };
- /**
- * Bright pass post-process
- */
- HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
- var _this = this;
- var brightOffsets = new Array(8);
- var brightPassCallback = function (effect) {
- if (_this._needUpdate) {
- var sU = (1.0 / _this._brightPassPostProcess.width);
- var sV = (1.0 / _this._brightPassPostProcess.height);
- brightOffsets[0] = -0.5 * sU;
- brightOffsets[1] = 0.5 * sV;
- brightOffsets[2] = 0.5 * sU;
- brightOffsets[3] = 0.5 * sV;
- brightOffsets[4] = -0.5 * sU;
- brightOffsets[5] = -0.5 * sV;
- brightOffsets[6] = 0.5 * sU;
- brightOffsets[7] = -0.5 * sV;
- }
- effect.setArray2("dsOffsets", brightOffsets);
- effect.setFloat("brightThreshold", _this.brightThreshold);
- };
- this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
- this._brightPassPostProcess.onApply = brightPassCallback;
- };
- /**
- * Luminance generator. Creates the luminance post-process and down sample post-processes
- */
- HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
- var _this = this;
- var lumSteps = HDRRenderingPipeline.LUM_STEPS;
- var luminanceOffsets = new Array(8);
- var downSampleOffsets = new Array(18);
- var halfDestPixelSize;
- this._downSamplePostProcesses = new Array(lumSteps);
- // Utils for luminance
- var luminanceUpdateSourceOffsets = function (width, height) {
- var sU = (1.0 / width);
- var sV = (1.0 / height);
- luminanceOffsets[0] = -0.5 * sU;
- luminanceOffsets[1] = 0.5 * sV;
- luminanceOffsets[2] = 0.5 * sU;
- luminanceOffsets[3] = 0.5 * sV;
- luminanceOffsets[4] = -0.5 * sU;
- luminanceOffsets[5] = -0.5 * sV;
- luminanceOffsets[6] = 0.5 * sU;
- luminanceOffsets[7] = -0.5 * sV;
- };
- var luminanceUpdateDestOffsets = function (width, height) {
- var id = 0;
- for (var x = -1; x < 2; x++) {
- for (var y = -1; y < 2; y++) {
- downSampleOffsets[id] = (x) / width;
- downSampleOffsets[id + 1] = (y) / height;
- id += 2;
- }
- }
- };
- // Luminance callback
- var luminanceCallback = function (effect) {
- if (_this._needUpdate) {
- luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
- }
- effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
- effect.setArray2("lumOffsets", luminanceOffsets);
- };
- // Down sample callbacks
- var downSampleCallback = function (indice) {
- var i = indice;
- return function (effect) {
- luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
- luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
- halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
- effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
- effect.setFloat("halfDestPixelSize", halfDestPixelSize);
- effect.setArray2("dsOffsets", downSampleOffsets);
- };
- };
- var downSampleAfterRenderCallback = function (effect) {
- // Unpack result
- var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
- 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);
- _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
- };
- // Create luminance post-process
- var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
- 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);
- this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
- // Create down sample post-processes
- for (var i = lumSteps - 2; i >= 0; i--) {
- var length = Math.pow(3, i);
- ratio = { width: length, height: length };
- var defines = "#define DOWN_SAMPLE\n";
- if (i === 0) {
- defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
- }
- this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
- this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
- if (i === 0) {
- this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
- }
- }
- };
- /**
- * Gaussian blur post-processes. Horizontal and Vertical
- */
- HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
- var _this = this;
- var blurOffsetsW = new Array(9);
- var blurOffsetsH = new Array(9);
- var blurWeights = new Array(9);
- var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
- // Utils for gaussian blur
- var calculateBlurOffsets = function (height) {
- var lastOutputDimensions = {
- width: scene.getEngine().getRenderWidth(),
- height: scene.getEngine().getRenderHeight()
- };
- for (var i = 0; i < 9; i++) {
- var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
- if (height) {
- blurOffsetsH[i] = value;
- }
- else {
- blurOffsetsW[i] = value;
- }
- }
- };
- var calculateWeights = function () {
- var x = 0.0;
- for (var i = 0; i < 9; i++) {
- x = (i - 4.0) / 4.0;
- 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));
- }
- };
- // Callback
- var gaussianBlurCallback = function (height) {
- return function (effect) {
- if (_this._needUpdate) {
- calculateWeights();
- calculateBlurOffsets(height);
- }
- effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
- effect.setArray("blurWeights", blurWeights);
- effect.setFloat("multiplier", _this.gaussMultiplier);
- };
- };
- // Create horizontal gaussian blur post-processes
- this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
- this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
- // Create vertical gaussian blur post-process
- this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
- this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
- };
- // Luminance generator
- HDRRenderingPipeline.LUM_STEPS = 6;
- return HDRRenderingPipeline;
- })(BABYLON.PostProcessRenderPipeline);
- BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var FaceAdjacencies = (function () {
- function FaceAdjacencies() {
- this.edges = new Array();
- this.edgesConnectedCount = 0;
- }
- return FaceAdjacencies;
- })();
- var EdgesRenderer = (function () {
- // Beware when you use this class with complex objects as the adjacencies computation can be really long
- function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
- if (epsilon === void 0) { epsilon = 0.95; }
- if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
- this.edgesWidthScalerForOrthographic = 1000.0;
- this.edgesWidthScalerForPerspective = 50.0;
- this._linesPositions = new Array();
- this._linesNormals = new Array();
- this._linesIndices = new Array();
- this._buffers = new Array();
- this._checkVerticesInsteadOfIndices = false;
- this._source = source;
- this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
- this._epsilon = epsilon;
- this._prepareRessources();
- this._generateEdgesLines();
- }
- EdgesRenderer.prototype._prepareRessources = function () {
- if (this._lineShader) {
- return;
- }
- this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
- attributes: ["position", "normal"],
- uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
- });
- this._lineShader.disableDepthWrite = true;
- this._lineShader.backFaceCulling = false;
- };
- EdgesRenderer.prototype.dispose = function () {
- this._vb0.dispose();
- this._vb1.dispose();
- this._source.getScene().getEngine()._releaseBuffer(this._ib);
- this._lineShader.dispose();
- };
- EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
- if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
- return 0;
- }
- if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
- return 1;
- }
- if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
- return 2;
- }
- return -1;
- };
- EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
- if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
- return 0;
- }
- if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
- return 1;
- }
- if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
- return 2;
- }
- return -1;
- };
- EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
- var needToCreateLine;
- if (edge === undefined) {
- needToCreateLine = true;
- }
- else {
- var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
- needToCreateLine = dotProduct < this._epsilon;
- }
- if (needToCreateLine) {
- var offset = this._linesPositions.length / 3;
- var normal = p0.subtract(p1);
- normal.normalize();
- // Positions
- this._linesPositions.push(p0.x);
- this._linesPositions.push(p0.y);
- this._linesPositions.push(p0.z);
- this._linesPositions.push(p0.x);
- this._linesPositions.push(p0.y);
- this._linesPositions.push(p0.z);
- this._linesPositions.push(p1.x);
- this._linesPositions.push(p1.y);
- this._linesPositions.push(p1.z);
- this._linesPositions.push(p1.x);
- this._linesPositions.push(p1.y);
- this._linesPositions.push(p1.z);
- // Normals
- this._linesNormals.push(p1.x);
- this._linesNormals.push(p1.y);
- this._linesNormals.push(p1.z);
- this._linesNormals.push(-1);
- this._linesNormals.push(p1.x);
- this._linesNormals.push(p1.y);
- this._linesNormals.push(p1.z);
- this._linesNormals.push(1);
- this._linesNormals.push(p0.x);
- this._linesNormals.push(p0.y);
- this._linesNormals.push(p0.z);
- this._linesNormals.push(-1);
- this._linesNormals.push(p0.x);
- this._linesNormals.push(p0.y);
- this._linesNormals.push(p0.z);
- this._linesNormals.push(1);
- // Indices
- this._linesIndices.push(offset);
- this._linesIndices.push(offset + 1);
- this._linesIndices.push(offset + 2);
- this._linesIndices.push(offset);
- this._linesIndices.push(offset + 2);
- this._linesIndices.push(offset + 3);
- }
- };
- EdgesRenderer.prototype._generateEdgesLines = function () {
- var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- var indices = this._source.getIndices();
- // First let's find adjacencies
- var adjacencies = new Array();
- var faceNormals = new Array();
- var index;
- var faceAdjacencies;
- // Prepare faces
- for (index = 0; index < indices.length; index += 3) {
- faceAdjacencies = new FaceAdjacencies();
- var p0Index = indices[index];
- var p1Index = indices[index + 1];
- var p2Index = indices[index + 2];
- faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
- faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
- faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
- var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
- faceNormal.normalize();
- faceNormals.push(faceNormal);
- adjacencies.push(faceAdjacencies);
- }
- // Scan
- for (index = 0; index < adjacencies.length; index++) {
- faceAdjacencies = adjacencies[index];
- for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
- var otherFaceAdjacencies = adjacencies[otherIndex];
- if (faceAdjacencies.edgesConnectedCount === 3) {
- break;
- }
- if (otherFaceAdjacencies.edgesConnectedCount === 3) {
- continue;
- }
- var otherP0 = indices[otherIndex * 3];
- var otherP1 = indices[otherIndex * 3 + 1];
- var otherP2 = indices[otherIndex * 3 + 2];
- for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
- var otherEdgeIndex;
- if (faceAdjacencies.edges[edgeIndex] !== undefined) {
- continue;
- }
- switch (edgeIndex) {
- case 0:
- if (this._checkVerticesInsteadOfIndices) {
- otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
- }
- else {
- otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
- }
- break;
- case 1:
- if (this._checkVerticesInsteadOfIndices) {
- otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
- }
- else {
- otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
- }
- break;
- case 2:
- if (this._checkVerticesInsteadOfIndices) {
- otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
- }
- else {
- otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
- }
- break;
- }
- if (otherEdgeIndex === -1) {
- continue;
- }
- faceAdjacencies.edges[edgeIndex] = otherIndex;
- otherFaceAdjacencies.edges[otherEdgeIndex] = index;
- faceAdjacencies.edgesConnectedCount++;
- otherFaceAdjacencies.edgesConnectedCount++;
- if (faceAdjacencies.edgesConnectedCount === 3) {
- break;
- }
- }
- }
- }
- // Create lines
- for (index = 0; index < adjacencies.length; index++) {
- // 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
- var current = adjacencies[index];
- this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
- this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
- this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
- }
- // Merge into a single mesh
- var engine = this._source.getScene().getEngine();
- this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
- this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
- this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
- this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
- this._ib = engine.createIndexBuffer(this._linesIndices);
- this._indicesCount = this._linesIndices.length;
- };
- EdgesRenderer.prototype.render = function () {
- if (!this._lineShader.isReady()) {
- return;
- }
- var scene = this._source.getScene();
- var engine = scene.getEngine();
- this._lineShader._preBind();
- // VBOs
- engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
- scene.resetCachedMaterial();
- this._lineShader.setColor4("color", this._source.edgesColor);
- if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
- this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
- }
- else {
- this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
- }
- this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
- this._lineShader.bind(this._source.getWorldMatrix());
- // Draw order
- engine.draw(true, 0, this._indicesCount);
- this._lineShader.unbind();
- engine.setDepthWrite(true);
- };
- return EdgesRenderer;
- })();
- BABYLON.EdgesRenderer = EdgesRenderer;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- (function (TonemappingOperator) {
- TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
- TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
- TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
- TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
- })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
- var TonemappingOperator = BABYLON.TonemappingOperator;
- ;
- var TonemapPostProcess = (function (_super) {
- __extends(TonemapPostProcess, _super);
- function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
- var _this = this;
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
- if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
- _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
- this._operator = _operator;
- this.exposureAdjustment = exposureAdjustment;
- var defines = "#define ";
- if (this._operator === TonemappingOperator.Hable)
- defines += "HABLE_TONEMAPPING";
- else if (this._operator === TonemappingOperator.Reinhard)
- defines += "REINHARD_TONEMAPPING";
- else if (this._operator === TonemappingOperator.HejiDawson)
- defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
- else if (this._operator === TonemappingOperator.Photographic)
- defines += "PHOTOGRAPHIC_TONEMAPPING";
- //sadly a second call to create the effect.
- this.updateEffect(defines);
- this.onApply = function (effect) {
- effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
- };
- }
- return TonemapPostProcess;
- })(BABYLON.PostProcess);
- BABYLON.TonemapPostProcess = TonemapPostProcess;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var ReflectionProbe = (function () {
- function ReflectionProbe(name, size, scene, generateMipMaps) {
- var _this = this;
- if (generateMipMaps === void 0) { generateMipMaps = true; }
- this.name = name;
- this._viewMatrix = BABYLON.Matrix.Identity();
- this._target = BABYLON.Vector3.Zero();
- this._add = BABYLON.Vector3.Zero();
- this.invertYAxis = false;
- this.position = BABYLON.Vector3.Zero();
- this._scene = scene;
- this._scene.reflectionProbes.push(this);
- this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
- this._renderTargetTexture.onBeforeRender = function (faceIndex) {
- switch (faceIndex) {
- case 0:
- _this._add.copyFromFloats(1, 0, 0);
- break;
- case 1:
- _this._add.copyFromFloats(-1, 0, 0);
- break;
- case 2:
- _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
- break;
- case 3:
- _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
- break;
- case 4:
- _this._add.copyFromFloats(0, 0, 1);
- break;
- case 5:
- _this._add.copyFromFloats(0, 0, -1);
- break;
- }
- if (_this._attachedMesh) {
- _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
- }
- _this.position.addToRef(_this._add, _this._target);
- BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
- scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
- };
- this._renderTargetTexture.onAfterUnbind = function () {
- scene.updateTransformMatrix(true);
- };
- this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
- }
- Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
- get: function () {
- return this._renderTargetTexture.refreshRate;
- },
- set: function (value) {
- this._renderTargetTexture.refreshRate = value;
- },
- enumerable: true,
- configurable: true
- });
- ReflectionProbe.prototype.getScene = function () {
- return this._scene;
- };
- Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
- get: function () {
- return this._renderTargetTexture;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ReflectionProbe.prototype, "renderList", {
- get: function () {
- return this._renderTargetTexture.renderList;
- },
- enumerable: true,
- configurable: true
- });
- ReflectionProbe.prototype.attachToMesh = function (mesh) {
- this._attachedMesh = mesh;
- };
- ReflectionProbe.prototype.dispose = function () {
- var index = this._scene.reflectionProbes.indexOf(this);
- if (index !== -1) {
- // Remove from the scene if found
- this._scene.reflectionProbes.splice(index, 1);
- }
- if (this._renderTargetTexture) {
- this._renderTargetTexture.dispose();
- this._renderTargetTexture = null;
- }
- };
- return ReflectionProbe;
- })();
- BABYLON.ReflectionProbe = ReflectionProbe;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var SolidParticle = (function () {
- function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
- this.color = new BABYLON.Color4(1, 1, 1, 1); // color
- this.position = BABYLON.Vector3.Zero(); // position
- this.rotation = BABYLON.Vector3.Zero(); // rotation
- this.scaling = new BABYLON.Vector3(1, 1, 1); // scaling
- this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
- this.velocity = BABYLON.Vector3.Zero(); // velocity
- this.alive = true; // alive
- this.idx = particleIndex;
- this._pos = positionIndex;
- this._model = model;
- this.shapeId = shapeId;
- this.idxInShape = idxInShape;
- }
- Object.defineProperty(SolidParticle.prototype, "scale", {
- //legacy support, changed scale to scaling
- get: function () {
- return this.scaling;
- },
- set: function (scale) {
- this.scaling = scale;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(SolidParticle.prototype, "quaternion", {
- //legacy support, changed quaternion to rotationQuaternion
- get: function () {
- return this.rotationQuaternion;
- },
- set: function (q) {
- this.rotationQuaternion = q;
- },
- enumerable: true,
- configurable: true
- });
- return SolidParticle;
- })();
- BABYLON.SolidParticle = SolidParticle;
- var ModelShape = (function () {
- function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
- this.shapeID = id;
- this._shape = shape;
- this._shapeUV = shapeUV;
- this._positionFunction = posFunction;
- this._vertexFunction = vtxFunction;
- }
- return ModelShape;
- })();
- BABYLON.ModelShape = ModelShape;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- /**
- * Full documentation here : http://doc.babylonjs.com/tutorials/Solid_Particle_System
- */
- var SolidParticleSystem = (function () {
- /**
- * Creates a SPS (Solid Particle System) object.
- * `name` (String) is the SPS name, this will be the underlying mesh name.
- * `scene` (Scene) is the scene in which the SPS is added.
- * `updatableè (default true) : if the SPS must be updatable or immutable.
- * `isPickable` (default false) : if the solid particles must be pickable.
- */
- function SolidParticleSystem(name, scene, options) {
- // public members
- /**
- * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
- * Example : var p = SPS.particles[i];
- */
- this.particles = new Array();
- /**
- * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
- */
- this.nbParticles = 0;
- /**
- * If the particles must ever face the camera (default false). Useful for planar particles.
- */
- this.billboard = false;
- /**
- * This a counter ofr your own usage. It's not set by any SPS functions.
- */
- this.counter = 0;
- /**
- * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
- * Please read : http://doc.babylonjs.com/tutorials/Solid_Particle_System#garbage-collector-concerns
- */
- this.vars = {};
- this._positions = new Array();
- this._indices = new Array();
- this._normals = new Array();
- this._colors = new Array();
- this._uvs = new Array();
- this._index = 0; // indices index
- this._updatable = true;
- this._pickable = false;
- this._isVisibilityBoxLocked = false;
- this._alwaysVisible = false;
- this._shapeCounter = 0;
- this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
- this._color = new BABYLON.Color4(0, 0, 0, 0);
- this._computeParticleColor = true;
- this._computeParticleTexture = true;
- this._computeParticleRotation = true;
- this._computeParticleVertex = false;
- this._computeBoundingBox = false;
- this._cam_axisZ = BABYLON.Vector3.Zero();
- this._cam_axisY = BABYLON.Vector3.Zero();
- this._cam_axisX = BABYLON.Vector3.Zero();
- this._axisX = BABYLON.Axis.X;
- this._axisY = BABYLON.Axis.Y;
- this._axisZ = BABYLON.Axis.Z;
- this._fakeCamPos = BABYLON.Vector3.Zero();
- this._rotMatrix = new BABYLON.Matrix();
- this._invertMatrix = new BABYLON.Matrix();
- this._rotated = BABYLON.Vector3.Zero();
- this._quaternion = new BABYLON.Quaternion();
- this._vertex = BABYLON.Vector3.Zero();
- this._normal = BABYLON.Vector3.Zero();
- this._yaw = 0.0;
- this._pitch = 0.0;
- this._roll = 0.0;
- this._halfroll = 0.0;
- this._halfpitch = 0.0;
- this._halfyaw = 0.0;
- this._sinRoll = 0.0;
- this._cosRoll = 0.0;
- this._sinPitch = 0.0;
- this._cosPitch = 0.0;
- this._sinYaw = 0.0;
- this._cosYaw = 0.0;
- this._w = 0.0;
- this._minimum = BABYLON.Tmp.Vector3[0];
- this._maximum = BABYLON.Tmp.Vector3[1];
- this.name = name;
- this._scene = scene;
- this._camera = scene.activeCamera;
- this._pickable = options ? options.isPickable : false;
- if (options && options.updatable) {
- this._updatable = options.updatable;
- }
- else {
- this._updatable = true;
- }
- if (this._pickable) {
- this.pickedParticles = [];
- }
- }
- /**
- * Builds the SPS underlying mesh. Returns a standard Mesh.
- * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
- */
- SolidParticleSystem.prototype.buildMesh = function () {
- if (this.nbParticles === 0) {
- var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
- this.addShape(triangle, 1);
- triangle.dispose();
- }
- this._positions32 = new Float32Array(this._positions);
- this._uvs32 = new Float32Array(this._uvs);
- this._colors32 = new Float32Array(this._colors);
- BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
- this._normals32 = new Float32Array(this._normals);
- this._fixedNormal32 = new Float32Array(this._normals);
- var vertexData = new BABYLON.VertexData();
- vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
- vertexData.indices = this._indices;
- vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
- if (this._uvs32) {
- vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
- ;
- }
- if (this._colors32) {
- vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
- }
- var mesh = new BABYLON.Mesh(this.name, this._scene);
- vertexData.applyToMesh(mesh, this._updatable);
- this.mesh = mesh;
- this.mesh.isPickable = this._pickable;
- // free memory
- this._positions = null;
- this._normals = null;
- this._uvs = null;
- this._colors = null;
- if (!this._updatable) {
- this.particles.length = 0;
- }
- return mesh;
- };
- /**
- * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
- * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
- * Thus the particles generated from `digest()` have their property `position` set yet.
- * `mesh` (`Mesh`) is the mesh to be digested
- * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
- * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
- * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
- */
- SolidParticleSystem.prototype.digest = function (mesh, options) {
- var size = (options && options.facetNb) || 1;
- var number = (options && options.number);
- var delta = (options && options.delta) || 0;
- var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- var meshInd = mesh.getIndices();
- var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
- var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
- var f = 0; // facet counter
- var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
- // compute size from number
- if (number) {
- number = (number > totalFacets) ? totalFacets : number;
- size = Math.round(totalFacets / number);
- delta = 0;
- }
- else {
- size = (size > totalFacets) ? totalFacets : size;
- }
- var facetPos = []; // submesh positions
- var facetInd = []; // submesh indices
- var facetUV = []; // submesh UV
- var facetCol = []; // submesh colors
- var barycenter = BABYLON.Tmp.Vector3[0];
- var rand;
- var sizeO = size;
- while (f < totalFacets) {
- size = sizeO + Math.floor((1 + delta) * Math.random());
- if (f > totalFacets - size) {
- size = totalFacets - f;
- }
- // reset temp arrays
- facetPos.length = 0;
- facetInd.length = 0;
- facetUV.length = 0;
- facetCol.length = 0;
- // iterate over "size" facets
- var fi = 0;
- for (var j = f * 3; j < (f + size) * 3; j++) {
- facetInd.push(fi);
- var i = meshInd[j];
- facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
- if (meshUV) {
- facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
- }
- if (meshCol) {
- facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
- }
- fi++;
- }
- // create a model shape for each single particle
- var idx = this.nbParticles;
- var shape = this._posToShape(facetPos);
- var shapeUV = this._uvsToShapeUV(facetUV);
- // compute the barycenter of the shape
- var v;
- for (v = 0; v < shape.length; v++) {
- barycenter.addInPlace(shape[v]);
- }
- barycenter.scaleInPlace(1 / shape.length);
- // shift the shape from its barycenter to the origin
- for (v = 0; v < shape.length; v++) {
- shape[v].subtractInPlace(barycenter);
- }
- var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
- // add the particle in the SPS
- this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
- this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
- // initialize the particle position
- this.particles[this.nbParticles].position.addInPlace(barycenter);
- this._index += shape.length;
- idx++;
- this.nbParticles++;
- this._shapeCounter++;
- f += size;
- }
- return this;
- };
- //reset copy
- SolidParticleSystem.prototype._resetCopy = function () {
- this._copy.position.x = 0;
- this._copy.position.y = 0;
- this._copy.position.z = 0;
- this._copy.rotation.x = 0;
- this._copy.rotation.y = 0;
- this._copy.rotation.z = 0;
- this._copy.rotationQuaternion = null;
- this._copy.scaling.x = 1;
- this._copy.scaling.y = 1;
- this._copy.scaling.z = 1;
- this._copy.uvs.x = 0;
- this._copy.uvs.y = 0;
- this._copy.uvs.z = 1;
- this._copy.uvs.w = 1;
- this._copy.color = null;
- };
- // _meshBuilder : inserts the shape model in the global SPS mesh
- SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
- var i;
- var u = 0;
- var c = 0;
- this._resetCopy();
- if (options && options.positionFunction) {
- options.positionFunction(this._copy, idx, idxInShape);
- }
- if (this._copy.rotationQuaternion) {
- this._quaternion.copyFrom(this._copy.rotationQuaternion);
- }
- else {
- this._yaw = this._copy.rotation.y;
- this._pitch = this._copy.rotation.x;
- this._roll = this._copy.rotation.z;
- this._quaternionRotationYPR();
- }
- this._quaternionToRotationMatrix();
- for (i = 0; i < shape.length; i++) {
- this._vertex.x = shape[i].x;
- this._vertex.y = shape[i].y;
- this._vertex.z = shape[i].z;
- if (options && options.vertexFunction) {
- options.vertexFunction(this._copy, this._vertex, i);
- }
- this._vertex.x *= this._copy.scaling.x;
- this._vertex.y *= this._copy.scaling.y;
- this._vertex.z *= this._copy.scaling.z;
- BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
- positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
- if (meshUV) {
- 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);
- u += 2;
- }
- if (this._copy.color) {
- this._color = this._copy.color;
- }
- else if (meshCol && meshCol[c]) {
- this._color.r = meshCol[c];
- this._color.g = meshCol[c + 1];
- this._color.b = meshCol[c + 2];
- this._color.a = meshCol[c + 3];
- }
- else {
- this._color.r = 1;
- this._color.g = 1;
- this._color.b = 1;
- this._color.a = 1;
- }
- colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
- c += 4;
- }
- for (i = 0; i < meshInd.length; i++) {
- indices.push(p + meshInd[i]);
- }
- if (this._pickable) {
- var nbfaces = meshInd.length / 3;
- for (i = 0; i < nbfaces; i++) {
- this.pickedParticles.push({ idx: idx, faceId: i });
- }
- }
- };
- // returns a shape array from positions array
- SolidParticleSystem.prototype._posToShape = function (positions) {
- var shape = [];
- for (var i = 0; i < positions.length; i += 3) {
- shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
- }
- return shape;
- };
- // returns a shapeUV array from a Vector4 uvs
- SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
- var shapeUV = [];
- if (uvs) {
- for (var i = 0; i < uvs.length; i++)
- shapeUV.push(uvs[i]);
- }
- return shapeUV;
- };
- // adds a new particle object in the particles array
- SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
- this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
- };
- /**
- * Adds some particles to the SPS from the model shape. Returns the shape id.
- * Please read the doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#create-an-immutable-sps
- * `mesh` is any `Mesh` object that will be used as a model for the solid particles.
- * `nb` (positive integer) the number of particles to be created from this model
- * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
- * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
- */
- SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
- var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- var meshInd = mesh.getIndices();
- var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
- var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
- var shape = this._posToShape(meshPos);
- var shapeUV = this._uvsToShapeUV(meshUV);
- var posfunc = options ? options.positionFunction : null;
- var vtxfunc = options ? options.vertexFunction : null;
- var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
- // particles
- var idx = this.nbParticles;
- for (var i = 0; i < nb; i++) {
- this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
- if (this._updatable) {
- this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
- }
- this._index += shape.length;
- idx++;
- }
- this.nbParticles += nb;
- this._shapeCounter++;
- return this._shapeCounter - 1;
- };
- // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
- SolidParticleSystem.prototype._rebuildParticle = function (particle) {
- this._resetCopy();
- if (particle._model._positionFunction) {
- particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
- }
- if (this._copy.rotationQuaternion) {
- this._quaternion.copyFrom(this._copy.rotationQuaternion);
- }
- else {
- this._yaw = this._copy.rotation.y;
- this._pitch = this._copy.rotation.x;
- this._roll = this._copy.rotation.z;
- this._quaternionRotationYPR();
- }
- this._quaternionToRotationMatrix();
- this._shape = particle._model._shape;
- for (var pt = 0; pt < this._shape.length; pt++) {
- this._vertex.x = this._shape[pt].x;
- this._vertex.y = this._shape[pt].y;
- this._vertex.z = this._shape[pt].z;
- if (particle._model._vertexFunction) {
- particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
- }
- this._vertex.x *= this._copy.scaling.x;
- this._vertex.y *= this._copy.scaling.y;
- this._vertex.z *= this._copy.scaling.z;
- BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
- this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
- this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
- this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
- }
- particle.position.x = 0;
- particle.position.y = 0;
- particle.position.z = 0;
- particle.rotation.x = 0;
- particle.rotation.y = 0;
- particle.rotation.z = 0;
- particle.rotationQuaternion = null;
- particle.scaling.x = 1;
- particle.scaling.y = 1;
- particle.scaling.z = 1;
- };
- /**
- * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
- */
- SolidParticleSystem.prototype.rebuildMesh = function () {
- for (var p = 0; p < this.particles.length; p++) {
- this._rebuildParticle(this.particles[p]);
- }
- this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
- };
- /**
- * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
- * This method calls `updateParticle()` for each particle of the SPS.
- * For an animated SPS, it is usually called within the render loop.
- * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
- * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
- * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
- */
- SolidParticleSystem.prototype.setParticles = function (start, end, update) {
- if (start === void 0) { start = 0; }
- if (end === void 0) { end = this.nbParticles - 1; }
- if (update === void 0) { update = true; }
- if (!this._updatable) {
- return;
- }
- // custom beforeUpdate
- this.beforeUpdateParticles(start, end, update);
- this._cam_axisX.x = 1;
- this._cam_axisX.y = 0;
- this._cam_axisX.z = 0;
- this._cam_axisY.x = 0;
- this._cam_axisY.y = 1;
- this._cam_axisY.z = 0;
- this._cam_axisZ.x = 0;
- this._cam_axisZ.y = 0;
- this._cam_axisZ.z = 1;
- // if the particles will always face the camera
- if (this.billboard) {
- // compute a fake camera position : un-rotate the camera position by the current mesh rotation
- this._yaw = this.mesh.rotation.y;
- this._pitch = this.mesh.rotation.x;
- this._roll = this.mesh.rotation.z;
- this._quaternionRotationYPR();
- this._quaternionToRotationMatrix();
- this._rotMatrix.invertToRef(this._invertMatrix);
- BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
- // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
- (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
- BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
- BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
- this._cam_axisY.normalize();
- this._cam_axisX.normalize();
- this._cam_axisZ.normalize();
- }
- BABYLON.Matrix.IdentityToRef(this._rotMatrix);
- var idx = 0;
- var index = 0;
- var colidx = 0;
- var colorIndex = 0;
- var uvidx = 0;
- var uvIndex = 0;
- if (this._computeBoundingBox) {
- BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
- BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
- }
- // particle loop
- end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
- for (var p = start; p <= end; p++) {
- this._particle = this.particles[p];
- this._shape = this._particle._model._shape;
- this._shapeUV = this._particle._model._shapeUV;
- // call to custom user function to update the particle properties
- this.updateParticle(this._particle);
- // particle rotation matrix
- if (this.billboard) {
- this._particle.rotation.x = 0.0;
- this._particle.rotation.y = 0.0;
- }
- if (this._computeParticleRotation) {
- if (this._particle.rotationQuaternion) {
- this._quaternion.copyFrom(this._particle.rotationQuaternion);
- }
- else {
- this._yaw = this._particle.rotation.y;
- this._pitch = this._particle.rotation.x;
- this._roll = this._particle.rotation.z;
- this._quaternionRotationYPR();
- }
- this._quaternionToRotationMatrix();
- }
- for (var pt = 0; pt < this._shape.length; pt++) {
- idx = index + pt * 3;
- colidx = colorIndex + pt * 4;
- uvidx = uvIndex + pt * 2;
- this._vertex.x = this._shape[pt].x;
- this._vertex.y = this._shape[pt].y;
- this._vertex.z = this._shape[pt].z;
- if (this._computeParticleVertex) {
- this.updateParticleVertex(this._particle, this._vertex, pt);
- }
- // positions
- this._vertex.x *= this._particle.scaling.x;
- this._vertex.y *= this._particle.scaling.y;
- this._vertex.z *= this._particle.scaling.z;
- 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];
- 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;
- 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;
- 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;
- 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;
- 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;
- 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;
- if (this._computeBoundingBox) {
- if (this._positions32[idx] < this._minimum.x) {
- this._minimum.x = this._positions32[idx];
- }
- if (this._positions32[idx] > this._maximum.x) {
- this._maximum.x = this._positions32[idx];
- }
- if (this._positions32[idx + 1] < this._minimum.y) {
- this._minimum.y = this._positions32[idx + 1];
- }
- if (this._positions32[idx + 1] > this._maximum.y) {
- this._maximum.y = this._positions32[idx + 1];
- }
- if (this._positions32[idx + 2] < this._minimum.z) {
- this._minimum.z = this._positions32[idx + 2];
- }
- if (this._positions32[idx + 2] > this._maximum.z) {
- this._maximum.z = this._positions32[idx + 2];
- }
- }
- // normals : if the particles can't be morphed then just rotate the normals
- if (!this._computeParticleVertex && !this.billboard) {
- this._normal.x = this._fixedNormal32[idx];
- this._normal.y = this._fixedNormal32[idx + 1];
- this._normal.z = this._fixedNormal32[idx + 2];
- 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];
- 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;
- 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;
- 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;
- this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
- 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;
- 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;
- }
- if (this._computeParticleColor) {
- this._colors32[colidx] = this._particle.color.r;
- this._colors32[colidx + 1] = this._particle.color.g;
- this._colors32[colidx + 2] = this._particle.color.b;
- this._colors32[colidx + 3] = this._particle.color.a;
- }
- if (this._computeParticleTexture) {
- this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
- this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
- }
- }
- index = idx + 3;
- colorIndex = colidx + 4;
- uvIndex = uvidx + 2;
- }
- if (update) {
- if (this._computeParticleColor) {
- this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
- }
- if (this._computeParticleTexture) {
- this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
- }
- this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
- if (!this.mesh.areNormalsFrozen) {
- if (this._computeParticleVertex || this.billboard) {
- // recompute the normals only if the particles can be morphed, update then the normal reference array
- BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
- for (var i = 0; i < this._normals32.length; i++) {
- this._fixedNormal32[i] = this._normals32[i];
- }
- }
- this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
- }
- }
- if (this._computeBoundingBox) {
- this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
- this.mesh._boundingInfo.update(this.mesh._worldMatrix);
- }
- this.afterUpdateParticles(start, end, update);
- };
- SolidParticleSystem.prototype._quaternionRotationYPR = function () {
- this._halfroll = this._roll * 0.5;
- this._halfpitch = this._pitch * 0.5;
- this._halfyaw = this._yaw * 0.5;
- this._sinRoll = Math.sin(this._halfroll);
- this._cosRoll = Math.cos(this._halfroll);
- this._sinPitch = Math.sin(this._halfpitch);
- this._cosPitch = Math.cos(this._halfpitch);
- this._sinYaw = Math.sin(this._halfyaw);
- this._cosYaw = Math.cos(this._halfyaw);
- this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
- this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
- this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
- this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
- };
- SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
- this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
- this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
- this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
- this._rotMatrix.m[3] = 0;
- this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
- this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
- this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
- this._rotMatrix.m[7] = 0;
- this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
- this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
- this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
- this._rotMatrix.m[11] = 0;
- this._rotMatrix.m[12] = 0;
- this._rotMatrix.m[13] = 0;
- this._rotMatrix.m[14] = 0;
- this._rotMatrix.m[15] = 1.0;
- };
- /**
- * Disposes the SPS
- */
- SolidParticleSystem.prototype.dispose = function () {
- this.mesh.dispose();
- this.vars = null;
- // drop references to internal big arrays for the GC
- this._positions = null;
- this._indices = null;
- this._normals = null;
- this._uvs = null;
- this._colors = null;
- this._positions32 = null;
- this._normals32 = null;
- this._fixedNormal32 = null;
- this._uvs32 = null;
- this._colors32 = null;
- this.pickedParticles = null;
- };
- /**
- * Visibilty helper : Recomputes the visible size according to the mesh bounding box
- * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
- */
- SolidParticleSystem.prototype.refreshVisibleSize = function () {
- if (!this._isVisibilityBoxLocked) {
- this.mesh.refreshBoundingInfo();
- }
- };
- /**
- * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
- * @param size the size (float) of the visibility box
- * note : this doesn't lock the SPS mesh bounding box.
- * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
- */
- SolidParticleSystem.prototype.setVisibilityBox = function (size) {
- var vis = size / 2;
- this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
- };
- Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
- // getter and setter
- get: function () {
- return this._alwaysVisible;
- },
- /**
- * Sets the SPS as always visible or not
- * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
- */
- set: function (val) {
- this._alwaysVisible = val;
- this.mesh.alwaysSelectAsActiveMesh = val;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
- get: function () {
- return this._isVisibilityBoxLocked;
- },
- /**
- * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
- * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
- */
- set: function (val) {
- this._isVisibilityBoxLocked = val;
- this.mesh.getBoundingInfo().isLocked = val;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
- // getters
- get: function () {
- return this._computeParticleRotation;
- },
- // Optimizer setters
- /**
- * Tells to `setParticles()` to compute the particle rotations or not.
- * Default value : true. The SPS is faster when it's set to false.
- * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
- */
- set: function (val) {
- this._computeParticleRotation = val;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
- get: function () {
- return this._computeParticleColor;
- },
- /**
- * Tells to `setParticles()` to compute the particle colors or not.
- * Default value : true. The SPS is faster when it's set to false.
- * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
- */
- set: function (val) {
- this._computeParticleColor = val;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
- get: function () {
- return this._computeParticleTexture;
- },
- /**
- * Tells to `setParticles()` to compute the particle textures or not.
- * Default value : true. The SPS is faster when it's set to false.
- * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
- */
- set: function (val) {
- this._computeParticleTexture = val;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
- get: function () {
- return this._computeParticleVertex;
- },
- /**
- * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
- * Default value : false. The SPS is faster when it's set to false.
- * Note : the particle custom vertex positions aren't stored values.
- */
- set: function (val) {
- this._computeParticleVertex = val;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
- get: function () {
- return this._computeBoundingBox;
- },
- /**
- * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
- */
- set: function (val) {
- this._computeBoundingBox = val;
- },
- enumerable: true,
- configurable: true
- });
- // =======================================================================
- // Particle behavior logic
- // these following methods may be overwritten by the user to fit his needs
- /**
- * This function does nothing. It may be overwritten to set all the particle first values.
- * The SPS doesn't call this function, you may have to call it by your own.
- * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
- */
- SolidParticleSystem.prototype.initParticles = function () {
- };
- /**
- * This function does nothing. It may be overwritten to recycle a particle.
- * The SPS doesn't call this function, you may have to call it by your own.
- * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
- */
- SolidParticleSystem.prototype.recycleParticle = function (particle) {
- return particle;
- };
- /**
- * Updates a particle : this function should be overwritten by the user.
- * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
- * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
- * ex : just set a particle position or velocity and recycle conditions
- */
- SolidParticleSystem.prototype.updateParticle = function (particle) {
- return particle;
- };
- /**
- * Updates a vertex of a particle : it can be overwritten by the user.
- * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
- * @param particle the current particle
- * @param vertex the current index of the current particle
- * @param pt the index of the current vertex in the particle shape
- * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#update-each-particle-shape
- * ex : just set a vertex particle position
- */
- SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
- return vertex;
- };
- /**
- * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
- * This does nothing and may be overwritten by the user.
- * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
- * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
- * @param update the boolean update value actually passed to setParticles()
- */
- SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
- };
- /**
- * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
- * This will be passed three parameters.
- * This does nothing and may be overwritten by the user.
- * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
- * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
- * @param update the boolean update value actually passed to setParticles()
- */
- SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
- };
- return SolidParticleSystem;
- })();
- BABYLON.SolidParticleSystem = SolidParticleSystem;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Internals;
- (function (Internals) {
- var FileFaceOrientation = (function () {
- function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
- this.name = name;
- this.worldAxisForNormal = worldAxisForNormal;
- this.worldAxisForFileX = worldAxisForFileX;
- this.worldAxisForFileY = worldAxisForFileY;
- }
- return FileFaceOrientation;
- })();
- ;
- /**
- * Helper class dealing with the extraction of spherical polynomial dataArray
- * from a cube map.
- */
- var CubeMapToSphericalPolynomialTools = (function () {
- function CubeMapToSphericalPolynomialTools() {
- }
- /**
- * Converts a cubemap to the according Spherical Polynomial data.
- * This extracts the first 3 orders only as they are the only one used in the lighting.
- *
- * @param cubeInfo The Cube map to extract the information from.
- * @return The Spherical Polynomial data.
- */
- CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
- var sphericalHarmonics = new BABYLON.SphericalHarmonics();
- var totalSolidAngle = 0.0;
- // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
- var du = 2.0 / cubeInfo.size;
- var dv = du;
- // The (u,v) of the first texel is half a texel from the corner (-1,-1).
- var minUV = du * 0.5 - 1.0;
- for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
- var fileFace = this.FileFaces[faceIndex];
- var dataArray = cubeInfo[fileFace.name];
- var v = minUV;
- // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
- // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
- // Because SP is still linear, so summation is fine in that basis.
- for (var y = 0; y < cubeInfo.size; y++) {
- var u = minUV;
- for (var x = 0; x < cubeInfo.size; x++) {
- // World direction (not normalised)
- var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
- worldDirection.normalize();
- var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
- if (1) {
- var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
- var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
- var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
- var color = new BABYLON.Color3(r, g, b);
- sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
- }
- else {
- if (faceIndex == 0) {
- dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
- dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
- dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
- }
- else if (faceIndex == 1) {
- dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
- dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
- dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
- }
- else if (faceIndex == 2) {
- dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
- dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
- dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
- }
- else if (faceIndex == 3) {
- dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
- dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
- dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
- }
- else if (faceIndex == 4) {
- dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
- dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
- dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
- }
- else if (faceIndex == 5) {
- dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
- dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
- dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
- }
- 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]);
- sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
- }
- totalSolidAngle += deltaSolidAngle;
- u += du;
- }
- v += dv;
- }
- }
- var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
- var correction = correctSolidAngle / totalSolidAngle;
- sphericalHarmonics.scale(correction);
- // Additionally scale by pi -- audit needed
- sphericalHarmonics.scale(1.0 / Math.PI);
- return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
- };
- CubeMapToSphericalPolynomialTools.FileFaces = [
- new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
- new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
- new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
- new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
- new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
- new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
- ];
- return CubeMapToSphericalPolynomialTools;
- })();
- Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
- })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Internals;
- (function (Internals) {
- /**
- * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
- */
- var PanoramaToCubeMapTools = (function () {
- function PanoramaToCubeMapTools() {
- }
- /**
- * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
- *
- * @param float32Array The source data.
- * @param inputWidth The width of the input panorama.
- * @param inputhHeight The height of the input panorama.
- * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
- * @return The cubemap data
- */
- PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
- if (!float32Array) {
- throw "ConvertPanoramaToCubemap: input cannot be null";
- }
- if (float32Array.length != inputWidth * inputHeight * 3) {
- throw "ConvertPanoramaToCubemap: input size is wrong";
- }
- var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
- var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
- var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
- var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
- var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
- var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
- return {
- front: textureFront,
- back: textureBack,
- left: textureLeft,
- right: textureRight,
- up: textureUp,
- down: textureDown,
- size: size
- };
- };
- PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
- var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
- var textureArray = new Float32Array(buffer);
- var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
- var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
- var dy = 1 / texSize;
- var fy = 0;
- for (var y = 0; y < texSize; y++) {
- var xv1 = faceData[0];
- var xv2 = faceData[2];
- for (var x = 0; x < texSize; x++) {
- var v = xv2.subtract(xv1).scale(fy).add(xv1);
- v.normalize();
- var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
- // 3 channels per pixels
- textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
- textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
- textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
- xv1 = xv1.add(rotDX1);
- xv2 = xv2.add(rotDX2);
- }
- fy += dy;
- }
- return textureArray;
- };
- PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
- var theta = Math.atan2(vDir.z, vDir.x);
- var phi = Math.acos(vDir.y);
- while (theta < -Math.PI)
- theta += 2 * Math.PI;
- while (theta > Math.PI)
- theta -= 2 * Math.PI;
- var dx = theta / Math.PI;
- var dy = phi / Math.PI;
- // recenter.
- dx = dx * 0.5 + 0.5;
- var px = Math.round(dx * inputWidth);
- if (px < 0)
- px = 0;
- else if (px >= inputWidth)
- px = inputWidth - 1;
- var py = Math.round(dy * inputHeight);
- if (py < 0)
- py = 0;
- else if (py >= inputHeight)
- py = inputHeight - 1;
- var inputY = (inputHeight - py - 1);
- var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
- var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
- var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
- return {
- r: r,
- g: g,
- b: b
- };
- };
- PanoramaToCubeMapTools.FACE_FRONT = [
- new BABYLON.Vector3(-1.0, -1.0, -1.0),
- new BABYLON.Vector3(1.0, -1.0, -1.0),
- new BABYLON.Vector3(-1.0, 1.0, -1.0),
- new BABYLON.Vector3(1.0, 1.0, -1.0)
- ];
- PanoramaToCubeMapTools.FACE_BACK = [
- new BABYLON.Vector3(1.0, -1.0, 1.0),
- new BABYLON.Vector3(-1.0, -1.0, 1.0),
- new BABYLON.Vector3(1.0, 1.0, 1.0),
- new BABYLON.Vector3(-1.0, 1.0, 1.0)
- ];
- PanoramaToCubeMapTools.FACE_RIGHT = [
- new BABYLON.Vector3(1.0, -1.0, -1.0),
- new BABYLON.Vector3(1.0, -1.0, 1.0),
- new BABYLON.Vector3(1.0, 1.0, -1.0),
- new BABYLON.Vector3(1.0, 1.0, 1.0)
- ];
- PanoramaToCubeMapTools.FACE_LEFT = [
- new BABYLON.Vector3(-1.0, -1.0, 1.0),
- new BABYLON.Vector3(-1.0, -1.0, -1.0),
- new BABYLON.Vector3(-1.0, 1.0, 1.0),
- new BABYLON.Vector3(-1.0, 1.0, -1.0)
- ];
- PanoramaToCubeMapTools.FACE_DOWN = [
- new BABYLON.Vector3(-1.0, 1.0, -1.0),
- new BABYLON.Vector3(1.0, 1.0, -1.0),
- new BABYLON.Vector3(-1.0, 1.0, 1.0),
- new BABYLON.Vector3(1.0, 1.0, 1.0)
- ];
- PanoramaToCubeMapTools.FACE_UP = [
- new BABYLON.Vector3(-1.0, -1.0, 1.0),
- new BABYLON.Vector3(1.0, -1.0, 1.0),
- new BABYLON.Vector3(-1.0, -1.0, -1.0),
- new BABYLON.Vector3(1.0, -1.0, -1.0)
- ];
- return PanoramaToCubeMapTools;
- })();
- Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
- })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Internals;
- (function (Internals) {
- ;
- /**
- * This groups tools to convert HDR texture to native colors array.
- */
- var HDRTools = (function () {
- function HDRTools() {
- }
- HDRTools.Ldexp = function (mantissa, exponent) {
- if (exponent > 1023) {
- return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
- }
- if (exponent < -1074) {
- return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
- }
- return mantissa * Math.pow(2, exponent);
- };
- HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
- if (exponent > 0) {
- exponent = this.Ldexp(1.0, exponent - (128 + 8));
- float32array[index + 0] = red * exponent;
- float32array[index + 1] = green * exponent;
- float32array[index + 2] = blue * exponent;
- }
- else {
- float32array[index + 0] = 0;
- float32array[index + 1] = 0;
- float32array[index + 2] = 0;
- }
- };
- HDRTools.readStringLine = function (uint8array, startIndex) {
- var line = "";
- var character = "";
- for (var i = startIndex; i < uint8array.length - startIndex; i++) {
- character = String.fromCharCode(uint8array[i]);
- if (character == "\n") {
- break;
- }
- line += character;
- }
- return line;
- };
- /**
- * Reads header information from an RGBE texture stored in a native array.
- * More information on this format are available here:
- * https://en.wikipedia.org/wiki/RGBE_image_format
- *
- * @param uint8array The binary file stored in native array.
- * @return The header information.
- */
- HDRTools.RGBE_ReadHeader = function (uint8array) {
- var height = 0;
- var width = 0;
- var line = this.readStringLine(uint8array, 0);
- if (line[0] != '#' || line[1] != '?') {
- throw "Bad HDR Format.";
- }
- var endOfHeader = false;
- var findFormat = false;
- var lineIndex = 0;
- do {
- lineIndex += (line.length + 1);
- line = this.readStringLine(uint8array, lineIndex);
- if (line == "FORMAT=32-bit_rle_rgbe") {
- findFormat = true;
- }
- else if (line.length == 0) {
- endOfHeader = true;
- }
- } while (!endOfHeader);
- if (!findFormat) {
- throw "HDR Bad header format, unsupported FORMAT";
- }
- lineIndex += (line.length + 1);
- line = this.readStringLine(uint8array, lineIndex);
- var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
- var match = sizeRegexp.exec(line);
- // TODO. Support +Y and -X if needed.
- if (match.length < 3) {
- throw "HDR Bad header format, no size";
- }
- width = parseInt(match[2]);
- height = parseInt(match[1]);
- if (width < 8 || width > 0x7fff) {
- throw "HDR Bad header format, unsupported size";
- }
- lineIndex += (line.length + 1);
- return {
- height: height,
- width: width,
- dataPosition: lineIndex
- };
- };
- /**
- * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
- * This RGBE texture needs to store the information as a panorama.
- *
- * More information on this format are available here:
- * https://en.wikipedia.org/wiki/RGBE_image_format
- *
- * @param buffer The binary file stored in an array buffer.
- * @param size The expected size of the extracted cubemap.
- * @return The Cube Map information.
- */
- HDRTools.GetCubeMapTextureData = function (buffer, size) {
- var uint8array = new Uint8Array(buffer);
- var hdrInfo = this.RGBE_ReadHeader(uint8array);
- var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
- var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
- return cubeMapData;
- };
- /**
- * Returns the pixels data extracted from an RGBE texture.
- * This pixels will be stored left to right up to down in the R G B order in one array.
- *
- * More information on this format are available here:
- * https://en.wikipedia.org/wiki/RGBE_image_format
- *
- * @param uint8array The binary file stored in an array buffer.
- * @param hdrInfo The header information of the file.
- * @return The pixels data in RGB right to left up to down order.
- */
- HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
- // Keep for multi format supports.
- return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
- };
- HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
- var num_scanlines = hdrInfo.height;
- var scanline_width = hdrInfo.width;
- var a, b, c, d, count;
- var dataIndex = hdrInfo.dataPosition;
- var index = 0, endIndex = 0, i = 0;
- var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
- var scanLineArray = new Uint8Array(scanLineArrayBuffer);
- // 3 channels of 4 bytes per pixel in float.
- var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
- var resultArray = new Float32Array(resultBuffer);
- // read in each successive scanline
- while (num_scanlines > 0) {
- a = uint8array[dataIndex++];
- b = uint8array[dataIndex++];
- c = uint8array[dataIndex++];
- d = uint8array[dataIndex++];
- if (a != 2 || b != 2 || (c & 0x80)) {
- // this file is not run length encoded
- throw "HDR Bad header format, not RLE";
- }
- if (((c << 8) | d) != scanline_width) {
- throw "HDR Bad header format, wrong scan line width";
- }
- index = 0;
- // read each of the four channels for the scanline into the buffer
- for (i = 0; i < 4; i++) {
- endIndex = (i + 1) * scanline_width;
- while (index < endIndex) {
- a = uint8array[dataIndex++];
- b = uint8array[dataIndex++];
- if (a > 128) {
- // a run of the same value
- count = a - 128;
- if ((count == 0) || (count > endIndex - index)) {
- throw "HDR Bad Format, bad scanline data (run)";
- }
- while (count-- > 0) {
- scanLineArray[index++] = b;
- }
- }
- else {
- // a non-run
- count = a;
- if ((count == 0) || (count > endIndex - index)) {
- throw "HDR Bad Format, bad scanline data (non-run)";
- }
- scanLineArray[index++] = b;
- if (--count > 0) {
- for (var j = 0; j < count; j++) {
- scanLineArray[index++] = uint8array[dataIndex++];
- }
- }
- }
- }
- }
- // now convert data from buffer into floats
- for (i = 0; i < scanline_width; i++) {
- a = scanLineArray[i];
- b = scanLineArray[i + scanline_width];
- c = scanLineArray[i + 2 * scanline_width];
- d = scanLineArray[i + 3 * scanline_width];
- this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
- }
- num_scanlines--;
- }
- return resultArray;
- };
- return HDRTools;
- })();
- Internals.HDRTools = HDRTools;
- })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
- })(BABYLON || (BABYLON = {}));
- //_______________________________________________________________
- // Extracted from CubeMapGen:
- // https://code.google.com/archive/p/cubemapgen/
- //
- // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
- //_______________________________________________________________
- var BABYLON;
- (function (BABYLON) {
- var Internals;
- (function (Internals) {
- /**
- * The bounding box information used during the conversion process.
- */
- var CMGBoundinBox = (function () {
- function CMGBoundinBox() {
- this.min = new BABYLON.Vector3(0, 0, 0);
- this.max = new BABYLON.Vector3(0, 0, 0);
- this.clear();
- }
- CMGBoundinBox.prototype.clear = function () {
- this.min.x = CMGBoundinBox.MAX;
- this.min.y = CMGBoundinBox.MAX;
- this.min.z = CMGBoundinBox.MAX;
- this.max.x = CMGBoundinBox.MIN;
- this.max.y = CMGBoundinBox.MIN;
- this.max.z = CMGBoundinBox.MIN;
- };
- CMGBoundinBox.prototype.augment = function (x, y, z) {
- this.min.x = Math.min(this.min.x, x);
- this.min.y = Math.min(this.min.y, y);
- this.min.z = Math.min(this.min.z, z);
- this.max.x = Math.max(this.max.x, x);
- this.max.y = Math.max(this.max.y, y);
- this.max.z = Math.max(this.max.z, z);
- };
- CMGBoundinBox.prototype.clampMin = function (x, y, z) {
- this.min.x = Math.max(this.min.x, x);
- this.min.y = Math.max(this.min.y, y);
- this.min.z = Math.max(this.min.z, z);
- };
- CMGBoundinBox.prototype.clampMax = function (x, y, z) {
- this.max.x = Math.min(this.max.x, x);
- this.max.y = Math.min(this.max.y, y);
- this.max.z = Math.min(this.max.z, z);
- };
- CMGBoundinBox.prototype.empty = function () {
- if ((this.min.x > this.max.y) ||
- (this.min.y > this.max.y) ||
- (this.min.z > this.max.y)) {
- return true;
- }
- else {
- return false;
- }
- };
- CMGBoundinBox.MAX = Number.MAX_VALUE;
- CMGBoundinBox.MIN = Number.MIN_VALUE;
- return CMGBoundinBox;
- })();
- /**
- * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
- * required by the glossinees of a material.
- *
- * This only supports the cosine drop power as well as Warp fixup generation method.
- *
- * This is using the process from CubeMapGen described here:
- * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
- */
- var PMREMGenerator = (function () {
- /**
- * Constructor of the generator.
- *
- * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
- * @param inputSize The size of the cubemap faces
- * @param outputSize The size of the output cubemap faces
- * @param maxNumMipLevels The max number of mip map to generate (0 means all)
- * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
- * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
- * @param specularPower The max specular level of the desired cubemap
- * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
- * @param excludeBase Specifies wether to process the level 0 (original level) or not
- * @param fixup Specifies wether to apply the edge fixup algorythm or not
- */
- function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
- this.input = input;
- this.inputSize = inputSize;
- this.outputSize = outputSize;
- this.maxNumMipLevels = maxNumMipLevels;
- this.numChannels = numChannels;
- this.isFloat = isFloat;
- this.specularPower = specularPower;
- this.cosinePowerDropPerMip = cosinePowerDropPerMip;
- this.excludeBase = excludeBase;
- this.fixup = fixup;
- this._outputSurface = [];
- this._numMipLevels = 0;
- }
- /**
- * Launches the filter process and return the result.
- *
- * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
- */
- PMREMGenerator.prototype.filterCubeMap = function () {
- // Init cubemap processor
- this.init();
- // Filters the cubemap
- this.filterCubeMapMipChain();
- // Returns the filtered mips.
- return this._outputSurface;
- };
- PMREMGenerator.prototype.init = function () {
- var i;
- var j;
- var mipLevelSize;
- //if nax num mip levels is set to 0, set it to generate the entire mip chain
- if (this.maxNumMipLevels == 0) {
- this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
- }
- //first miplevel size
- mipLevelSize = this.outputSize;
- //Iterate over mip chain, and init ArrayBufferView for mip-chain
- for (j = 0; j < this.maxNumMipLevels; j++) {
- this._outputSurface.length++;
- this._outputSurface[j] = [];
- //Iterate over faces for output images
- for (i = 0; i < 6; i++) {
- this._outputSurface[j].length++;
- // Initializes a new array for the output.
- if (this.isFloat) {
- this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
- }
- else {
- this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
- }
- }
- //next mip level is half size
- mipLevelSize >>= 1;
- this._numMipLevels++;
- //terminate if mip chain becomes too small
- if (mipLevelSize == 0) {
- this.maxNumMipLevels = j;
- return;
- }
- }
- };
- //--------------------------------------------------------------------------------------
- //Cube map filtering and mip chain generation.
- // the cube map filtereing is specified using a number of parameters:
- // Filtering per miplevel is specified using 2D cone angle (in degrees) that
- // indicates the region of the hemisphere to filter over for each tap.
- //
- // Note that the top mip level is also a filtered version of the original input images
- // as well in order to create mip chains for diffuse environment illumination.
- // The cone angle for the top level is specified by a_BaseAngle. This can be used to
- // generate mipchains used to store the resutls of preintegration across the hemisphere.
- //
- // Then the mip angle used to genreate the next level of the mip chain from the first level
- // is a_InitialMipAngle
- //
- // The angle for the subsequent levels of the mip chain are specified by their parents
- // filtering angle and a per-level scale and bias
- // newAngle = oldAngle * a_MipAnglePerLevelScale;
- //
- //--------------------------------------------------------------------------------------
- PMREMGenerator.prototype.filterCubeMapMipChain = function () {
- // First, take count of the lighting model to modify SpecularPower
- // 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;
- // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
- //Cone angle start (for generating subsequent mip levels)
- var currentSpecularPower = this.specularPower;
- //Build filter lookup tables based on the source miplevel size
- this.precomputeFilterLookupTables(this.inputSize);
- // Note that we need to filter the first level before generating mipmap
- // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
- for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
- // TODO : Write a function to copy and scale the base mipmap in output
- // I am just lazy here and just put a high specular power value, and do some if.
- if (this.excludeBase && (levelIndex == 0)) {
- // 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).
- currentSpecularPower = 100000.0;
- }
- // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
- var srcCubeImage = this.input;
- var dstCubeImage = this._outputSurface[levelIndex];
- var dstSize = this.outputSize >> levelIndex;
- // Compute required angle.
- var angle = this.getBaseFilterAngle(currentSpecularPower);
- // filter cube surfaces
- this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
- // fix seams
- if (this.fixup) {
- this.fixupCubeEdges(dstCubeImage, dstSize);
- }
- // Decrease the specular power to generate the mipmap chain
- // TODO : Use another method for Exclude (see first comment at start of the function
- if (this.excludeBase && (levelIndex == 0)) {
- currentSpecularPower = this.specularPower;
- }
- currentSpecularPower *= this.cosinePowerDropPerMip;
- }
- };
- //--------------------------------------------------------------------------------------
- // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
- // It allow to optimize the texel to access base on the specular power.
- //--------------------------------------------------------------------------------------
- PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
- // We want to find the alpha such that:
- // cos(alpha)^cosinePower = epsilon
- // That's: acos(epsilon^(1/cosinePower))
- var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
- var angle = 180.0;
- angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
- angle *= 180.0 / Math.PI; // Convert to degree
- angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
- return angle;
- };
- //--------------------------------------------------------------------------------------
- //Builds the following lookup tables prior to filtering:
- // -normalizer cube map
- // -tap weight lookup table
- //
- //--------------------------------------------------------------------------------------
- PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
- var srcTexelAngle;
- var iCubeFace;
- //clear pre-existing normalizer cube map
- this._normCubeMap = [];
- //Normalized vectors per cubeface and per-texel solid angle
- this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
- };
- //--------------------------------------------------------------------------------------
- //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
- //
- //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
- //
- //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
- // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
- // below
- //--------------------------------------------------------------------------------------
- PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
- var iCubeFace;
- var u;
- var v;
- //iterate over cube faces
- for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
- //First three channels for norm cube, and last channel for solid angle
- this._normCubeMap.push(new Float32Array(size * size * 4));
- //fast texture walk, build normalizer cube map
- var facesData = this.input[iCubeFace];
- for (v = 0; v < size; v++) {
- for (u = 0; u < size; u++) {
- var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
- this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
- this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
- this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
- var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
- this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
- }
- }
- }
- };
- //--------------------------------------------------------------------------------------
- // Convert cubemap face texel coordinates and face idx to 3D vector
- // note the U and V coords are integer coords and range from 0 to size-1
- // this routine can be used to generate a normalizer cube map
- //--------------------------------------------------------------------------------------
- // SL BEGIN
- PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
- var nvcU;
- var nvcV;
- var tempVec;
- // Change from original AMD code
- // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
- // + 0.5f is for texel center addressing
- nvcU = (2.0 * (u + 0.5) / size) - 1.0;
- nvcV = (2.0 * (v + 0.5) / size) - 1.0;
- // warp fixup
- if (fixup && size > 1) {
- // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
- var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
- nvcU = a * Math.pow(nvcU, 3) + nvcU;
- nvcV = a * Math.pow(nvcV, 3) + nvcV;
- }
- // Get current vector
- // generate x,y,z vector (xform 2d NVC coord to 3D vector)
- // U contribution
- var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
- PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
- PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
- PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
- // V contribution and Sum
- var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
- PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
- PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
- PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
- //add face axis
- var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
- PMREMGenerator._vectorTemp.x += faceAxis[0];
- PMREMGenerator._vectorTemp.y += faceAxis[1];
- PMREMGenerator._vectorTemp.z += faceAxis[2];
- //normalize vector
- PMREMGenerator._vectorTemp.normalize();
- return PMREMGenerator._vectorTemp;
- };
- //--------------------------------------------------------------------------------------
- // Convert 3D vector to cubemap face texel coordinates and face idx
- // note the U and V coords are integer coords and range from 0 to size-1
- // this routine can be used to generate a normalizer cube map
- //
- // returns face IDX and texel coords
- //--------------------------------------------------------------------------------------
- // SL BEGIN
- /*
- Mapping Texture Coordinates to Cube Map Faces
- Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
- is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
- designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
- map arrangement in Pixar's RenderMan package.
- For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
- emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
- without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
- selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
- the major axis direction). The target column in the table below explains how the major axis direction
- maps to the 2D image of a particular cube map target.
-
- major axis
- direction target sc tc ma
- ---------- --------------------------------- --- --- ---
- +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
- -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
- +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
- -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
- +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
- -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
-
- Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
- an updated (s,t) is calculated as follows
- s = ( sc/|ma| + 1 ) / 2
- t = ( tc/|ma| + 1 ) / 2
- If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
- (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
- set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
- */
- // Note this method return U and V in range from 0 to size-1
- // SL END
- // Store the information in vector3 for convenience (faceindex, u, v)
- PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
- var maxCoord;
- var faceIdx;
- //absolute value 3
- var absX = Math.abs(x);
- var absY = Math.abs(y);
- var absZ = Math.abs(z);
- if (absX >= absY && absX >= absZ) {
- maxCoord = absX;
- if (x >= 0) {
- faceIdx = PMREMGenerator.CP_FACE_X_POS;
- }
- else {
- faceIdx = PMREMGenerator.CP_FACE_X_NEG;
- }
- }
- else if (absY >= absX && absY >= absZ) {
- maxCoord = absY;
- if (y >= 0) {
- faceIdx = PMREMGenerator.CP_FACE_Y_POS;
- }
- else {
- faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
- }
- }
- else {
- maxCoord = absZ;
- if (z >= 0) {
- faceIdx = PMREMGenerator.CP_FACE_Z_POS;
- }
- else {
- faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
- }
- }
- //divide through by max coord so face vector lies on cube face
- var scale = 1 / maxCoord;
- x *= scale;
- y *= scale;
- z *= scale;
- var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
- var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
- temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
- var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
- // Modify original AMD code to return value from 0 to Size - 1
- var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
- var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
- PMREMGenerator._vectorTemp.x = faceIdx;
- PMREMGenerator._vectorTemp.y = u;
- PMREMGenerator._vectorTemp.z = v;
- return PMREMGenerator._vectorTemp;
- };
- //--------------------------------------------------------------------------------------
- //Original code from Ignacio CastaÒo
- // This formula is from Manne ÷hrstrˆm's thesis.
- // Take two coordiantes in the range [-1, 1] that define a portion of a
- // cube face and return the area of the projection of that portion on the
- // surface of the sphere.
- //--------------------------------------------------------------------------------------
- PMREMGenerator.prototype.areaElement = function (x, y) {
- return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
- };
- PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
- // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
- // (+ 0.5f is for texel center addressing)
- u = (2.0 * (u + 0.5) / size) - 1.0;
- v = (2.0 * (v + 0.5) / size) - 1.0;
- // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
- var invResolution = 1.0 / size;
- // U and V are the -1..1 texture coordinate on the current face.
- // Get projected area for this texel
- var x0 = u - invResolution;
- var y0 = v - invResolution;
- var x1 = u + invResolution;
- var y1 = v + invResolution;
- var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
- return solidAngle;
- };
- //--------------------------------------------------------------------------------------
- //The key to the speed of these filtering routines is to quickly define a per-face
- // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
- // Later these pixels are selectively processed based on their dot products to see if
- // they reside within the filtering cone.
- //
- //This is done by computing the smallest per-texel angle to get a conservative estimate
- // of the number of texels needed to be covered in width and height order to filter the
- // region. the bounding box for the center taps face is defined first, and if the
- // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
- // defined next
- //--------------------------------------------------------------------------------------
- PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
- // note that pixels within these regions may be rejected
- // based on the anlge
- var iCubeFace;
- var u;
- var v;
- // bounding box per face to specify region to process
- var filterExtents = [];
- for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
- filterExtents.push(new CMGBoundinBox());
- }
- // min angle a src texel can cover (in degrees)
- var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
- // angle about center tap to define filter cone
- // filter angle is 1/2 the cone angle
- var filterAngle = filterConeAngle / 2.0;
- //ensure filter angle is larger than a texel
- if (filterAngle < srcTexelAngle) {
- filterAngle = srcTexelAngle;
- }
- //ensure filter cone is always smaller than the hemisphere
- if (filterAngle > 90.0) {
- filterAngle = 90.0;
- }
- // the maximum number of texels in 1D the filter cone angle will cover
- // used to determine bounding box size for filter extents
- var filterSize = Math.ceil(filterAngle / srcTexelAngle);
- // ensure conservative region always covers at least one texel
- if (filterSize < 1) {
- filterSize = 1;
- }
- // dotProdThresh threshold based on cone angle to determine whether or not taps
- // reside within the cone angle
- var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
- // process required faces
- for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
- //iterate over dst cube map face texel
- for (v = 0; v < dstSize; v++) {
- for (u = 0; u < dstSize; u++) {
- //get center tap direction
- var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
- //clear old per-face filter extents
- this.clearFilterExtents(filterExtents);
- //define per-face filter extents
- this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
- //perform filtering of src faces using filter extents
- var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
- dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
- dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
- dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
- }
- }
- }
- };
- //--------------------------------------------------------------------------------------
- //Clear filter extents for the 6 cube map faces
- //--------------------------------------------------------------------------------------
- PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
- for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
- filterExtents[iCubeFaces].clear();
- }
- };
- //--------------------------------------------------------------------------------------
- //Define per-face bounding box filter extents
- //
- // These define conservative texel regions in each of the faces the filter can possibly
- // process. When the pixels in the regions are actually processed, the dot product
- // between the tap vector and the center tap vector is used to determine the weight of
- // the tap and whether or not the tap is within the cone.
- //
- //--------------------------------------------------------------------------------------
- PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
- //neighboring face and bleed over amount, and width of BBOX for
- // left, right, top, and bottom edges of this face
- var bleedOverAmount = [0, 0, 0, 0];
- var bleedOverBBoxMin = [0, 0, 0, 0];
- var bleedOverBBoxMax = [0, 0, 0, 0];
- var neighborFace;
- var neighborEdge;
- var oppositeFaceIdx;
- //get face idx, and u, v info from center tap dir
- var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
- var faceIdx = result.x;
- var u = result.y;
- var v = result.z;
- //define bbox size within face
- filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
- filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
- filterExtents[faceIdx].clampMin(0, 0, 0);
- filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
- //u and v extent in face corresponding to center tap
- var minU = filterExtents[faceIdx].min.x;
- var minV = filterExtents[faceIdx].min.y;
- var maxU = filterExtents[faceIdx].max.x;
- var maxV = filterExtents[faceIdx].max.y;
- //bleed over amounts for face across u=0 edge (left)
- bleedOverAmount[0] = (bboxSize - u);
- bleedOverBBoxMin[0] = minV;
- bleedOverBBoxMax[0] = maxV;
- //bleed over amounts for face across u=1 edge (right)
- bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
- bleedOverBBoxMin[1] = minV;
- bleedOverBBoxMax[1] = maxV;
- //bleed over to face across v=0 edge (up)
- bleedOverAmount[2] = (bboxSize - v);
- bleedOverBBoxMin[2] = minU;
- bleedOverBBoxMax[2] = maxU;
- //bleed over to face across v=1 edge (down)
- bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
- bleedOverBBoxMin[3] = minU;
- bleedOverBBoxMax[3] = maxU;
- //compute bleed over regions in neighboring faces
- for (var i = 0; i < 4; i++) {
- if (bleedOverAmount[i] > 0) {
- neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
- neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
- //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
- // be flipped: the cases are
- // if a left edge mates with a left or bottom edge on the neighbor
- // if a top edge mates with a top or right edge on the neighbor
- // if a right edge mates with a right or top edge on the neighbor
- // if a bottom edge mates with a bottom or left edge on the neighbor
- //Seeing as the edges are enumerated as follows
- // left =0
- // right =1
- // top =2
- // bottom =3
- //
- // so if the edge enums are the same, or the sum of the enums == 3,
- // the bbox needs to be flipped
- if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
- bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
- bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
- }
- //The way the bounding box is extended onto the neighboring face
- // depends on which edge of neighboring face abuts with this one
- switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
- case PMREMGenerator.CP_EDGE_LEFT:
- filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
- filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
- break;
- case PMREMGenerator.CP_EDGE_RIGHT:
- filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
- filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
- break;
- case PMREMGenerator.CP_EDGE_TOP:
- filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
- filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
- break;
- case PMREMGenerator.CP_EDGE_BOTTOM:
- filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
- filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
- break;
- }
- //clamp filter extents in non-center tap faces to remain within surface
- filterExtents[neighborFace].clampMin(0, 0, 0);
- filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
- }
- //If the bleed over amount bleeds past the adjacent face onto the opposite face
- // from the center tap face, then process the opposite face entirely for now.
- //Note that the cases in which this happens, what usually happens is that
- // more than one edge bleeds onto the opposite face, and the bounding box
- // encompasses the entire cube map face.
- if (bleedOverAmount[i] > srcSize) {
- //determine opposite face
- switch (faceIdx) {
- case PMREMGenerator.CP_FACE_X_POS:
- oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
- break;
- case PMREMGenerator.CP_FACE_X_NEG:
- oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
- break;
- case PMREMGenerator.CP_FACE_Y_POS:
- oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
- break;
- case PMREMGenerator.CP_FACE_Y_NEG:
- oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
- break;
- case PMREMGenerator.CP_FACE_Z_POS:
- oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
- break;
- case PMREMGenerator.CP_FACE_Z_NEG:
- oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
- break;
- default:
- break;
- }
- //just encompass entire face for now
- filterExtents[oppositeFaceIdx].augment(0, 0, 0);
- filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
- }
- }
- };
- //--------------------------------------------------------------------------------------
- //ProcessFilterExtents
- // Process bounding box in each cube face
- //
- //--------------------------------------------------------------------------------------
- PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
- //accumulators are 64-bit floats in order to have the precision needed
- // over a summation of a large number of pixels
- var dstAccum = [0, 0, 0, 0];
- var weightAccum = 0;
- var k = 0;
- var nSrcChannels = this.numChannels;
- // norm cube map and srcCubeMap have same face width
- var faceWidth = srcSize;
- //amount to add to pointer to move to next scanline in images
- var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
- var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
- var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
- //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
- // iterate over cubefaces
- for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
- //if bbox is non empty
- if (!filterExtents[iFaceIdx].empty()) {
- var uStart = filterExtents[iFaceIdx].min.x;
- var vStart = filterExtents[iFaceIdx].min.y;
- var uEnd = filterExtents[iFaceIdx].max.x;
- var vEnd = filterExtents[iFaceIdx].max.y;
- var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
- var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
- //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
- for (var v = vStart; v <= vEnd; v++) {
- var normCubeRowWalk = 0;
- var srcCubeRowWalk = 0;
- for (var u = uStart; u <= uEnd; u++) {
- //pointer to direction in cube map associated with texel
- var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
- var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
- var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
- //check dot product to see if texel is within cone
- var tapDotProd = texelVectX * centerTapDir.x +
- texelVectY * centerTapDir.y +
- texelVectZ * centerTapDir.z;
- if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
- //solid angle stored in 4th channel of normalizer/solid angle cube map
- var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
- // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
- // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
- // so just adding one to specularpower do the trick.
- weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
- //iterate over channels
- for (k = 0; k < nSrcChannels; k++) {
- dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
- srcCubeRowWalk++;
- }
- weightAccum += weight; //accumulate weight
- }
- else {
- //step across source pixel
- srcCubeRowWalk += nSrcChannels;
- }
- normCubeRowWalk += 4; // 4 channels per norm cube map.
- }
- startIndexNormCubeMap += normCubePitch;
- startIndexSrcCubeMap += srcCubePitch;
- }
- }
- }
- //divide through by weights if weight is non zero
- if (weightAccum != 0.0) {
- PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
- PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
- PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
- if (this.numChannels > 3) {
- PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
- }
- }
- else {
- // otherwise sample nearest
- // get face idx and u, v texel coordinate in face
- var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
- PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
- PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
- PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
- if (this.numChannels > 3) {
- PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
- }
- }
- return PMREMGenerator._vectorTemp;
- };
- //--------------------------------------------------------------------------------------
- // Fixup cube edges
- //
- // average texels on cube map faces across the edges
- // WARP/BENT Method Only.
- //--------------------------------------------------------------------------------------
- PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
- var k;
- var j;
- var i;
- var iFace;
- var iCorner = 0;
- var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
- var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
- // note that if functionality to filter across the three texels for each corner, then
- //indexed by corner and face idx. the array contains the face the start points belongs to.
- var cornerPtr = [
- [[], [], []],
- [[], [], []],
- [[], [], []],
- [[], [], []],
- [[], [], []],
- [[], [], []],
- [[], [], []],
- [[], [], []]
- ];
- //if there is no fixup, or fixup width = 0, do nothing
- if (cubeMapSize < 1) {
- return;
- }
- //special case 1x1 cubemap, average face colors
- if (cubeMapSize == 1) {
- //iterate over channels
- for (k = 0; k < this.numChannels; k++) {
- var accum = 0.0;
- //iterate over faces to accumulate face colors
- for (iFace = 0; iFace < 6; iFace++) {
- accum += cubeMap[iFace][k];
- }
- //compute average over 6 face colors
- accum /= 6.0;
- //iterate over faces to distribute face colors
- for (iFace = 0; iFace < 6; iFace++) {
- cubeMap[iFace][k] = accum;
- }
- }
- return;
- }
- //iterate over faces to collect list of corner texel pointers
- for (iFace = 0; iFace < 6; iFace++) {
- //the 4 corner pointers for this face
- faceCornerStartIndicies[0] = [iFace, 0];
- faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
- faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
- faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
- //iterate over face corners to collect cube corner pointers
- for (iCorner = 0; iCorner < 4; iCorner++) {
- var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
- cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
- cornerNumPtrs[corner]++;
- }
- }
- //iterate over corners to average across corner tap values
- for (iCorner = 0; iCorner < 8; iCorner++) {
- for (k = 0; k < this.numChannels; k++) {
- var cornerTapAccum = 0.0;
- //iterate over corner texels and average results
- for (i = 0; i < 3; i++) {
- cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
- }
- //divide by 3 to compute average of corner tap values
- cornerTapAccum *= (1.0 / 3.0);
- //iterate over corner texels and average results
- for (i = 0; i < 3; i++) {
- cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
- }
- }
- }
- //iterate over the twelve edges of the cube to average across edges
- for (i = 0; i < 12; i++) {
- var face = PMREMGenerator._sgCubeEdgeList[i][0];
- var edge = PMREMGenerator._sgCubeEdgeList[i][1];
- var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
- var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
- var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
- var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
- var edgeWalk = 0;
- var neighborEdgeWalk = 0;
- //Determine walking pointers based on edge type
- // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
- switch (edge) {
- case PMREMGenerator.CP_EDGE_LEFT:
- // no change to faceEdgeStartPtr
- edgeWalk = this.numChannels * cubeMapSize;
- break;
- case PMREMGenerator.CP_EDGE_RIGHT:
- edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
- edgeWalk = this.numChannels * cubeMapSize;
- break;
- case PMREMGenerator.CP_EDGE_TOP:
- // no change to faceEdgeStartPtr
- edgeWalk = this.numChannels;
- break;
- case PMREMGenerator.CP_EDGE_BOTTOM:
- edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
- edgeWalk = this.numChannels;
- break;
- }
- //For certain types of edge abutments, the neighbor edge walk needs to
- // be flipped: the cases are
- // if a left edge mates with a left or bottom edge on the neighbor
- // if a top edge mates with a top or right edge on the neighbor
- // if a right edge mates with a right or top edge on the neighbor
- // if a bottom edge mates with a bottom or left edge on the neighbor
- //Seeing as the edges are enumerated as follows
- // left =0
- // right =1
- // top =2
- // bottom =3
- //
- //If the edge enums are the same, or the sum of the enums == 3,
- // the neighbor edge walk needs to be flipped
- if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
- switch (neighborEdge) {
- case PMREMGenerator.CP_EDGE_LEFT:
- neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
- neighborEdgeWalk = -(this.numChannels * cubeMapSize);
- break;
- case PMREMGenerator.CP_EDGE_RIGHT:
- neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
- neighborEdgeWalk = -(this.numChannels * cubeMapSize);
- break;
- case PMREMGenerator.CP_EDGE_TOP:
- neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
- neighborEdgeWalk = -this.numChannels;
- break;
- case PMREMGenerator.CP_EDGE_BOTTOM:
- neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
- neighborEdgeWalk = -this.numChannels;
- break;
- }
- }
- else {
- //swapped direction neighbor edge walk
- switch (neighborEdge) {
- case PMREMGenerator.CP_EDGE_LEFT:
- //no change to neighborEdgeStartPtr for this case since it points
- // to the upper left corner already
- neighborEdgeWalk = this.numChannels * cubeMapSize;
- break;
- case PMREMGenerator.CP_EDGE_RIGHT:
- neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
- neighborEdgeWalk = this.numChannels * cubeMapSize;
- break;
- case PMREMGenerator.CP_EDGE_TOP:
- //no change to neighborEdgeStartPtr for this case since it points
- // to the upper left corner already
- neighborEdgeWalk = this.numChannels;
- break;
- case PMREMGenerator.CP_EDGE_BOTTOM:
- neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
- neighborEdgeWalk = this.numChannels;
- break;
- }
- }
- //Perform edge walk, to average across the 12 edges and smoothly propagate change to
- //nearby neighborhood
- //step ahead one texel on edge
- edgeStartIndex += edgeWalk;
- neighborEdgeStartIndex += neighborEdgeWalk;
- // note that this loop does not process the corner texels, since they have already been
- // averaged across faces across earlier
- for (j = 1; j < (cubeMapSize - 1); j++) {
- //for each set of taps along edge, average them
- // and rewrite the results into the edges
- for (k = 0; k < this.numChannels; k++) {
- var edgeTap = cubeMap[face][edgeStartIndex + k];
- var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
- //compute average of tap intensity values
- var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
- //propagate average of taps to edge taps
- cubeMap[face][edgeStartIndex + k] = avgTap;
- cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
- }
- edgeStartIndex += edgeWalk;
- neighborEdgeStartIndex += neighborEdgeWalk;
- }
- }
- };
- PMREMGenerator.CP_MAX_MIPLEVELS = 16;
- PMREMGenerator.CP_UDIR = 0;
- PMREMGenerator.CP_VDIR = 1;
- PMREMGenerator.CP_FACEAXIS = 2;
- //used to index cube faces
- PMREMGenerator.CP_FACE_X_POS = 0;
- PMREMGenerator.CP_FACE_X_NEG = 1;
- PMREMGenerator.CP_FACE_Y_POS = 2;
- PMREMGenerator.CP_FACE_Y_NEG = 3;
- PMREMGenerator.CP_FACE_Z_POS = 4;
- PMREMGenerator.CP_FACE_Z_NEG = 5;
- //used to index image edges
- // NOTE.. the actual number corresponding to the edge is important
- // do not change these, or the code will break
- //
- // CP_EDGE_LEFT is u = 0
- // CP_EDGE_RIGHT is u = width-1
- // CP_EDGE_TOP is v = 0
- // CP_EDGE_BOTTOM is v = height-1
- PMREMGenerator.CP_EDGE_LEFT = 0;
- PMREMGenerator.CP_EDGE_RIGHT = 1;
- PMREMGenerator.CP_EDGE_TOP = 2;
- PMREMGenerator.CP_EDGE_BOTTOM = 3;
- //corners of CUBE map (P or N specifys if it corresponds to the
- // positive or negative direction each of X, Y, and Z
- PMREMGenerator.CP_CORNER_NNN = 0;
- PMREMGenerator.CP_CORNER_NNP = 1;
- PMREMGenerator.CP_CORNER_NPN = 2;
- PMREMGenerator.CP_CORNER_NPP = 3;
- PMREMGenerator.CP_CORNER_PNN = 4;
- PMREMGenerator.CP_CORNER_PNP = 5;
- PMREMGenerator.CP_CORNER_PPN = 6;
- PMREMGenerator.CP_CORNER_PPP = 7;
- PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
- //3x2 matrices that map cube map indexing vectors in 3d
- // (after face selection and divide through by the
- // _ABSOLUTE VALUE_ of the max coord)
- // into NVC space
- //Note this currently assumes the D3D cube face ordering and orientation
- PMREMGenerator._sgFace2DMapping = [
- //XPOS face
- [[0, 0, -1],
- [0, -1, 0],
- [1, 0, 0]],
- //XNEG face
- [[0, 0, 1],
- [0, -1, 0],
- [-1, 0, 0]],
- //YPOS face
- [[1, 0, 0],
- [0, 0, 1],
- [0, 1, 0]],
- //YNEG face
- [[1, 0, 0],
- [0, 0, -1],
- [0, -1, 0]],
- //ZPOS face
- [[1, 0, 0],
- [0, -1, 0],
- [0, 0, 1]],
- //ZNEG face
- [[-1, 0, 0],
- [0, -1, 0],
- [0, 0, -1]],
- ];
- //------------------------------------------------------------------------------
- // D3D cube map face specification
- // mapping from 3D x,y,z cube map lookup coordinates
- // to 2D within face u,v coordinates
- //
- // --------------------> U direction
- // | (within-face texture space)
- // | _____
- // | | |
- // | | +Y |
- // | _____|_____|_____ _____
- // | | | | | |
- // | | -X | +Z | +X | -Z |
- // | |_____|_____|_____|_____|
- // | | |
- // | | -Y |
- // | |_____|
- // |
- // v V direction
- // (within-face texture space)
- //------------------------------------------------------------------------------
- //Information about neighbors and how texture coorrdinates change across faces
- // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
- // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
- //Note this currently assumes the D3D cube face ordering and orientation
- PMREMGenerator._sgCubeNgh = [
- //XPOS face
- [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
- [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
- [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
- [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
- //XNEG face
- [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
- [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
- [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
- [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
- //YPOS face
- [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
- [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
- [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
- [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
- //YNEG face
- [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
- [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
- [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
- [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
- //ZPOS face
- [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
- [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
- [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
- [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
- //ZNEG face
- [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
- [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
- [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
- [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
- ];
- //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
- // this table is used to average over the edges.
- PMREMGenerator._sgCubeEdgeList = [
- [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
- [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
- [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
- [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
- [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
- [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
- [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
- [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
- [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
- [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
- [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
- [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
- ];
- //Information about which of the 8 cube corners are correspond to the
- // the 4 corners in each cube face
- // the order is upper left, upper right, lower left, lower right
- PMREMGenerator._sgCubeCornerList = [
- [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
- [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
- [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
- [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
- [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
- [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
- ];
- return PMREMGenerator;
- })();
- Internals.PMREMGenerator = PMREMGenerator;
- })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- /**
- * This represents a texture coming from an HDR input.
- *
- * The only supported format is currently panorama picture stored in RGBE format.
- * Example of such files can be found on HDRLib: http://hdrlib.com/
- */
- var HDRCubeTexture = (function (_super) {
- __extends(HDRCubeTexture, _super);
- /**
- * Instantiates an HDRTexture from the following parameters.
- *
- * @param url The location of the HDR raw data (Panorama stored in RGBE format)
- * @param scene The scene the texture will be used in
- * @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.
- * @param noMipmap Forces to not generate the mipmap if true
- * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
- * @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)
- * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
- */
- function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
- if (noMipmap === void 0) { noMipmap = false; }
- if (generateHarmonics === void 0) { generateHarmonics = true; }
- if (useInGammaSpace === void 0) { useInGammaSpace = false; }
- if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
- _super.call(this, scene);
- this._useInGammaSpace = false;
- this._generateHarmonics = true;
- this._isBABYLONPreprocessed = false;
- /**
- * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
- */
- this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
- /**
- * The spherical polynomial data extracted from the texture.
- */
- this.sphericalPolynomial = null;
- /**
- * Specifies wether the texture has been generated through the PMREMGenerator tool.
- * This is usefull at run time to apply the good shader.
- */
- this.isPMREM = false;
- if (!url) {
- return;
- }
- this.name = url;
- this.url = url;
- this.hasAlpha = false;
- this.isCube = true;
- this._textureMatrix = BABYLON.Matrix.Identity();
- if (size) {
- this._isBABYLONPreprocessed = false;
- this._noMipmap = noMipmap;
- this._size = size;
- this._useInGammaSpace = useInGammaSpace;
- this._usePMREMGenerator = usePMREMGenerator && scene.getEngine().getCaps().textureLOD;
- }
- else {
- this._isBABYLONPreprocessed = true;
- this._noMipmap = false;
- this._useInGammaSpace = false;
- this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD;
- }
- this.isPMREM = this._usePMREMGenerator;
- this._texture = this._getFromCache(url, this._noMipmap);
- if (!this._texture) {
- if (!scene.useDelayedTextureLoading) {
- this.loadTexture();
- }
- else {
- this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
- }
- }
- }
- /**
- * Occurs when the file is a preprocessed .babylon.hdr file.
- */
- HDRCubeTexture.prototype.loadBabylonTexture = function () {
- var _this = this;
- var mipLevels = 0;
- var floatArrayView = null;
- var mipmapGenerator = function (data) {
- var mips = [];
- var startIndex = 30;
- for (var level = 0; level < mipLevels; level++) {
- mips.push([]);
- // Fill each pixel of the mip level.
- var faceSize = Math.pow(_this._size >> level, 2) * 3;
- for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
- var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
- mips[level].push(faceData);
- startIndex += faceSize;
- }
- }
- return mips;
- };
- var callback = function (buffer) {
- // Create Native Array Views
- var intArrayView = new Int32Array(buffer);
- floatArrayView = new Float32Array(buffer);
- // Fill header.
- var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
- _this._size = intArrayView[1]; // CubeMap max mip face size.
- // Update Texture Information.
- _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
- // Fill polynomial information.
- _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
- _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
- _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
- _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
- _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
- _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
- _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
- _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
- _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
- _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
- // Fill pixel data.
- mipLevels = intArrayView[29]; // Number of mip levels.
- var startIndex = 30;
- var data = [];
- var faceSize = Math.pow(_this._size, 2) * 3;
- for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
- data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
- }
- var results = [];
- var byteArray = null;
- // Create uintarray fallback.
- if (!_this.getScene().getEngine().getCaps().textureFloat) {
- // 3 channels of 1 bytes per pixel in bytes.
- var byteBuffer = new ArrayBuffer(faceSize);
- byteArray = new Uint8Array(byteBuffer);
- mipmapGenerator = null;
- }
- // Push each faces.
- for (var j = 0; j < 6; j++) {
- var dataFace = data[j];
- // If special cases.
- if (_this._useInGammaSpace || byteArray) {
- for (var i = 0; i < _this._size * _this._size; i++) {
- // Put in gamma space if requested.
- if (_this._useInGammaSpace) {
- dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
- dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
- dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
- }
- // Convert to int texture for fallback.
- if (byteArray) {
- // R
- byteArray[(i * 3) + 0] = dataFace[(i * 3) + 0] * 255;
- byteArray[(i * 3) + 0] = Math.min(255, byteArray[(i * 3) + 0]);
- // G
- byteArray[(i * 3) + 1] = dataFace[(i * 3) + 1] * 255;
- byteArray[(i * 3) + 1] = Math.min(255, byteArray[(i * 3) + 1]);
- // B
- byteArray[(i * 3) + 2] = dataFace[(i * 3) + 2] * 255;
- byteArray[(i * 3) + 2] = Math.min(255, byteArray[(i * 3) + 2]);
- }
- }
- }
- results.push(dataFace);
- }
- return results;
- };
- this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, BABYLON.Engine.TEXTURETYPE_FLOAT, this._noMipmap, callback, mipmapGenerator);
- };
- /**
- * Occurs when the file is raw .hdr file.
- */
- HDRCubeTexture.prototype.loadHDRTexture = function () {
- var _this = this;
- var callback = function (buffer) {
- // Extract the raw linear data.
- var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
- // Generate harmonics if needed.
- if (_this._generateHarmonics) {
- _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
- }
- var results = [];
- var byteArray = null;
- // Create uintarray fallback.
- if (!_this.getScene().getEngine().getCaps().textureFloat) {
- // 3 channels of 1 bytes per pixel in bytes.
- var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
- byteArray = new Uint8Array(byteBuffer);
- }
- // Push each faces.
- for (var j = 0; j < 6; j++) {
- var dataFace = data[HDRCubeTexture._facesMapping[j]];
- // If special cases.
- if (_this._useInGammaSpace || byteArray) {
- for (var i = 0; i < _this._size * _this._size; i++) {
- // Put in gamma space if requested.
- if (_this._useInGammaSpace) {
- dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
- dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
- dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
- }
- // Convert to int texture for fallback.
- if (byteArray) {
- // R
- byteArray[(i * 3) + 0] = dataFace[(i * 3) + 0] * 255;
- byteArray[(i * 3) + 0] = Math.min(255, byteArray[(i * 3) + 0]);
- // G
- byteArray[(i * 3) + 1] = dataFace[(i * 3) + 1] * 255;
- byteArray[(i * 3) + 1] = Math.min(255, byteArray[(i * 3) + 1]);
- // B
- byteArray[(i * 3) + 2] = dataFace[(i * 3) + 2] * 255;
- byteArray[(i * 3) + 2] = Math.min(255, byteArray[(i * 3) + 2]);
- }
- }
- }
- results.push(dataFace);
- }
- return results;
- };
- var mipmapGenerator = null;
- if (!this._noMipmap && this._usePMREMGenerator) {
- mipmapGenerator = function (data) {
- // Custom setup of the generator matching with the PBR shader values.
- var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
- return generator.filterCubeMap();
- };
- }
- this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, BABYLON.Engine.TEXTURETYPE_FLOAT, this._noMipmap, callback, mipmapGenerator);
- };
- /**
- * Starts the loading process of the texture.
- */
- HDRCubeTexture.prototype.loadTexture = function () {
- if (this._isBABYLONPreprocessed) {
- this.loadBabylonTexture();
- }
- else {
- this.loadHDRTexture();
- }
- };
- HDRCubeTexture.prototype.clone = function () {
- var size = this._isBABYLONPreprocessed ? null : this._size;
- var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
- // Base texture
- newTexture.level = this.level;
- newTexture.wrapU = this.wrapU;
- newTexture.wrapV = this.wrapV;
- newTexture.coordinatesIndex = this.coordinatesIndex;
- newTexture.coordinatesMode = this.coordinatesMode;
- return newTexture;
- };
- // Methods
- HDRCubeTexture.prototype.delayLoad = function () {
- if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
- return;
- }
- this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
- this._texture = this._getFromCache(this.url, this._noMipmap);
- if (!this._texture) {
- this.loadTexture();
- }
- };
- HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
- return this._textureMatrix;
- };
- HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
- var texture = null;
- if (parsedTexture.name && !parsedTexture.isRenderTarget) {
- var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
- texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
- texture.name = parsedTexture.name;
- texture.hasAlpha = parsedTexture.hasAlpha;
- texture.level = parsedTexture.level;
- texture.coordinatesMode = parsedTexture.coordinatesMode;
- }
- return texture;
- };
- HDRCubeTexture.prototype.serialize = function () {
- if (!this.name) {
- return null;
- }
- var serializationObject = {};
- serializationObject.name = this.name;
- serializationObject.hasAlpha = this.hasAlpha;
- serializationObject.isCube = true;
- serializationObject.level = this.level;
- serializationObject.size = this._size;
- serializationObject.coordinatesMode = this.coordinatesMode;
- serializationObject.useInGammaSpace = this._useInGammaSpace;
- serializationObject.generateHarmonics = this._generateHarmonics;
- serializationObject.usePMREMGenerator = this._usePMREMGenerator;
- serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
- return serializationObject;
- };
- /**
- * Saves as a file the data contained in the texture in a binary format.
- * This can be used to prevent the long loading tie associated with creating the seamless texture as well
- * as the spherical used in the lighting.
- * @param url The HDR file url.
- * @param size The size of the texture data to generate (one of the cubemap face desired width).
- * @param onError Method called if any error happens during download.
- * @return The packed binary data.
- */
- HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
- if (onError === void 0) { onError = null; }
- var callback = function (buffer) {
- var data = new Blob([buffer], { type: 'application/octet-stream' });
- // Returns a URL you can use as a href.
- var objUrl = window.URL.createObjectURL(data);
- // Simulates a link to it and click to dowload.
- var a = document.createElement("a");
- document.body.appendChild(a);
- a.style.display = "none";
- a.href = objUrl;
- a.download = "envmap.babylon.hdr";
- a.click();
- };
- HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
- };
- /**
- * Serializes the data contained in the texture in a binary format.
- * This can be used to prevent the long loading tie associated with creating the seamless texture as well
- * as the spherical used in the lighting.
- * @param url The HDR file url.
- * @param size The size of the texture data to generate (one of the cubemap face desired width).
- * @param onError Method called if any error happens during download.
- * @return The packed binary data.
- */
- HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
- if (onError === void 0) { onError = null; }
- // Needs the url tho create the texture.
- if (!url) {
- return null;
- }
- // Check Power of two size.
- if (!BABYLON.Tools.IsExponentOfTwo(size)) {
- return null;
- }
- var getDataCallback = function (dataBuffer) {
- // Extract the raw linear data.
- var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
- // Generate harmonics if needed.
- var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
- // Generate seamless faces
- var mipGeneratorArray = [];
- // Data are known to be in +X +Y +Z -X -Y -Z
- // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
- mipGeneratorArray.push(cubeData.right); // +X
- mipGeneratorArray.push(cubeData.left); // -X
- mipGeneratorArray.push(cubeData.up); // +Y
- mipGeneratorArray.push(cubeData.down); // -Y
- mipGeneratorArray.push(cubeData.front); // +Z
- mipGeneratorArray.push(cubeData.back); // -Z
- // Custom setup of the generator matching with the PBR shader values.
- var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
- var mippedData = generator.filterCubeMap();
- // Compute required byte length.
- var byteLength = 1 * 4; // Raw Data Version int32.
- byteLength += 4; // CubeMap max mip face size int32.
- byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
- // Add data size.
- byteLength += 4; // Number of mip levels int32.
- for (var level = 0; level < mippedData.length; level++) {
- var mipSize = size >> level;
- byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
- }
- // Prepare binary structure.
- var buffer = new ArrayBuffer(byteLength);
- var intArrayView = new Int32Array(buffer);
- var floatArrayView = new Float32Array(buffer);
- // Fill header.
- intArrayView[0] = 1; // Version 1.
- intArrayView[1] = size; // CubeMap max mip face size.
- // Fill polynomial information.
- sphericalPolynomial.x.toArray(floatArrayView, 2);
- sphericalPolynomial.y.toArray(floatArrayView, 5);
- sphericalPolynomial.z.toArray(floatArrayView, 8);
- sphericalPolynomial.xx.toArray(floatArrayView, 11);
- sphericalPolynomial.yy.toArray(floatArrayView, 14);
- sphericalPolynomial.zz.toArray(floatArrayView, 17);
- sphericalPolynomial.xy.toArray(floatArrayView, 20);
- sphericalPolynomial.yz.toArray(floatArrayView, 23);
- sphericalPolynomial.zx.toArray(floatArrayView, 26);
- // Fill pixel data.
- intArrayView[29] = mippedData.length; // Number of mip levels.
- var startIndex = 30;
- for (var level = 0; level < mippedData.length; level++) {
- // Fill each pixel of the mip level.
- var faceSize = Math.pow(size >> level, 2) * 3;
- for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
- floatArrayView.set(mippedData[level][faceIndex], startIndex);
- startIndex += faceSize;
- }
- }
- // Callback.
- callback(buffer);
- };
- // Download and process.
- BABYLON.Tools.LoadFile(url, function (data) {
- getDataCallback(data);
- }, null, null, true, onError);
- };
- HDRCubeTexture._facesMapping = [
- "right",
- "up",
- "front",
- "left",
- "down",
- "back"
- ];
- return HDRCubeTexture;
- })(BABYLON.BaseTexture);
- BABYLON.HDRCubeTexture = HDRCubeTexture;
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var Debug;
- (function (Debug) {
- /**
- * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
- */
- var SkeletonViewer = (function () {
- function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
- if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
- if (renderingGroupId === void 0) { renderingGroupId = 1; }
- this.skeleton = skeleton;
- this.mesh = mesh;
- this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
- this.renderingGroupId = renderingGroupId;
- this.color = BABYLON.Color3.White();
- this._debugLines = [];
- this._isEnabled = false;
- this._scene = scene;
- this.update();
- this._renderFunction = this.update.bind(this);
- }
- Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
- get: function () {
- return this._isEnabled;
- },
- set: function (value) {
- if (this._isEnabled === value) {
- return;
- }
- this._isEnabled = value;
- if (value) {
- this._scene.registerBeforeRender(this._renderFunction);
- }
- else {
- this._scene.unregisterBeforeRender(this._renderFunction);
- }
- },
- enumerable: true,
- configurable: true
- });
- SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
- if (x === void 0) { x = 0; }
- if (y === void 0) { y = 0; }
- if (z === void 0) { z = 0; }
- var tmat = BABYLON.Tmp.Matrix[0];
- var parentBone = bone.getParent();
- tmat.copyFrom(bone.getLocalMatrix());
- if (x !== 0 || y !== 0 || z !== 0) {
- var tmat2 = BABYLON.Tmp.Matrix[1];
- BABYLON.Matrix.IdentityToRef(tmat2);
- tmat2.m[12] = x;
- tmat2.m[13] = y;
- tmat2.m[14] = z;
- tmat2.multiplyToRef(tmat, tmat);
- }
- if (parentBone) {
- tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
- }
- tmat.multiplyToRef(meshMat, tmat);
- position.x = tmat.m[12];
- position.y = tmat.m[13];
- position.z = tmat.m[14];
- };
- SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
- var len = bones.length;
- for (var i = 0; i < len; i++) {
- var bone = bones[i];
- var points = this._debugLines[i];
- if (!points) {
- points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
- this._debugLines[i] = points;
- }
- this._getBonePosition(points[0], bone, meshMat);
- this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
- }
- };
- SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
- var len = bones.length;
- var boneNum = 0;
- for (var i = len - 1; i >= 0; i--) {
- var childBone = bones[i];
- var parentBone = childBone.getParent();
- if (!parentBone) {
- continue;
- }
- var points = this._debugLines[boneNum];
- if (!points) {
- points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
- this._debugLines[boneNum] = points;
- }
- this._getBonePosition(points[0], childBone, meshMat);
- this._getBonePosition(points[1], parentBone, meshMat);
- boneNum++;
- }
- };
- SkeletonViewer.prototype.update = function () {
- if (this.autoUpdateBonesMatrices) {
- this._updateBoneMatrix(this.skeleton.bones[0]);
- }
- if (this.skeleton.bones[0].length === undefined) {
- this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
- }
- else {
- this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
- }
- if (!this._debugMesh) {
- this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
- this._debugMesh.renderingGroupId = this.renderingGroupId;
- }
- else {
- BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
- }
- this._debugMesh.color = this.color;
- };
- SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
- if (bone.getParent()) {
- bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
- }
- var children = bone.children;
- var len = children.length;
- for (var i = 0; i < len; i++) {
- this._updateBoneMatrix(children[i]);
- }
- };
- SkeletonViewer.prototype.dispose = function () {
- if (this._debugMesh) {
- this.isEnabled = false;
- this._debugMesh.dispose();
- this._debugMesh = null;
- }
- };
- return SkeletonViewer;
- })();
- Debug.SkeletonViewer = SkeletonViewer;
- })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
- })(BABYLON || (BABYLON = {}));
- var BABYLON;
- (function (BABYLON) {
- var maxSimultaneousLights = 4;
- var PBRMaterialDefines = (function (_super) {
- __extends(PBRMaterialDefines, _super);
- function PBRMaterialDefines() {
- _super.call(this);
- this.ALBEDO = false;
- this.AMBIENT = false;
- this.OPACITY = false;
- this.OPACITYRGB = false;
- this.REFLECTION = false;
- this.EMISSIVE = false;
- this.REFLECTIVITY = false;
- this.BUMP = false;
- this.PARALLAX = false;
- this.PARALLAXOCCLUSION = false;
- this.SPECULAROVERALPHA = false;
- this.CLIPPLANE = false;
- this.ALPHATEST = false;
- this.ALPHAFROMALBEDO = false;
- this.POINTSIZE = false;
- this.FOG = false;
- this.LIGHT0 = false;
- this.LIGHT1 = false;
- this.LIGHT2 = false;
- this.LIGHT3 = false;
- this.SPOTLIGHT0 = false;
- this.SPOTLIGHT1 = false;
- this.SPOTLIGHT2 = false;
- this.SPOTLIGHT3 = false;
- this.HEMILIGHT0 = false;
- this.HEMILIGHT1 = false;
- this.HEMILIGHT2 = false;
- this.HEMILIGHT3 = false;
- this.POINTLIGHT0 = false;
- this.POINTLIGHT1 = false;
- this.POINTLIGHT2 = false;
- this.POINTLIGHT3 = false;
- this.DIRLIGHT0 = false;
- this.DIRLIGHT1 = false;
- this.DIRLIGHT2 = false;
- this.DIRLIGHT3 = false;
- this.SPECULARTERM = false;
- this.SHADOW0 = false;
- this.SHADOW1 = false;
- this.SHADOW2 = false;
- this.SHADOW3 = false;
- this.SHADOWS = false;
- this.SHADOWVSM0 = false;
- this.SHADOWVSM1 = false;
- this.SHADOWVSM2 = false;
- this.SHADOWVSM3 = false;
- this.SHADOWPCF0 = false;
- this.SHADOWPCF1 = false;
- this.SHADOWPCF2 = false;
- this.SHADOWPCF3 = false;
- this.OPACITYFRESNEL = false;
- this.EMISSIVEFRESNEL = false;
- this.FRESNEL = false;
- this.NORMAL = false;
- this.UV1 = false;
- this.UV2 = false;
- this.VERTEXCOLOR = false;
- this.VERTEXALPHA = false;
- this.NUM_BONE_INFLUENCERS = 0;
- this.BonesPerMesh = 0;
- this.INSTANCES = false;
- this.MICROSURFACEFROMREFLECTIVITYMAP = false;
- this.MICROSURFACEAUTOMATIC = false;
- this.EMISSIVEASILLUMINATION = false;
- this.LINKEMISSIVEWITHALBEDO = false;
- this.LIGHTMAP = false;
- this.USELIGHTMAPASSHADOWMAP = false;
- this.REFLECTIONMAP_3D = false;
- this.REFLECTIONMAP_SPHERICAL = false;
- this.REFLECTIONMAP_PLANAR = false;
- this.REFLECTIONMAP_CUBIC = false;
- this.REFLECTIONMAP_PROJECTION = false;
- this.REFLECTIONMAP_SKYBOX = false;
- this.REFLECTIONMAP_EXPLICIT = false;
- this.REFLECTIONMAP_EQUIRECTANGULAR = false;
- this.INVERTCUBICMAP = false;
- this.LOGARITHMICDEPTH = false;
- this.CAMERATONEMAP = false;
- this.CAMERACONTRAST = false;
- this.OVERLOADEDVALUES = false;
- this.OVERLOADEDSHADOWVALUES = false;
- this.USESPHERICALFROMREFLECTIONMAP = false;
- this.REFRACTION = false;
- this.REFRACTIONMAP_3D = false;
- this.LINKREFRACTIONTOTRANSPARENCY = false;
- this.REFRACTIONMAPINLINEARSPACE = false;
- this.LODBASEDMICROSFURACE = false;
- this.USEPHYSICALLIGHTFALLOFF = false;
- this.RADIANCEOVERALPHA = false;
- this.USEPMREMREFLECTION = false;
- this.USEPMREMREFRACTION = false;
- this._keys = Object.keys(this);
- }
- return PBRMaterialDefines;
- })(BABYLON.MaterialDefines);
- /**
- * The Physically based material of BJS.
- *
- * This offers the main features of a standard PBR material.
- * For more information, please refer to the documentation :
- * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
- */
- var PBRMaterial = (function (_super) {
- __extends(PBRMaterial, _super);
- /**
- * Instantiates a new PBRMaterial instance.
- *
- * @param name The material name
- * @param scene The scene the material will be use in.
- */
- function PBRMaterial(name, scene) {
- var _this = this;
- _super.call(this, name, scene);
- /**
- * Intensity of the direct lights e.g. the four lights available in your scene.
- * This impacts both the direct diffuse and specular highlights.
- */
- this.directIntensity = 1.0;
- /**
- * Intensity of the emissive part of the material.
- * This helps controlling the emissive effect without modifying the emissive color.
- */
- this.emissiveIntensity = 1.0;
- /**
- * Intensity of the environment e.g. how much the environment will light the object
- * either through harmonics for rough material or through the refelction for shiny ones.
- */
- this.environmentIntensity = 1.0;
- /**
- * This is a special control allowing the reduction of the specular highlights coming from the
- * four lights of the scene. Those highlights may not be needed in full environment lighting.
- */
- this.specularIntensity = 1.0;
- this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
- /**
- * Debug Control allowing disabling the bump map on this material.
- */
- this.disableBumpMap = false;
- /**
- * Debug Control helping enforcing or dropping the darkness of shadows.
- * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
- */
- this.overloadedShadowIntensity = 1.0;
- /**
- * Debug Control helping dropping the shading effect coming from the diffuse lighting.
- * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
- */
- this.overloadedShadeIntensity = 1.0;
- this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
- /**
- * The camera exposure used on this material.
- * This property is here and not in the camera to allow controlling exposure without full screen post process.
- * This corresponds to a photographic exposure.
- */
- this.cameraExposure = 1.0;
- /**
- * The camera contrast used on this material.
- * This property is here and not in the camera to allow controlling contrast without full screen post process.
- */
- this.cameraContrast = 1.0;
- this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
- this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
- /**
- * Debug Control allowing to overload the ambient color.
- * This as to be use with the overloadedAmbientIntensity parameter.
- */
- this.overloadedAmbient = BABYLON.Color3.White();
- /**
- * Debug Control indicating how much the overloaded ambient color is used against the default one.
- */
- this.overloadedAmbientIntensity = 0.0;
- /**
- * Debug Control allowing to overload the albedo color.
- * This as to be use with the overloadedAlbedoIntensity parameter.
- */
- this.overloadedAlbedo = BABYLON.Color3.White();
- /**
- * Debug Control indicating how much the overloaded albedo color is used against the default one.
- */
- this.overloadedAlbedoIntensity = 0.0;
- /**
- * Debug Control allowing to overload the reflectivity color.
- * This as to be use with the overloadedReflectivityIntensity parameter.
- */
- this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
- /**
- * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
- */
- this.overloadedReflectivityIntensity = 0.0;
- /**
- * Debug Control allowing to overload the emissive color.
- * This as to be use with the overloadedEmissiveIntensity parameter.
- */
- this.overloadedEmissive = BABYLON.Color3.White();
- /**
- * Debug Control indicating how much the overloaded emissive color is used against the default one.
- */
- this.overloadedEmissiveIntensity = 0.0;
- this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
- /**
- * Debug Control allowing to overload the reflection color.
- * This as to be use with the overloadedReflectionIntensity parameter.
- */
- this.overloadedReflection = BABYLON.Color3.White();
- /**
- * Debug Control indicating how much the overloaded reflection color is used against the default one.
- */
- this.overloadedReflectionIntensity = 0.0;
- /**
- * Debug Control allowing to overload the microsurface.
- * This as to be use with the overloadedMicroSurfaceIntensity parameter.
- */
- this.overloadedMicroSurface = 0.0;
- /**
- * Debug Control indicating how much the overloaded microsurface is used against the default one.
- */
- this.overloadedMicroSurfaceIntensity = 0.0;
- this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
- this.ambientColor = new BABYLON.Color3(0, 0, 0);
- /**
- * AKA Diffuse Color in other nomenclature.
- */
- this.albedoColor = new BABYLON.Color3(1, 1, 1);
- /**
- * AKA Specular Color in other nomenclature.
- */
- this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
- this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
- this.emissiveColor = new BABYLON.Color3(0, 0, 0);
- /**
-
- * AKA Glossiness in other nomenclature.
- */
- this.microSurface = 0.9;
- /**
- * source material index of refraction (IOR)' / 'destination material IOR.
- */
- this.indexOfRefraction = 0.66;
- /**
- * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
- */
- this.invertRefractionY = false;
- /**
- * This parameters will make the material used its opacity to control how much it is refracting aginst not.
- * Materials half opaque for instance using refraction could benefit from this control.
- */
- this.linkRefractionWithTransparency = false;
- /**
- * The emissive and albedo are linked to never be more than one (Energy conservation).
- */
- this.linkEmissiveWithAlbedo = false;
- this.useLightmapAsShadowmap = false;
- /**
- * In this mode, the emissive informtaion will always be added to the lighting once.
- * A light for instance can be thought as emissive.
- */
- this.useEmissiveAsIllumination = false;
- /**
- * Secifies that the alpha is coming form the albedo channel alpha channel.
- */
- this.useAlphaFromAlbedoTexture = false;
- /**
- * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
- * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
- */
- this.useSpecularOverAlpha = true;
- /**
- * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
- */
- this.useMicroSurfaceFromReflectivityMapAlpha = false;
- /**
- * In case the reflectivity map does not contain the microsurface information in its alpha channel,
- * The material will try to infer what glossiness each pixel should be.
- */
- this.useAutoMicroSurfaceFromReflectivityMap = false;
- /**
- * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
- * the creation of the material.
- */
- this.useScalarInLinearSpace = false;
- /**
- * BJS is using an harcoded light falloff based on a manually sets up range.
- * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
- * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
- */
- this.usePhysicalLightFalloff = true;
- /**
- * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
- * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
- */
- this.useRadianceOverAlpha = true;
- /**
- * Allows using the bump map in parallax mode.
- */
- this.useParallax = false;
- /**
- * Allows using the bump map in parallax occlusion mode.
- */
- this.useParallaxOcclusion = false;
- /**
- * Controls the scale bias of the parallax mode.
- */
- this.parallaxScaleBias = 0.05;
- this.disableLighting = false;
- this._renderTargets = new BABYLON.SmartArray(16);
- this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
- this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
- this._tempColor = new BABYLON.Color3();
- this._defines = new PBRMaterialDefines();
- this._cachedDefines = new PBRMaterialDefines();
- this._myScene = null;
- this._myShadowGenerator = null;
- this._cachedDefines.BonesPerMesh = -1;
- this.getRenderTargetTextures = function () {
- _this._renderTargets.reset();
- if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
- _this._renderTargets.push(_this.reflectionTexture);
- }
- if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
- _this._renderTargets.push(_this.refractionTexture);
- }
- return _this._renderTargets;
- };
- }
- Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
- get: function () {
- return this._useLogarithmicDepth;
- },
- set: function (value) {
- this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
- },
- enumerable: true,
- configurable: true
- });
- PBRMaterial.prototype.needAlphaBlending = function () {
- if (this.linkRefractionWithTransparency) {
- return false;
- }
- return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
- };
- PBRMaterial.prototype.needAlphaTesting = function () {
- if (this.linkRefractionWithTransparency) {
- return false;
- }
- return this.albedoTexture != null && this.albedoTexture.hasAlpha;
- };
- PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
- return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
- };
- PBRMaterial.prototype.getAlphaTestTexture = function () {
- return this.albedoTexture;
- };
- PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
- if (!mesh) {
- return true;
- }
- if (this._defines.INSTANCES !== useInstances) {
- return false;
- }
- if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
- return true;
- }
- return false;
- };
- PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
- PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
- };
- PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
- if (!useScalarInLinear) {
- color.toLinearSpaceToRef(ref);
- }
- else {
- ref.r = color.r;
- ref.g = color.g;
- ref.b = color.b;
- }
- };
- PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace) {
- var lightIndex = 0;
- var depthValuesAlreadySet = false;
- for (var index = 0; index < scene.lights.length; index++) {
- var light = scene.lights[index];
- if (!light.isEnabled()) {
- continue;
- }
- if (!light.canAffectMesh(mesh)) {
- continue;
- }
- this._lightRadiuses[lightIndex] = light.radius;
- BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
- // GAMMA CORRECTION.
- this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
- PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
- effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, light.range);
- if (defines["SPECULARTERM"]) {
- this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
- PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
- effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
- }
- // Shadows
- if (scene.shadowsEnabled) {
- depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
- }
- lightIndex++;
- if (lightIndex === maxSimultaneousLights)
- break;
- }
- effect.setFloat4("vLightRadiuses", this._lightRadiuses[0], this._lightRadiuses[1], this._lightRadiuses[2], this._lightRadiuses[3]);
- };
- PBRMaterial.prototype.isReady = function (mesh, useInstances) {
- if (this.checkReadyOnlyOnce) {
- if (this._wasPreviouslyReady) {
- return true;
- }
- }
- var scene = this.getScene();
- if (!this.checkReadyOnEveryCall) {
- if (this._renderId === scene.getRenderId()) {
- if (this._checkCache(scene, mesh, useInstances)) {
- return true;
- }
- }
- }
- var engine = scene.getEngine();
- var needNormals = false;
- var needUVs = false;
- this._defines.reset();
- if (scene.texturesEnabled) {
- // Textures
- if (scene.texturesEnabled) {
- if (scene.getEngine().getCaps().textureLOD) {
- this._defines.LODBASEDMICROSFURACE = true;
- }
- if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
- if (!this.albedoTexture.isReady()) {
- return false;
- }
- else {
- needUVs = true;
- this._defines.ALBEDO = true;
- }
- }
- if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
- if (!this.ambientTexture.isReady()) {
- return false;
- }
- else {
- needUVs = true;
- this._defines.AMBIENT = true;
- }
- }
- if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
- if (!this.opacityTexture.isReady()) {
- return false;
- }
- else {
- needUVs = true;
- this._defines.OPACITY = true;
- if (this.opacityTexture.getAlphaFromRGB) {
- this._defines.OPACITYRGB = true;
- }
- }
- }
- if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
- if (!this.reflectionTexture.isReady()) {
- return false;
- }
- else {
- needNormals = true;
- this._defines.REFLECTION = true;
- if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
- this._defines.INVERTCUBICMAP = true;
- }
- this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
- switch (this.reflectionTexture.coordinatesMode) {
- case BABYLON.Texture.CUBIC_MODE:
- case BABYLON.Texture.INVCUBIC_MODE:
- this._defines.REFLECTIONMAP_CUBIC = true;
- break;
- case BABYLON.Texture.EXPLICIT_MODE:
- this._defines.REFLECTIONMAP_EXPLICIT = true;
- break;
- case BABYLON.Texture.PLANAR_MODE:
- this._defines.REFLECTIONMAP_PLANAR = true;
- break;
- case BABYLON.Texture.PROJECTION_MODE:
- this._defines.REFLECTIONMAP_PROJECTION = true;
- break;
- case BABYLON.Texture.SKYBOX_MODE:
- this._defines.REFLECTIONMAP_SKYBOX = true;
- break;
- case BABYLON.Texture.SPHERICAL_MODE:
- this._defines.REFLECTIONMAP_SPHERICAL = true;
- break;
- case BABYLON.Texture.EQUIRECTANGULAR_MODE:
- this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
- break;
- }
- if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
- this._defines.USESPHERICALFROMREFLECTIONMAP = true;
- needNormals = true;
- if (this.reflectionTexture.isPMREM) {
- this._defines.USEPMREMREFLECTION = true;
- }
- }
- }
- }
- if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
- if (!this.lightmapTexture.isReady()) {
- return false;
- }
- else {
- needUVs = true;
- this._defines.LIGHTMAP = true;
- this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
- }
- }
- if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
- if (!this.emissiveTexture.isReady()) {
- return false;
- }
- else {
- needUVs = true;
- this._defines.EMISSIVE = true;
- }
- }
- if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
- if (!this.reflectivityTexture.isReady()) {
- return false;
- }
- else {
- needUVs = true;
- this._defines.REFLECTIVITY = true;
- this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
- this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
- }
- }
- }
- if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
- if (!this.bumpTexture.isReady()) {
- return false;
- }
- else {
- needUVs = true;
- this._defines.BUMP = true;
- if (this.useParallax) {
- this._defines.PARALLAX = true;
- if (this.useParallaxOcclusion) {
- this._defines.PARALLAXOCCLUSION = true;
- }
- }
- }
- }
- if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
- if (!this.refractionTexture.isReady()) {
- return false;
- }
- else {
- needUVs = true;
- this._defines.REFRACTION = true;
- this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
- if (this.linkRefractionWithTransparency) {
- this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
- }
- if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
- this._defines.REFRACTIONMAPINLINEARSPACE = true;
- if (this.refractionTexture.isPMREM) {
- this._defines.USEPMREMREFRACTION = true;
- }
- }
- }
- }
- }
- // Effect
- if (scene.clipPlane) {
- this._defines.CLIPPLANE = true;
- }
- if (engine.getAlphaTesting()) {
- this._defines.ALPHATEST = true;
- }
- if (this._shouldUseAlphaFromAlbedoTexture()) {
- this._defines.ALPHAFROMALBEDO = true;
- }
- if (this.useEmissiveAsIllumination) {
- this._defines.EMISSIVEASILLUMINATION = true;
- }
- if (this.linkEmissiveWithAlbedo) {
- this._defines.LINKEMISSIVEWITHALBEDO = true;
- }
- if (this.useLogarithmicDepth) {
- this._defines.LOGARITHMICDEPTH = true;
- }
- if (this.cameraContrast != 1) {
- this._defines.CAMERACONTRAST = true;
- }
- if (this.cameraExposure != 1) {
- this._defines.CAMERATONEMAP = true;
- }
- if (this.overloadedShadeIntensity != 1 ||
- this.overloadedShadowIntensity != 1) {
- this._defines.OVERLOADEDSHADOWVALUES = true;
- }
- if (this.overloadedMicroSurfaceIntensity > 0 ||
- this.overloadedEmissiveIntensity > 0 ||
- this.overloadedReflectivityIntensity > 0 ||
- this.overloadedAlbedoIntensity > 0 ||
- this.overloadedAmbientIntensity > 0 ||
- this.overloadedReflectionIntensity > 0) {
- this._defines.OVERLOADEDVALUES = true;
- }
- // Point size
- if (this.pointsCloud || scene.forcePointsCloud) {
- this._defines.POINTSIZE = true;
- }
- // Fog
- if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
- this._defines.FOG = true;
- }
- if (scene.lightsEnabled && !this.disableLighting) {
- needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines) || needNormals;
- }
- if (BABYLON.StandardMaterial.FresnelEnabled) {
- // Fresnel
- if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
- this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
- if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
- this._defines.OPACITYFRESNEL = true;
- }
- if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
- this._defines.EMISSIVEFRESNEL = true;
- }
- needNormals = true;
- this._defines.FRESNEL = true;
- }
- }
- if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
- this._defines.SPECULAROVERALPHA = true;
- }
- if (this.usePhysicalLightFalloff) {
- this._defines.USEPHYSICALLIGHTFALLOFF = true;
- }
- if (this.useRadianceOverAlpha) {
- this._defines.RADIANCEOVERALPHA = true;
- }
- // Attribs
- if (mesh) {
- if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
- this._defines.NORMAL = true;
- }
- if (needUVs) {
- if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
- this._defines.UV1 = true;
- }
- if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
- this._defines.UV2 = true;
- }
- }
- if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
- this._defines.VERTEXCOLOR = true;
- if (mesh.hasVertexAlpha) {
- this._defines.VERTEXALPHA = true;
- }
- }
- if (mesh.useBones && mesh.computeBonesUsingShaders) {
- this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
- this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
- }
- // Instances
- if (useInstances) {
- this._defines.INSTANCES = true;
- }
- }
- // Get correct effect
- if (!this._defines.isEqual(this._cachedDefines)) {
- this._defines.cloneTo(this._cachedDefines);
- scene.resetCachedMaterial();
- // Fallbacks
- var fallbacks = new BABYLON.EffectFallbacks();
- if (this._defines.REFLECTION) {
- fallbacks.addFallback(0, "REFLECTION");
- }
- if (this._defines.REFRACTION) {
- fallbacks.addFallback(0, "REFRACTION");
- }
- if (this._defines.REFLECTIVITY) {
- fallbacks.addFallback(0, "REFLECTIVITY");
- }
- if (this._defines.BUMP) {
- fallbacks.addFallback(0, "BUMP");
- }
- if (this._defines.PARALLAX) {
- fallbacks.addFallback(1, "PARALLAX");
- }
- if (this._defines.PARALLAXOCCLUSION) {
- fallbacks.addFallback(0, "PARALLAXOCCLUSION");
- }
- if (this._defines.SPECULAROVERALPHA) {
- fallbacks.addFallback(0, "SPECULAROVERALPHA");
- }
- if (this._defines.FOG) {
- fallbacks.addFallback(1, "FOG");
- }
- if (this._defines.POINTSIZE) {
- fallbacks.addFallback(0, "POINTSIZE");
- }
- if (this._defines.LOGARITHMICDEPTH) {
- fallbacks.addFallback(0, "LOGARITHMICDEPTH");
- }
- BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks);
- if (this._defines.SPECULARTERM) {
- fallbacks.addFallback(0, "SPECULARTERM");
- }
- if (this._defines.OPACITYFRESNEL) {
- fallbacks.addFallback(1, "OPACITYFRESNEL");
- }
- if (this._defines.EMISSIVEFRESNEL) {
- fallbacks.addFallback(2, "EMISSIVEFRESNEL");
- }
- if (this._defines.FRESNEL) {
- fallbacks.addFallback(3, "FRESNEL");
- }
- if (this._defines.NUM_BONE_INFLUENCERS > 0) {
- fallbacks.addCPUSkinningFallback(0, mesh);
- }
- //Attributes
- var attribs = [BABYLON.VertexBuffer.PositionKind];
- if (this._defines.NORMAL) {
- attribs.push(BABYLON.VertexBuffer.NormalKind);
- }
- if (this._defines.UV1) {
- attribs.push(BABYLON.VertexBuffer.UVKind);
- }
- if (this._defines.UV2) {
- attribs.push(BABYLON.VertexBuffer.UV2Kind);
- }
- if (this._defines.VERTEXCOLOR) {
- attribs.push(BABYLON.VertexBuffer.ColorKind);
- }
- BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
- BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
- // Legacy browser patch
- var shaderName = "pbr";
- if (!scene.getEngine().getCaps().standardDerivatives) {
- shaderName = "legacypbr";
- }
- var join = this._defines.toString();
- this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
- "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
- "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
- "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
- "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
- "vFogInfos", "vFogColor", "pointSize",
- "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
- "mBones",
- "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
- "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
- "opacityParts", "emissiveLeftColor", "emissiveRightColor",
- "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vCameraInfos", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
- "logarithmicDepthConstant",
- "vSphericalX", "vSphericalY", "vSphericalZ",
- "vSphericalXX", "vSphericalYY", "vSphericalZZ",
- "vSphericalXY", "vSphericalYZ", "vSphericalZX",
- "vMicrosurfaceTextureLods", "vLightRadiuses"
- ], ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
- "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
- ], join, fallbacks, this.onCompiled, this.onError);
- }
- if (!this._effect.isReady()) {
- return false;
- }
- this._renderId = scene.getRenderId();
- this._wasPreviouslyReady = true;
- if (mesh) {
- if (!mesh._materialDefines) {
- mesh._materialDefines = new PBRMaterialDefines();
- }
- this._defines.cloneTo(mesh._materialDefines);
- }
- return true;
- };
- PBRMaterial.prototype.unbind = function () {
- if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
- this._effect.setTexture("reflection2DSampler", null);
- }
- if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
- this._effect.setTexture("refraction2DSampler", null);
- }
- _super.prototype.unbind.call(this);
- };
- PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
- this._effect.setMatrix("world", world);
- };
- PBRMaterial.prototype.bind = function (world, mesh) {
- this._myScene = this.getScene();
- // Matrices
- this.bindOnlyWorldMatrix(world);
- // Bones
- BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
- if (this._myScene.getCachedMaterial() !== this) {
- this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
- if (BABYLON.StandardMaterial.FresnelEnabled) {
- if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
- this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
- }
- if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
- this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
- this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
- }
- }
- // Textures
- if (this._myScene.texturesEnabled) {
- if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
- this._effect.setTexture("albedoSampler", this.albedoTexture);
- this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
- this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
- }
- if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
- this._effect.setTexture("ambientSampler", this.ambientTexture);
- this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
- this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
- }
- if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
- this._effect.setTexture("opacitySampler", this.opacityTexture);
- this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
- this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
- }
- if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
- this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
- if (this.reflectionTexture.isCube) {
- this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
- }
- else {
- this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
- }
- this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
- this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
- if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
- this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
- this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
- this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
- this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
- this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
- this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
- this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
- this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
- this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
- }
- }
- if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
- this._effect.setTexture("emissiveSampler", this.emissiveTexture);
- this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
- this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
- }
- if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
- this._effect.setTexture("lightmapSampler", this.lightmapTexture);
- this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
- this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
- }
- if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
- this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
- this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
- this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
- }
- if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
- this._effect.setTexture("bumpSampler", this.bumpTexture);
- this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
- this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
- }
- if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
- this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
- var depth = 1.0;
- if (this.refractionTexture.isCube) {
- this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
- }
- else {
- this._effect.setTexture("refraction2DSampler", this.refractionTexture);
- this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
- if (this.refractionTexture.depth) {
- depth = this.refractionTexture.depth;
- }
- }
- this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
- }
- if ((this.reflectionTexture || this.refractionTexture)) {
- this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
- }
- }
- // Clip plane
- BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
- // Point size
- if (this.pointsCloud) {
- this._effect.setFloat("pointSize", this.pointSize);
- }
- // Colors
- this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
- // GAMMA CORRECTION.
- this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
- this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
- this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
- this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
- // GAMMA CORRECTION.
- this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
- this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
- // GAMMA CORRECTION.
- this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
- this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
- }
- if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
- // GAMMA CORRECTION.
- this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
- this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
- // Lights
- if (this._myScene.lightsEnabled && !this.disableLighting) {
- PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace);
- }
- // View
- if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
- this._effect.setMatrix("view", this._myScene.getViewMatrix());
- }
- // Fog
- BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
- this._lightingInfos.x = this.directIntensity;
- this._lightingInfos.y = this.emissiveIntensity;
- this._lightingInfos.z = this.environmentIntensity;
- this._lightingInfos.w = this.specularIntensity;
- this._effect.setVector4("vLightingIntensity", this._lightingInfos);
- this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
- this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
- this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
- this._cameraInfos.x = this.cameraExposure;
- this._cameraInfos.y = this.cameraContrast;
- this._effect.setVector4("vCameraInfos", this._cameraInfos);
- this._overloadedIntensity.x = this.overloadedAmbientIntensity;
- this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
- this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
- this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
- this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
- this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
- this._effect.setColor3("vOverloadedAmbient", this._tempColor);
- this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
- this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
- this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
- this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
- this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
- this._effect.setColor3("vOverloadedEmissive", this._tempColor);
- this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
- this._effect.setColor3("vOverloadedReflection", this._tempColor);
- this._overloadedMicroSurface.x = this.overloadedMicroSurface;
- this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
- this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
- this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
- // Log. depth
- BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
- }
- _super.prototype.bind.call(this, world, mesh);
- this._myScene = null;
- };
- PBRMaterial.prototype.getAnimatables = function () {
- var results = [];
- if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
- results.push(this.albedoTexture);
- }
- if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
- results.push(this.ambientTexture);
- }
- if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
- results.push(this.opacityTexture);
- }
- if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
- results.push(this.reflectionTexture);
- }
- if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
- results.push(this.emissiveTexture);
- }
- if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
- results.push(this.reflectivityTexture);
- }
- if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
- results.push(this.bumpTexture);
- }
- if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
- results.push(this.lightmapTexture);
- }
- if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
- results.push(this.refractionTexture);
- }
- return results;
- };
- PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
- if (forceDisposeTextures) {
- if (this.albedoTexture) {
- this.albedoTexture.dispose();
- }
- if (this.ambientTexture) {
- this.ambientTexture.dispose();
- }
- if (this.opacityTexture) {
- this.opacityTexture.dispose();
- }
- if (this.reflectionTexture) {
- this.reflectionTexture.dispose();
- }
- if (this.emissiveTexture) {
- this.emissiveTexture.dispose();
- }
- if (this.reflectivityTexture) {
- this.reflectivityTexture.dispose();
- }
- if (this.bumpTexture) {
- this.bumpTexture.dispose();
- }
- if (this.lightmapTexture) {
- this.lightmapTexture.dispose();
- }
- if (this.refractionTexture) {
- this.refractionTexture.dispose();
- }
- }
- _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
- };
- PBRMaterial.prototype.clone = function (name) {
- var _this = this;
- return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
- };
- PBRMaterial.prototype.serialize = function () {
- var serializationObject = BABYLON.SerializationHelper.Serialize(this);
- serializationObject.customType = "BABYLON.PBRMaterial";
- return serializationObject;
- };
- // Statics
- PBRMaterial.Parse = function (source, scene, rootUrl) {
- return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
- };
- PBRMaterial._scaledAlbedo = new BABYLON.Color3();
- PBRMaterial._scaledReflectivity = new BABYLON.Color3();
- PBRMaterial._scaledEmissive = new BABYLON.Color3();
- PBRMaterial._scaledReflection = new BABYLON.Color3();
- PBRMaterial._lightRadiuses = [1, 1, 1, 1];
- __decorate([
- BABYLON.serialize()
- ], PBRMaterial.prototype, "directIntensity", void 0);
- __decorate([
- BABYLON.serialize()
- ], PBRMaterial.prototype, "emissiveIntensity", void 0);
- __decorate([
- BABYLON.serialize()
- ], PBRMaterial.prototype, "environmentIntensity", void 0);
- __decorate([
- BABYLON.serialize()
- ], PBRMaterial.prototype, "specularIntensity", void 0);
- __decorate([
- BABYLON.serialize()
- ], PBRMaterial.prototype, "disableBumpMap", void 0);
- __decorate([
- BABYLON.serialize()
- ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
- __decorate([
- BABYLON.serialize()
- ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
- __decorate([
- BABYLON.serialize()
- ], PBRMaterial.prototype, "cameraExposure", void 0);
- __decorate([
- BABYLON.serialize()
- ], PBRMaterial.prototype, "cameraContrast", void 0);
- __decorate([
- BABYLON.serializeAsColor3()
- ], PBRMaterial.prototype, "overloadedAmbient", void 0);
- __decorate([
- BABYLON.serialize()
- ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
- __decorate([
- BABYLON.serializeAsColor3()
- ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
- __decorate([
- BABYLON.serialize()
- ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
- __decorate([
- BABYLON.serializeAsColor3()
- ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
- __decorate([
- BABYLON.serialize()
- ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
- __decorate([
- BABYLON.serializeAsColor3()
- ], PBRMaterial.prototype, "overloadedEmissive", void 0);
- __decorate([
- BABYLON.serialize()
- ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
- __decorate([
- BABYLON.serializeAsColor3()
- ], PBRMaterial.prototype, "overloadedReflection", void 0);
- __decorate([
- BABYLON.serialize()
- ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
- __decorate([
- BABYLON.serialize()
- ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
- __decorate([
- BABYLON.serialize()
- ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
- __decorate([
- BABYLON.serializeAsTexture()
- ], PBRMaterial.prototype, "albedoTexture", void 0);
- __decorate([
- BABYLON.serializeAsTexture()
- ], PBRMaterial.prototype, "ambientTexture", void 0);
- __decorate([
- BABYLON.serializeAsTexture()
- ], PBRMaterial.prototype, "opacityTexture", void 0);
- __decorate([
- BABYLON.serializeAsTexture()
- ], PBRMaterial.prototype, "reflectionTexture", void 0);
- __decorate([
- BABYLON.serializeAsTexture()
- ], PBRMaterial.prototype, "emissiveTexture", void 0);
- __decorate([
- BABYLON.serializeAsTexture()
- ], PBRMaterial.prototype, "reflectivityTexture", void 0);
- __decorate([
- BABYLON.serializeAsTexture()
- ], PBRMaterial.prototype, "bumpTexture", void 0);
- __decorate([
- BABYLON.serializeAsTexture()
- ], PBRMaterial.prototype, "lightmapTexture", void 0);
- __decorate([
- BABYLON.serializeAsTexture()
- ], PBRMaterial.prototype, "refractionTexture", void 0);
- __decorate([
- BABYLON.serializeAsColor3("ambient")
- ], PBRMaterial.prototype, "ambientColor", void 0);
- __decorate([
- BABYLON.serializeAsColor3("albedo")
- ], PBRMaterial.prototype, "albedoColor", void 0);
- __decorate([
- BABYLON.serializeAsColor3("reflectivity")
- ], PBRMaterial.prototype, "reflectivityColor", void 0);
- __decorate([
- BABYLON.serializeAsColor3("reflection")
- ], PBRMaterial.prototype, "reflectionColor", void 0);
- __decorate([
- BABYLON.serializeAsColor3("emissive")
- ], PBRMaterial.prototype, "emissiveColor", void 0);
- __decorate([
- BABYLON.serialize()
- ], PBRMaterial.prototype, "microSurface", void 0);
- __decorate([
- BABYLON.serialize()
- ], PBRMaterial.prototype, "indexOfRefraction", void 0);
- __decorate([
- BABYLON.serialize()
- ], PBRMaterial.prototype, "invertRefractionY", void 0);
- __decorate([
- BABYLON.serializeAsFresnelParameters()
- ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
- __decorate([
- BABYLON.serializeAsFresnelParameters()
- ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
- __decorate([
- BABYLON.serialize()
- ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
- __decorate([
- BABYLON.serialize()
- ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
- __decorate([
- BABYLON.serialize()
- ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
- __decorate([
- BABYLON.serialize()
- ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
- __decorate([
- BABYLON.serialize()
- ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
- __decorate([
- BABYLON.serialize()
- ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
- __decorate([
- BABYLON.serialize()
- ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
- __decorate([
- BABYLON.serialize()
- ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
- __decorate([
- BABYLON.serialize()
- ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
- __decorate([
- BABYLON.serialize()
- ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
- __decorate([
- BABYLON.serialize()
- ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
- __decorate([
- BABYLON.serialize()
- ], PBRMaterial.prototype, "useParallax", void 0);
- __decorate([
- BABYLON.serialize()
- ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
- __decorate([
- BABYLON.serialize()
- ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
- __decorate([
- BABYLON.serialize()
- ], PBRMaterial.prototype, "disableLighting", void 0);
- __decorate([
- BABYLON.serialize()
- ], PBRMaterial.prototype, "useLogarithmicDepth", null);
- return PBRMaterial;
- })(BABYLON.Material);
- BABYLON.PBRMaterial = PBRMaterial;
- })(BABYLON || (BABYLON = {}));
- 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]\n#include<lightFragmentDeclaration>[1]\n#include<lightFragmentDeclaration>[2]\n#include<lightFragmentDeclaration>[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 EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nvec2 diffuseUV=vDiffuseUV;\n#endif\n#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,diffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0]\n#include<lightFragment>[1]\n#include<lightFragment>[2]\n#include<lightFragment>[3]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\ngl_FragColor=color;\n}","defaultVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>\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>\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}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","fxaaPixelShader":"#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvoid main(){\nvec2 localTexelSize=texelSize;\nvec4 rgbNW=texture2D(textureSampler,(vUV+vec2(-1.0,-1.0)*localTexelSize));\nvec4 rgbNE=texture2D(textureSampler,(vUV+vec2(1.0,-1.0)*localTexelSize));\nvec4 rgbSW=texture2D(textureSampler,(vUV+vec2(-1.0,1.0)*localTexelSize));\nvec4 rgbSE=texture2D(textureSampler,(vUV+vec2(1.0,1.0)*localTexelSize));\nvec4 rgbM=texture2D(textureSampler,vUV);\nvec4 luma=vec4(0.299,0.587,0.114,1.0);\nfloat lumaNW=dot(rgbNW,luma);\nfloat lumaNE=dot(rgbNE,luma);\nfloat lumaSW=dot(rgbSW,luma);\nfloat lumaSE=dot(rgbSE,luma);\nfloat lumaM=dot(rgbM,luma);\nfloat lumaMin=min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));\nfloat lumaMax=max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));\nvec2 dir=vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));\nfloat dirReduce=max(\n(lumaNW+lumaNE+lumaSW+lumaSE)*(0.25*FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\nfloat rcpDirMin=1.0/(min(abs(dir.x),abs(dir.y))+dirReduce);\ndir=min(vec2(FXAA_SPAN_MAX,FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX,-FXAA_SPAN_MAX),\ndir*rcpDirMin))*localTexelSize;\nvec4 rgbA=0.5*(\ntexture2D(textureSampler,vUV+dir*(1.0/3.0-0.5)) +\ntexture2D(textureSampler,vUV+dir*(2.0/3.0-0.5)));\nvec4 rgbB=rgbA*0.5+0.25*(\ntexture2D(textureSampler,vUV+dir*-0.5) +\ntexture2D(textureSampler,vUV+dir*0.5));\nfloat lumaB=dot(rgbB,luma);\nif ((lumaB<lumaMin) || (lumaB>lumaMax)) {\ngl_FragColor=rgbA;\n}\nelse {\ngl_FragColor=rgbB;\n}\n}","hdrPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","legacydefaultPixelShader":"#define MAP_PROJECTION 4.\n\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0]\n#include<lightFragmentDeclaration>[1]\n#include<lightFragmentDeclaration>[2]\n#include<lightFragmentDeclaration>[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]\n#include<lightFragment>[1]\n#include<lightFragment>[2]\n#include<lightFragment>[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>\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>\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;\nuniform vec4 vLightRadiuses;\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]\n#include<lightFragmentDeclaration>[1]\n#include<lightFragmentDeclaration>[2]\n#include<lightFragmentDeclaration>[3]\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\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]\n#include<pbrLightFunctionsCall>[1]\n#include<pbrLightFunctionsCall>[2]\n#include<pbrLightFunctionsCall>[3]\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\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}","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;\nuniform vec4 vLightRadiuses;\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]\n#include<lightFragmentDeclaration>[1]\n#include<lightFragmentDeclaration>[2]\n#include<lightFragmentDeclaration>[3]\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\n#include<pbrShadowFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution= vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \nfloat NdotL=-1.;\nlightingInfo info;\n#include<pbrLightFunctionsCall>[0]\n#include<pbrLightFunctionsCall>[1]\n#include<pbrLightFunctionsCall>[2]\n#include<pbrLightFunctionsCall>[3]\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 (microSurface>0.5)\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 (microSurface>0.5)\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 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);\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\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y+refractance,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\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>\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>\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}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","shadowMapPixelShader":"vec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn color-(color.yy*bitOffset);\n}\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5;\n#endif\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=pack(depth);\n#endif\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","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":"uniform sampler2D textureSampler;\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;\nvarying vec2 vUV;\nvec3 normalFromDepth(float depth,vec2 coords) {\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","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","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}"};
- 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;\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","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fFogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fFogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","fogVertex":"#ifdef FOG\nfFogDistance=(view*worldPos).z;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying float fFogDistance;\n#endif","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX;\nuniform vec3 vSphericalYY;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 EnvironmentIrradiance(vec3 normal)\n{\n\n\n\nvec3 result =\nvSphericalX*normal.x +\nvSphericalY*normal.y +\nvSphericalZ*normal.z +\nvSphericalXX*normal.x*normal.x +\nvSphericalYY*normal.y*normal.y +\nvSphericalZZ*normal.z*normal.z +\nvSphericalYZ*normal.y*normal.z +\nvSphericalZX*normal.z*normal.x +\nvSphericalXY*normal.x*normal.y;\nreturn result.rgb;\n}\n#endif","helperFunctions":"mat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","lightFragment":"#ifdef LIGHT{X}\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nshadow=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#else\nuniform samplerCube shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(-lightDirection.xyz,lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,-lightDirection.xyz));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW-lightDirection.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,vec3(0.2126,0.7152,0.0722)),0.,1.);\n}\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=Square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=Square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(kPi*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 FresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 specularColor)\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,vec3(1.,1.,1.));\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\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\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}\nfloat computeLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.0001));\nreturn lightDistanceFalloff;\n#else\nfloat lightFalloff=max(0.,1.0-length(lightOffset)/range);\nreturn lightFalloff;\n#endif\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};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float roughness,float NdotV,float lightRadius,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=computeLightFalloff(lightOffset,lightDistanceSquared,range);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,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);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float roughness,float NdotV,float lightRadius,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(lightOffset);\n\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection.xyz,lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeLightFalloff(lightOffset,lightDistanceSquared,range);\n\nattenuation*=cosAngle;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,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);\nresult.specular=specTerm*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 roughness,float NdotV,float lightRadius,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);\nresult.specular=specTerm;\n#endif\nreturn result;\n}","pbrLightFunctionsCall":"#ifdef LIGHT{X}\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.0);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,vLightRadiuses[{X}],NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},roughness,NdotV,vLightRadiuses[{X}],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,vLightRadiuses[{X}],NdotL);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nnotShadowLevel=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nnotShadowLevel=1.;\n#endif\nlightDiffuseContribution+=info.diffuse*notShadowLevel;\n#ifdef OVERLOADEDSHADOWVALUES\nif (NdotL<0.000000000011)\n{\nnotShadowLevel=1.;\n}\nshadowedOnlyLightDiffuseContribution*=notShadowLevel;\n#endif\n#ifdef SPECULARTERM\nlightSpecularContribution+=info.specular*notShadowLevel;\n#endif\n#endif","pbrShadowFunctions":"\n#ifdef SHADOWS\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y =-directionToLight.y;\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\nif (depth>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\n#endif\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\nif (depth.z>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n#endif\n}\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","shadowsFragmentFunctions":"#ifdef SHADOWS\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\nreturn min(1.0,visibility+darkness);\n}\n#endif\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\nif (depth.z>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\nreturn min(1.0,visibility+darkness);\n}\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n}\n#endif\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\nvPositionFromLight0=lightMatrix0*worldPos;\n#endif\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\nvPositionFromLight1=lightMatrix1*worldPos;\n#endif\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\nvPositionFromLight2=lightMatrix2*worldPos;\n#endif\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\nvPositionFromLight3=lightMatrix3*worldPos;\n#endif\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif"};
- BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:!(o.z-i>e.z)},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:!!e(s,r,this.basePointWorld,this.velocityWorldLength+c)},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,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(f,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(f,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(f=g*-m+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(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+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(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+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(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?(0===e.x&&0===e.y&&0===e.z||this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;r>s;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?(0===i.x&&0===i.y&&0===i.z||t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){t.ToGammaSpace=1/2.2,t.ToLinearSpace=2.2,t.Epsilon=.001;var i=function(){function t(){}return t.WithinEpsilon=function(t,i,n){void 0===n&&(n=1.401298e-45);var r=t-i;return r>=-n&&n>=r},t.ToHex=function(t){var i=t.toString(16);return 15>=t?(\"0\"+i).toUpperCase():i.toUpperCase()},t.Sign=function(t){return t=+t,0===t||isNaN(t)?t:t>0?1:-1},t.Clamp=function(t,i,n){return void 0===i&&(i=0),void 0===n&&(n=1),Math.min(n,Math.max(i,t))},t}();t.MathTools=i;var n=function(){function n(t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.r=t,this.g=i,this.b=n}return n.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},n.prototype.toColor4=function(t){return void 0===t&&(t=1),new r(this.r,this.g,this.b,t)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},n.prototype.multiply=function(t){return new n(this.r*t.r,this.g*t.g,this.b*t.b)},n.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},n.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},n.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},n.prototype.scale=function(t){return new n(this.r*t,this.g*t,this.b*t)},n.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},n.prototype.add=function(t){return new n(this.r+t.r,this.g+t.g,this.b+t.b)},n.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},n.prototype.subtract=function(t){return new n(this.r-t.r,this.g-t.g,this.b-t.b)},n.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},n.prototype.clone=function(){return new n(this.r,this.g,this.b)},n.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},n.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},n.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)},n.prototype.toLinearSpace=function(){var t=new n;return this.toLinearSpaceToRef(t),t},n.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},n.prototype.toGammaSpace=function(){var t=new n;return this.toGammaSpaceToRef(t),t},n.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},n.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new n(0,0,0);var i=parseInt(t.substring(1,3),16),r=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return n.FromInts(i,r,o)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1],t[i+2])},n.FromInts=function(t,i,r){return new n(t/255,i/255,r/255)},n.Lerp=function(t,i,r){var o=t.r+(i.r-t.r)*r,s=t.g+(i.g-t.g)*r,e=t.b+(i.b-t.b)*r;return new n(o,s,e)},n.Red=function(){return new n(1,0,0)},n.Green=function(){return new n(0,1,0)},n.Blue=function(){return new n(0,0,1)},n.Black=function(){return new n(0,0,0)},n.White=function(){return new n(1,1,1)},n.Purple=function(){return new n(.5,0,.5)},n.Magenta=function(){return new n(1,0,1)},n.Yellow=function(){return new n(1,1,0)},n.Gray=function(){return new n(.5,.5,.5)},n}();t.Color3=n;var r=function(){function t(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var n=parseInt(i.substring(1,3),16),r=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),s=parseInt(i.substring(7,9),16);return t.FromInts(n,r,o,s)},t.Lerp=function(i,n,r){var o=new t(0,0,0,0);return t.LerpToRef(i,n,r,o),o},t.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},t.FromArray=function(i,n){return void 0===n&&(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.FromInts=function(i,n,r,o){return new t(i/255,n/255,r/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var n=[],r=0;r<t.length;r+=3){var o=r/3*4;n[o]=t[r],n[o+1]=t[r+1],n[o+2]=t[r+2],n[o+3]=1}return n}return t},t}();t.Color4=r;var o=function(){function n(t,i){this.x=t,this.y=i}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},n.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.addVector3=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y)},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},n.prototype.multiplyByFloats=function(t,i){return new n(this.x*t,this.y*i)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},n.prototype.negate=function(){return new n(-this.x,-this.y)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t)},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},n.prototype.clone=function(){return new n(this.x,this.y)},n.Zero=function(){return new n(0,0)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},n.CatmullRom=function(t,i,r,o,s){var e=s*s,h=s*e,a=.5*(2*i.x+(-t.x+r.x)*s+(2*t.x-5*i.x+4*r.x-o.x)*e+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*s+(2*t.y-5*i.y+4*r.y-o.y)*e+(-t.y+3*i.y-3*r.y+o.y)*h);return new n(a,u)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var s=t.y;return s=s>r.y?r.y:s,s=s<i.y?i.y:s,new n(o,s)},n.Hermite=function(t,i,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y;return new n(c,p)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,s=t.y+(i.y-t.y)*r;return new n(o,s)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y},n.Normalize=function(t){var i=t.clone();return i.normalize(),i},n.Minimize=function(t,i){var r=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new n(r,o)},n.Maximize=function(t,i){var r=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new n(r,o)},n.Transform=function(t,i){var r=t.x*i.m[0]+t.y*i.m[4],o=t.x*i.m[1]+t.y*i.m[5];return new n(r,o)},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},n}();t.Vector2=o;var s=function(){function n(t,i,n){this.x=t,this.y=i,this.z=n}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},n.prototype.toQuaternion=function(){var t=new h(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),e=Math.sin(.5*this.y);return t.x=r*e,t.y=-o*e,t.z=n*s,t.w=i*s,t},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},n.prototype.subtractFromFloats=function(t,i,r){return new n(this.x-t,this.y-i,this.z-r)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},n.prototype.negate=function(){return new n(-this.x,-this.y,-this.z)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)},n.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},n.prototype.multiplyByFloats=function(t,i,r){return new n(this.x*t,this.y*i,this.z*r)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},n.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},n.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},n.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},n.prototype.clone=function(){return new n(this.x,this.y,this.z)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},n.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},n.GetClipFactor=function(t,i,r,o){var s=n.Dot(t,r)-o,e=n.Dot(i,r)-o,h=s/(s-e);return h},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromFloatArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},n.Zero=function(){return new n(0,0,0)},n.Up=function(){return new n(0,1,0)},n.TransformCoordinates=function(t,i){var r=n.Zero();return n.TransformCoordinatesToRef(t,i,r),r},n.TransformCoordinatesToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];n.x=r/e,n.y=o/e,n.z=s/e},n.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var s=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],e=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=s/a,o.y=e/a,o.z=h/a},n.TransformNormal=function(t,i){var r=n.Zero();return n.TransformNormalToRef(t,i,r),r},n.TransformNormalToRef=function(t,i,n){n.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],n.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],n.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},n.TransformNormalFromFloatsToRef=function(t,i,n,r,o){o.x=t*r.m[0]+i*r.m[4]+n*r.m[8],o.y=t*r.m[1]+i*r.m[5]+n*r.m[9],o.z=t*r.m[2]+i*r.m[6]+n*r.m[10]},n.CatmullRom=function(t,i,r,o,s){var e=s*s,h=s*e,a=.5*(2*i.x+(-t.x+r.x)*s+(2*t.x-5*i.x+4*r.x-o.x)*e+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*s+(2*t.y-5*i.y+4*r.y-o.y)*e+(-t.y+3*i.y-3*r.y+o.y)*h),m=.5*(2*i.z+(-t.z+r.z)*s+(2*t.z-5*i.z+4*r.z-o.z)*e+(-t.z+3*i.z-3*r.z+o.z)*h);return new n(a,u,m)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var s=t.y;s=s>r.y?r.y:s,s=s<i.y?i.y:s;var e=t.z;return e=e>r.z?r.z:e,e=e<i.z?i.z:e,new n(o,s,e)},n.Hermite=function(t,i,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y,f=t.z*a+r.z*u+i.z*m+o.z*y;return new n(c,p,f)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,s=t.y+(i.y-t.y)*r,e=t.z+(i.z-t.z)*r;return new n(o,s,e)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},n.Cross=function(t,i){var r=n.Zero();return n.CrossToRef(t,i,r),r},n.CrossToRef=function(t,i,n){n.x=t.y*i.z-t.z*i.y,n.y=t.z*i.x-t.x*i.z,n.z=t.x*i.y-t.y*i.x},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Project=function(t,i,r,o){var s=o.width,e=o.height,h=o.x,u=o.y,m=a.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+u,0,1),y=i.multiply(r).multiply(m);return n.TransformCoordinates(t,y)},n.UnprojectFromTransform=function(t,r,o,s,e){var h=s.multiply(e);h.invert(),t.x=t.x/r*2-1,t.y=-(t.y/o*2-1);var a=n.TransformCoordinates(t,h),u=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(u,1)&&(a=a.scale(1/u)),a},n.Unproject=function(t,r,o,s,e,h){var a=s.multiply(e).multiply(h);a.invert();var u=new n(t.x/r*2-1,-(t.y/o*2-1),t.z),m=n.TransformCoordinates(u,a),y=u.x*a.m[3]+u.y*a.m[7]+u.z*a.m[11]+a.m[15];return i.WithinEpsilon(y,1)&&(m=m.scale(1/y)),m},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n.RotationFromAxis=function(t,i,r){var o=n.Zero();return n.RotationFromAxisToRef(t,i,r,o),o},n.RotationFromAxisToRef=function(r,o,s,e){var h=r.normalize(),a=s.normalize(),u=c.X,m=c.Y,y=0,p=0,f=0,l=0,x=0,z=0,w=0,v=-1,d=0,g=_.Vector3[0],T=0,R=_.Vector3[1];i.WithinEpsilon(a.z,0,t.Epsilon)?z=1:i.WithinEpsilon(a.x,0,t.Epsilon)?l=1:(w=a.z/a.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),R.x=l,R.y=x,R.z=z,R.normalize(),n.CrossToRef(h,R,g),g.normalize(),n.Dot(a,g)<0&&(v=1),T=n.Dot(h,R),T=Math.min(1,Math.max(-1,T)),f=Math.acos(T)*v,n.Dot(R,u)<0&&(f=Math.PI+f,R=R.scaleInPlace(-1),d++);var M=_.Vector3[2],F=_.Vector3[3];l=0,x=0,z=0,v=-1,i.WithinEpsilon(a.z,0,t.Epsilon)?l=1:(w=R.z/R.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),M.x=l,M.y=x,M.z=z,M.normalize(),n.CrossToRef(M,R,F),F.normalize(),n.CrossToRef(a,M,g),g.normalize(),n.Dot(R,g)<0&&(v=1),T=n.Dot(a,M),T=Math.min(1,Math.max(-1,T)),p=Math.acos(T)*v,n.Dot(F,m)<0&&(p=Math.PI+p,d++),v=-1,n.CrossToRef(u,R,g),g.normalize(),n.Dot(g,m)<0&&(v=1),T=n.Dot(R,u),T=Math.min(1,Math.max(-1,T)),y=-Math.acos(T)*v,0>T&&2>d&&(y=Math.PI+y),e.x=p,e.y=y,e.z=f},n}();t.Vector3=s;var e=function(){function n(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},n.prototype.subtractFromFloats=function(t,i,r,o){return new n(this.x-t,this.y-i,this.z-r,this.w-o)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,this},n.prototype.negate=function(){return new n(-this.x,-this.y,-this.z,-this.w)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t,this.w*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)&&i.WithinEpsilon(this.w,n.w,r)},n.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},n.prototype.multiplyByFloats=function(t,i,r,o){return new n(this.x*t,this.y*i,this.z*r,this.w*o)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},n.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},n.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},n.prototype.toVector3=function(){return new s(this.x,this.y,this.z)},n.prototype.clone=function(){return new n(this.x,this.y,this.z,this.w)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},n.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2],t[i+3])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},n.Zero=function(){return new n(0,0,0,0)},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z,s=t.w-i.w;return n*n+r*r+o*o+s*s},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n}();t.Vector4=e;var h=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(n,r,o,s),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=s.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var n,r,o,s=this.x,e=this.y,h=this.z,a=this.w;switch(i){case\"YZX\":var u=s*e+h*a;if(u>.499&&(n=2*Math.atan2(s,a),r=Math.PI/2,o=0),-.499>u&&(n=-2*Math.atan2(s,a),r=-Math.PI/2,o=0),isNaN(n)){var m=s*s,y=e*e,c=h*h;n=Math.atan2(2*e*a-2*s*h,1-2*y-2*c),r=Math.asin(2*u),o=Math.atan2(2*s*a-2*e*h,1-2*m-2*c)}break;default:throw new Error(\"Euler order \"+i+\" not supported yet.\")}return t.y=n,t.z=r,t.x=o,this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=this.z*this.z,o=this.x*this.y,s=this.z*this.w,e=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+s),t.m[2]=2*(e-h),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(e+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],s=r[4],e=r[8],h=r[1],a=r[5],u=r[9],m=r[2],y=r[6],c=r[10],p=o+a+c;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(y-u)*n,i.y=(e-m)*n,i.z=(h-s)*n):o>a&&o>c?(n=2*Math.sqrt(1+o-a-c),i.w=(y-u)/n,i.x=.25*n,i.y=(s+h)/n,i.z=(e+m)/n):a>c?(n=2*Math.sqrt(1+a-o-c),i.w=(e-m)/n,i.x=(s+h)/n,i.y=.25*n,i.z=(u+y)/n):(n=2*Math.sqrt(1+c-o-a),i.w=(h-s)/n,i.x=(e+m)/n,i.y=(u+y)/n,i.z=.25*n)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){var r=new t,o=Math.sin(n/2);return i.normalize(),r.w=Math.cos(n/2),r.x=i.x*o,r.y=i.y*o,r.z=i.z*o,r},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,s=.5*i,e=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(s),m=Math.cos(s),y=Math.sin(e),c=Math.cos(e);r.x=c*u*a+y*m*h,r.y=y*m*a-c*u*h,r.z=c*m*h-y*u*a,r.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),s=.5*(n-t),e=.5*i;r.x=Math.cos(s)*Math.sin(e),r.y=Math.sin(s)*Math.sin(e),r.z=Math.sin(o)*Math.cos(e),r.w=Math.cos(o)*Math.cos(e)},t.Slerp=function(i,n,r){var o,s,e=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.w,a=!1;if(0>h&&(a=!0,h=-h),h>.999999)s=1-e,o=a?-e:e;else{var u=Math.acos(h),m=1/Math.sin(u);s=Math.sin((1-e)*u)*m,o=a?-Math.sin(e*u)*m:Math.sin(e*u)*m}return new t(s*i.x+o*n.x,s*i.y+o*n.y,s*i.z+o*n.z,s*i.w+o*n.w)},t}();t.Quaternion=h;var a=function(){function t(){this.m=new Float32Array(16)}return t.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0===this.m[1]&&0===this.m[2]&&0===this.m[3]&&0===this.m[4]&&0===this.m[6]&&0===this.m[7]&&0===this.m[8]&&0===this.m[9]&&0===this.m[11]&&0===this.m[12]&&0===this.m[13]&&0===this.m[14]},t.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*s)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*s)},t.prototype.toArray=function(){return this.m},t.prototype.asArray=function(){return this.toArray()},t.prototype.invert=function(){return this.invertToRef(this),this},t.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},t.prototype.add=function(i){var n=new t;return this.addToRef(i,n),n},t.prototype.addToRef=function(t,i){for(var n=0;16>n;n++)i.m[n]=this.m[n]+t.m[n];return this},t.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},t.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],s=this.m[4],e=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],l=this.m[14],x=this.m[15],z=y*x-c*l,w=m*x-c*f,v=m*l-y*f,d=u*x-c*p,g=u*l-y*p,T=u*f-m*p,R=e*z-h*w+a*v,_=-(s*z-h*d+a*g),M=s*w-e*d+a*T,F=-(s*v-e*g+h*T),b=1/(i*R+n*_+r*M+o*F),A=h*x-a*l,L=e*x-a*f,P=e*l-h*f,Z=s*x-a*p,C=s*l-h*p,S=s*f-e*p,I=h*c-a*y,q=e*c-a*m,E=e*y-h*m,D=s*c-a*u,V=s*y-h*u,W=s*m-e*u;return t.m[0]=R*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=F*b,t.m[1]=-(n*z-r*w+o*v)*b,t.m[5]=(i*z-r*d+o*g)*b,t.m[9]=-(i*w-n*d+o*T)*b,t.m[13]=(i*v-n*g+r*T)*b,t.m[2]=(n*A-r*L+o*P)*b,t.m[6]=-(i*A-r*Z+o*C)*b,t.m[10]=(i*L-n*Z+o*S)*b,t.m[14]=-(i*P-n*C+r*S)*b,t.m[3]=-(n*I-r*q+o*E)*b,t.m[7]=(i*I-r*D+o*V)*b,t.m[11]=-(i*q-n*D+o*W)*b,t.m[15]=(i*E-n*V+r*W)*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 s(this.m[12],this.m[13],this.m[14])},t.prototype.multiply=function(i){var n=new t;return this.multiplyToRef(i,n),n},t.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},t.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;16>n;n++)t[i+n]=this.m[n];return this},t.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},t.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],s=this.m[2],e=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],l=this.m[12],x=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],T=t.m[3],R=t.m[4],_=t.m[5],M=t.m[6],F=t.m[7],b=t.m[8],A=t.m[9],L=t.m[10],P=t.m[11],Z=t.m[12],C=t.m[13],S=t.m[14],I=t.m[15];return i[n]=r*v+o*R+s*b+e*Z,i[n+1]=r*d+o*_+s*A+e*C,i[n+2]=r*g+o*M+s*L+e*S,i[n+3]=r*T+o*F+s*P+e*I,i[n+4]=h*v+a*R+u*b+m*Z,i[n+5]=h*d+a*_+u*A+m*C,i[n+6]=h*g+a*M+u*L+m*S,i[n+7]=h*T+a*F+u*P+m*I,i[n+8]=y*v+c*R+p*b+f*Z,i[n+9]=y*d+c*_+p*A+f*C,i[n+10]=y*g+c*M+p*L+f*S,i[n+11]=y*T+c*F+p*P+f*I,i[n+12]=l*v+x*R+z*b+w*Z,i[n+13]=l*d+x*_+z*A+w*C,i[n+14]=l*g+x*M+z*L+w*S,i[n+15]=l*T+x*F+z*P+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.decompose=function(n,r,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var s=i.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,e=i.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,a=i.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(n.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=e*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=a*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z)return r.x=0,r.y=0,r.z=0,r.w=1,!1;var u=t.FromValues(this.m[0]/n.x,this.m[1]/n.x,this.m[2]/n.x,0,this.m[4]/n.y,this.m[5]/n.y,this.m[6]/n.y,0,this.m[8]/n.z,this.m[9]/n.z,this.m[10]/n.z,0,0,0,0,1);return h.FromRotationMatrixToRef(u,r),!0},t.FromArray=function(i,n){var r=new t;return n||(n=0),t.FromArrayToRef(i,n,r),r},t.FromArrayToRef=function(t,i,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]},t.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;16>o;o++)r.m[o]=t[o+i]*n},t.FromValuesToRef=function(t,i,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=n,x.m[3]=r,x.m[4]=o,x.m[5]=s,x.m[6]=e,x.m[7]=h,x.m[8]=a,x.m[9]=u,x.m[10]=m,x.m[11]=y,x.m[12]=c,x.m[13]=p,x.m[14]=f,x.m[15]=l},t.prototype.getRow=function(t){if(0>t||t>3)return null;var i=4*t;return new e(this.m[i+0],this.m[i+1],this.m[i+2],this.m[i+3])},t.prototype.setRow=function(t,i){if(0>t||t>3)return this;var n=4*t;return this.m[n+0]=i.x,this.m[n+1]=i.y,this.m[n+2]=i.z,this.m[n+3]=i.w,this},t.FromValues=function(i,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){var z=new t;return z.m[0]=i,z.m[1]=n,z.m[2]=r,z.m[3]=o,z.m[4]=s,z.m[5]=e,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=l,z.m[15]=x,z},t.Compose=function(i,n,r){var o=t.FromValues(i.x,0,0,0,0,i.y,0,0,0,0,i.z,0,0,0,0,1),s=t.Identity();return n.toRotationMatrix(s),o=o.multiply(s),o.setTranslation(r),o},t.Identity=function(){return t.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},t.IdentityToRef=function(i){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,i)},t.Zero=function(){return t.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},t.RotationX=function(i){var n=new t;return t.RotationXToRef(i,n),\nn},t.Invert=function(i){var n=new t;return i.invertToRef(n),n},t.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationY=function(i){var n=new t;return t.RotationYToRef(i,n),n},t.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationZ=function(i){var n=new t;return t.RotationZToRef(i,n),n},t.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,i.m[5]=r,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationAxis=function(i,n){var r=t.Zero();return t.RotationAxisToRef(i,n,r),r},t.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),s=1-o;t.normalize(),n.m[0]=t.x*t.x*s+o,n.m[1]=t.x*t.y*s-t.z*r,n.m[2]=t.x*t.z*s+t.y*r,n.m[3]=0,n.m[4]=t.y*t.x*s+t.z*r,n.m[5]=t.y*t.y*s+o,n.m[6]=t.y*t.z*s-t.x*r,n.m[7]=0,n.m[8]=t.z*t.x*s-t.y*r,n.m[9]=t.z*t.y*s+t.x*r,n.m[10]=t.z*t.z*s+o,n.m[11]=0,n.m[15]=1},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){h.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},t.Scaling=function(i,n,r){var o=t.Zero();return t.ScalingToRef(i,n,r,o),o},t.ScalingToRef=function(t,i,n,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=n,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},t.Translation=function(i,n,r){var o=t.Identity();return t.TranslationToRef(i,n,r,o),o},t.TranslationToRef=function(i,n,r,o){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,i,n,r,1,o)},t.Lerp=function(i,n,r){var o=new s(0,0,0),e=new h,a=new s(0,0,0);i.decompose(o,e,a);var u=new s(0,0,0),m=new h,y=new s(0,0,0);n.decompose(u,m,y);var c=s.Lerp(o,u,r),p=h.Slerp(e,m,r),f=s.Lerp(a,y,r);return t.Compose(c,p,f)},t.LookAtLH=function(i,n,r){var o=t.Zero();return t.LookAtLHToRef(i,n,r,o),o},t.LookAtLHToRef=function(i,n,r,o){n.subtractToRef(i,this._zAxis),this._zAxis.normalize(),s.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),s.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-s.Dot(this._xAxis,i),h=-s.Dot(this._yAxis,i),a=-s.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,e,h,a,1,o)},t.OrthoLH=function(i,n,r,o){var s=t.Zero();return t.OrthoLHToRef(i,n,r,o,s),s},t.OrthoLHToRef=function(i,n,r,o,s){var e=2/i,h=2/n,a=1/(o-r),u=r/(r-o);t.FromValuesToRef(e,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,s)},t.OrthoOffCenterLH=function(i,n,r,o,s,e){var h=t.Zero();return t.OrthoOffCenterLHToRef(i,n,r,o,s,e,h),h},t.OrthoOffCenterLHToRef=function(t,i,n,r,o,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(r-n),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(o-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(r+n)/(n-r),e.m[14]=o/(o-s),e.m[15]=1},t.PerspectiveLH=function(i,n,r,o){var s=t.Zero();return s.m[0]=2*r/i,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*r/n,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-o/(r-o),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o),s},t.PerspectiveFovLH=function(i,n,r,o){var s=t.Zero();return t.PerspectiveFovLHToRef(i,n,r,o,s),s},t.PerspectiveFovLHToRef=function(t,i,n,r,o,s){void 0===s&&(s=!0);var e=1/Math.tan(.5*t);s?o.m[0]=e/i:o.m[0]=e,o.m[1]=o.m[2]=o.m[3]=0,s?o.m[5]=e:o.m[5]=e*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=-r/(n-r),o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=n*r/(n-r)},t.GetFinalMatrix=function(i,n,r,o,s,e){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,e-s,0,u+h/2,a/2+m,s,1);return n.multiply(r).multiply(o).multiply(y)},t.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},t.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},t.Transpose=function(i){var n=new t;return n.m[0]=i.m[0],n.m[1]=i.m[4],n.m[2]=i.m[8],n.m[3]=i.m[12],n.m[4]=i.m[1],n.m[5]=i.m[5],n.m[6]=i.m[9],n.m[7]=i.m[13],n.m[8]=i.m[2],n.m[9]=i.m[6],n.m[10]=i.m[10],n.m[11]=i.m[14],n.m[12]=i.m[3],n.m[13]=i.m[7],n.m[14]=i.m[11],n.m[15]=i.m[15],n},t.Reflection=function(i){var n=new t;return t.ReflectionToRef(i,n),n},t.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,s=-2*n,e=-2*r,h=-2*o;i.m[0]=s*n+1,i.m[1]=e*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=s*r,i.m[5]=e*r+1,i.m[6]=h*r,i.m[7]=0,i.m[8]=s*o,i.m[9]=e*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=h*t.d,i.m[15]=1},t._tempQuaternion=new h,t._xAxis=s.Zero(),t._yAxis=s.Zero(),t._zAxis=s.Zero(),t}();t.Matrix=a;var u=function(){function t(t,i,n,r){this.normal=new s(t,i,n),this.d=r}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var n=a.Transpose(i),r=this.normal.x,o=this.normal.y,s=this.normal.z,e=this.d,h=r*n.m[0]+o*n.m[1]+s*n.m[2]+e*n.m[3],u=r*n.m[4]+o*n.m[5]+s*n.m[6]+e*n.m[7],m=r*n.m[8]+o*n.m[9]+s*n.m[10]+e*n.m[11],y=r*n.m[12]+o*n.m[13]+s*n.m[14]+e*n.m[15];return new t(h,u,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,n){var r,o=i.x-t.x,s=i.y-t.y,e=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=s*u-e*a,y=e*h-o*u,c=o*a-s*h,p=Math.sqrt(m*m+y*y+c*c);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=y*r,this.normal.z=c*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var n=s.Dot(this.normal,t);return i>=n},t.prototype.signedDistanceTo=function(t){return s.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,n,r){var o=new t(0,0,0,0);return o.copyFromPoints(i,n,r),o},t.FromPositionAndNormal=function(i,n){var r=new t(0,0,0,0);return n.normalize(),r.normal=n,r.d=-(n.x*i.x+n.y*i.y+n.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,n){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return s.Dot(n,i)+r},t}();t.Plane=u;var m=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i,n){return new t(this.x*i,this.y*n,this.width*i,this.height*n)},t}();t.Viewport=m;var y=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new u(0,0,0,0));return t.GetPlanesToRef(i,n),n},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=y,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var c=(t.Space,function(){function t(){}return t.X=new s(1,0,0),t.Y=new s(0,1,0),t.Z=new s(0,0,1),t}());t.Axis=c;var p=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var s=1-3*r+3*i,e=3*r-6*i,h=3*i,a=t,u=0;5>u;u++){var m=a*a,y=m*a,c=s*y+e*m+h*a,p=1/(3*s*m+2*e*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=p,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var f=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,n){var r=n.subtract(i),o=Math.atan2(r.y,r.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=l;var x=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var r=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new o((s*(i.y-n.y)-e*(t.y-i.y))/h,((t.x-i.x)*e-(i.x-n.x)*s)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=l.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=l.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=l.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),-180>u-a&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-a?f.CW:f.CCW,this.angle=l.FromDegrees(this.orientation===f.CW?a-m:m-a)}return t}();t.Arc2=x;var z=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var n=new o(t,i),r=this._points[this._points.length-1];return this._points.push(n),this._length+=n.subtract(r).length(),this},t.prototype.addArcTo=function(t,i,n,r,s){if(void 0===s&&(s=36),closed)return this;var e=this._points[this._points.length-1],h=new o(t,i),a=new o(n,r),u=new x(e,h,a),m=u.angle.radians()/s;u.orientation===f.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;s>c;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,l=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,l),y+=m}return this},t.prototype.close=function(){return this.closed=!0,this},t.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],n=this._points[0];t+=n.subtract(i).length()}return t},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(0>t||t>1)return o.Zero();for(var i=t*this.length(),n=0,r=0;r<this._points.length;r++){var s=(r+1)%this._points.length,e=this._points[r],h=this._points[s],a=h.subtract(e),u=a.length()+n;if(i>=n&&u>=i){var m=a.normalize(),y=i-n;return new o(e.x+m.x*y,e.y+m.y*y)}n=u}return o.Zero()},t.StartingAt=function(i,n){return new t(i,n)},t}();t.Path2=z;var w=function(){function n(t,i,n){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!1,this._compute(i)}return n.prototype.getCurve=function(){return this._curve},n.prototype.getTangents=function(){return this._tangents},n.prototype.getNormals=function(){return this._normals},n.prototype.getBinormals=function(){return this._binormals},n.prototype.getDistances=function(){return this._distances},n.prototype.update=function(t,i){for(var n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].z;return this._compute(i),this},n.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=s.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,e,h,a,u=1;i>u;u++)o=this._getLastNonNullVector(u),i-1>u&&(e=this._getFirstNonNullVector(u),this._tangents[u]=o.add(e),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]=s.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=s.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},n.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},n.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},n.prototype._normalVector=function(n,r,o){var e;if(void 0===o||null===o){var h;i.WithinEpsilon(r.y,1,t.Epsilon)?i.WithinEpsilon(r.x,1,t.Epsilon)?i.WithinEpsilon(r.z,1,t.Epsilon)||(h=new s(0,0,1)):h=new s(1,0,0):h=new s(0,-1,0),e=s.Cross(r,h)}else e=s.Cross(r,o),s.CrossToRef(e,r,e);return e.normalize(),e},n}();t.Path3D=w;var v=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,o){o=o>2?o:3;for(var e=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;o>=a;a++)e.push(new s(h(a/o,i.x,n.x,r.x),h(a/o,i.y,n.y,r.y),h(a/o,i.z,n.z,r.z)));return new t(e)},t.CreateCubicBezier=function(i,n,r,o,e){e=e>3?e:4;for(var h=new Array,a=function(t,i,n,r,o){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return s},u=0;e>=u;u++)h.push(new s(a(u/e,i.x,n.x,r.x,o.x),a(u/e,i.y,n.y,r.y,o.y),a(u/e,i.z,n.z,r.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,o,e){for(var h=new Array,a=1/e,u=0;e>=u;u++)h.push(s.Hermite(i,n,r,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),s=1;s<o.length;s++)r.push(o[s].subtract(o[0]).add(n));var e=new t(r);return e},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=v;var d=function(){function t(){this.L00=s.Zero(),this.L1_1=s.Zero(),this.L10=s.Zero(),this.L11=s.Zero(),this.L2_2=s.Zero(),this.L2_1=s.Zero(),this.L20=s.Zero(),this.L21=s.Zero(),this.L22=s.Zero()}return t.prototype.addLight=function(t,i,n){var r=new s(i.r,i.g,i.b),o=r.scale(n);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=d;var g=function(){function t(){this.x=s.Zero(),this.y=s.Zero(),this.z=s.Zero(),this.xx=s.Zero(),this.yy=s.Zero(),this.zz=s.Zero(),this.xy=s.Zero(),this.yz=s.Zero(),this.zx=s.Zero()}return t.prototype.addAmbient=function(t){var i=new s(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var n=new t;return n.x=i.L11.scale(1.02333),n.y=i.L1_1.scale(1.02333),n.z=i.L10.scale(1.02333),n.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),n.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),n.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),n.yz=i.L2_1.scale(.858086),n.zx=i.L21.scale(.858086),n.xy=i.L2_2.scale(.858086),n},t}();t.SphericalPolynomial=g;var T=function(){function t(t,i){void 0===t&&(t=s.Zero()),void 0===i&&(i=s.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 R=function(){function t(t,i,n){void 0===t&&(t=s.Zero()),void 0===i&&(i=s.Up()),void 0===n&&(n=o.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=R;var _=function(){function t(){}return t.Color3=[n.Black(),n.Black(),n.Black()],t.Vector2=[o.Zero(),o.Zero(),o.Zero()],t.Vector3=[s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero()],t.Vector4=[e.Zero(),e.Zero(),e.Zero()],t.Quaternion=[new h(0,0,0,0)],t.Matrix=[a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero()],t}();t.Tmp=_}(BABYLON||(BABYLON={}));";
- if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
- module.exports = BABYLON;
- };
|