12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475 |
- var __extends = (this && this.__extends) || (function () {
- var extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- 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 BABYLON;
- (function (BABYLON) {
- var EffectFallbacks = /** @class */ (function () {
- function EffectFallbacks() {
- this._defines = {};
- this._currentRank = 32;
- this._maxRank = -1;
- }
- EffectFallbacks.prototype.unBindMesh = function () {
- this._mesh = null;
- };
- 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._mesh = mesh;
- if (rank < this._currentRank) {
- this._currentRank = rank;
- }
- 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) {
- // First we try to switch to CPU skinning
- if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
- 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);
- var scene = this._mesh.getScene();
- for (var index = 0; index < scene.meshes.length; index++) {
- var otherMesh = scene.meshes[index];
- if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
- otherMesh.computeBonesUsingShaders = false;
- }
- }
- }
- else {
- var currentFallbacks = this._defines[this._currentRank];
- if (currentFallbacks) {
- for (var index = 0; index < currentFallbacks.length; index++) {
- currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
- }
- }
- this._currentRank++;
- }
- return currentDefines;
- };
- return EffectFallbacks;
- }());
- BABYLON.EffectFallbacks = EffectFallbacks;
- var EffectCreationOptions = /** @class */ (function () {
- function EffectCreationOptions() {
- }
- return EffectCreationOptions;
- }());
- BABYLON.EffectCreationOptions = EffectCreationOptions;
- var Effect = /** @class */ (function () {
- function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
- if (samplers === void 0) { samplers = null; }
- if (defines === void 0) { defines = null; }
- if (fallbacks === void 0) { fallbacks = null; }
- if (onCompiled === void 0) { onCompiled = null; }
- if (onError === void 0) { onError = null; }
- var _this = this;
- this.uniqueId = 0;
- this.onCompileObservable = new BABYLON.Observable();
- this.onErrorObservable = new BABYLON.Observable();
- this.onBindObservable = new BABYLON.Observable();
- this._uniformBuffersNames = {};
- this._isReady = false;
- this._compilationError = "";
- this.name = baseName;
- if (attributesNamesOrOptions.attributes) {
- var options = attributesNamesOrOptions;
- this._engine = uniformsNamesOrEngine;
- this._attributesNames = options.attributes;
- this._uniformsNames = options.uniformsNames.concat(options.samplers);
- this._samplers = options.samplers;
- this.defines = options.defines;
- this.onError = options.onError;
- this.onCompiled = options.onCompiled;
- this._fallbacks = options.fallbacks;
- this._indexParameters = options.indexParameters;
- this._transformFeedbackVaryings = options.transformFeedbackVaryings;
- if (options.uniformBuffersNames) {
- for (var i = 0; i < options.uniformBuffersNames.length; i++) {
- this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
- }
- }
- }
- else {
- this._engine = engine;
- this.defines = defines;
- this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
- this._samplers = samplers;
- this._attributesNames = attributesNamesOrOptions;
- this.onError = onError;
- this.onCompiled = onCompiled;
- this._indexParameters = indexParameters;
- this._fallbacks = fallbacks;
- }
- this.uniqueId = Effect._uniqueIdSeed++;
- 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._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
- _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
- _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
- _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
- if (baseName) {
- var vertex = baseName.vertexElement || baseName.vertex || baseName;
- var fragment = baseName.fragmentElement || baseName.fragment || baseName;
- _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
- _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
- }
- else {
- _this._vertexSourceCode = migratedVertexCode;
- _this._fragmentSourceCode = migratedFragmentCode;
- }
- _this._prepareEffect();
- });
- });
- });
- });
- });
- });
- }
- Object.defineProperty(Effect.prototype, "key", {
- get: function () {
- return this._key;
- },
- enumerable: true,
- configurable: true
- });
- // Properties
- Effect.prototype.isReady = function () {
- return this._isReady;
- };
- Effect.prototype.getEngine = function () {
- return this._engine;
- };
- 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.executeWhenCompiled = function (func) {
- if (this.isReady()) {
- func(this);
- return;
- }
- this.onCompileObservable.add(function (effect) {
- func(effect);
- });
- };
- Effect.prototype._loadVertexShader = function (vertex, callback) {
- if (BABYLON.Tools.IsWindowObjectExist()) {
- // DOM element ?
- if (vertex instanceof HTMLElement) {
- var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
- callback(vertexCode);
- return;
- }
- }
- // Base64 encoded ?
- if (vertex.substr(0, 7) === "base64:") {
- var vertexBinary = window.atob(vertex.substr(7));
- callback(vertexBinary);
- 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
- this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
- };
- Effect.prototype._loadFragmentShader = function (fragment, callback) {
- if (BABYLON.Tools.IsWindowObjectExist()) {
- // DOM element ?
- if (fragment instanceof HTMLElement) {
- var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
- callback(fragmentCode);
- return;
- }
- }
- // Base64 encoded ?
- if (fragment.substr(0, 7) === "base64:") {
- var fragmentBinary = window.atob(fragment.substr(7));
- callback(fragmentBinary);
- 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
- this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
- };
- Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
- // Rebuild shaders source code
- var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
- var prefix = shaderVersion + (defines ? defines + "\n" : "");
- vertexCode = prefix + vertexCode;
- fragmentCode = prefix + fragmentCode;
- // Number lines of shaders source code
- var i = 2;
- var regex = /\n/gm;
- var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
- i = 2;
- var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
- // Dump shaders name and formatted source code
- if (this.name.vertexElement) {
- BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
- BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
- }
- else if (this.name.vertex) {
- BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
- BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
- }
- else {
- BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
- BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
- }
- };
- ;
- Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
- var preparedSourceCode = this._processPrecision(sourceCode);
- if (this._engine.webGLVersion == 1) {
- callback(preparedSourceCode);
- return;
- }
- // Already converted
- if (preparedSourceCode.indexOf("#version 3") !== -1) {
- callback(preparedSourceCode.replace("#version 300 es", ""));
- return;
- }
- var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
- // Remove extensions
- // #extension GL_OES_standard_derivatives : enable
- // #extension GL_EXT_shader_texture_lod : enable
- // #extension GL_EXT_frag_depth : enable
- // #extension GL_EXT_draw_buffers : require
- var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
- var result = preparedSourceCode.replace(regex, "");
- // Migrate to GLSL v300
- result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
- result = result.replace(/attribute[ \t]/g, "in ");
- result = result.replace(/[ \t]attribute/g, " in");
- if (isFragment) {
- result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
- result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
- result = result.replace(/texture2D\s*\(/g, "texture(");
- result = result.replace(/textureCube\s*\(/g, "texture(");
- result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
- result = result.replace(/gl_FragColor/g, "glFragColor");
- result = result.replace(/gl_FragData/g, "glFragData");
- result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
- }
- callback(result);
- };
- 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];
- // Uniform declaration
- if (includeFile.indexOf("__decl__") !== -1) {
- includeFile = includeFile.replace(/__decl__/, "");
- if (this._engine.supportsUniformBuffers) {
- includeFile = includeFile.replace(/Vertex/, "Ubo");
- includeFile = includeFile.replace(/Fragment/, "Ubo");
- }
- includeFile = includeFile + "Declaration";
- }
- 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]) {
- var indexString = match[5];
- if (indexString.indexOf("..") !== -1) {
- var indexSplits = indexString.split("..");
- var minIndex = parseInt(indexSplits[0]);
- var maxIndex = parseInt(indexSplits[1]);
- var sourceIncludeContent = includeContent.slice(0);
- includeContent = "";
- if (isNaN(maxIndex)) {
- maxIndex = this._indexParameters[indexSplits[1]];
- }
- for (var i = minIndex; i < maxIndex; i++) {
- if (!this._engine.supportsUniformBuffers) {
- // Ubo replacement
- sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
- return p1 + "{X}";
- });
- }
- includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
- }
- }
- else {
- if (!this._engine.supportsUniformBuffers) {
- // Ubo replacement
- includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
- return p1 + "{X}";
- });
- }
- includeContent = includeContent.replace(/\{X\}/g, indexString);
- }
- }
- // Replace
- returnValue = returnValue.replace(match[0], includeContent);
- }
- else {
- var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
- this._engine._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._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
- var _this = this;
- this._isReady = false;
- this._vertexSourceCodeOverride = vertexSourceCode;
- this._fragmentSourceCodeOverride = fragmentSourceCode;
- this.onError = function (effect, error) {
- if (onError) {
- onError(error);
- }
- };
- this.onCompiled = function () {
- var scenes = _this.getEngine().scenes;
- for (var i = 0; i < scenes.length; i++) {
- scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
- }
- if (onCompiled) {
- onCompiled(_this._program);
- }
- };
- this._fallbacks = null;
- this._prepareEffect();
- };
- Effect.prototype.getSpecificUniformLocations = function (names) {
- var engine = this._engine;
- return engine.getUniforms(this._program, names);
- };
- Effect.prototype._prepareEffect = function () {
- var attributesNames = this._attributesNames;
- var defines = this.defines;
- var fallbacks = this._fallbacks;
- this._valueCache = {};
- var previousProgram = this._program;
- try {
- var engine = this._engine;
- if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
- this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
- }
- else {
- this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
- }
- this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
- if (engine.supportsUniformBuffers) {
- for (var name in this._uniformBuffersNames) {
- this.bindUniformBlock(name, this._uniformBuffersNames[name]);
- }
- }
- this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
- this._attributes = engine.getAttributes(this._program, attributesNames);
- var index;
- for (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._compilationError = "";
- this._isReady = true;
- if (this.onCompiled) {
- this.onCompiled(this);
- }
- this.onCompileObservable.notifyObservers(this);
- this.onCompileObservable.clear();
- // Unbind mesh reference in fallbacks
- if (this._fallbacks) {
- this._fallbacks.unBindMesh();
- }
- if (previousProgram) {
- this.getEngine()._deleteProgram(previousProgram);
- }
- }
- catch (e) {
- this._compilationError = e.message;
- // Let's go through fallbacks then
- BABYLON.Tools.Error("Unable to compile effect:");
- BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
- return " " + uniform;
- }));
- BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
- return " " + attribute;
- }));
- this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
- BABYLON.Tools.Error("Error: " + this._compilationError);
- if (previousProgram) {
- this._program = previousProgram;
- this._isReady = true;
- if (this.onError) {
- this.onError(this, this._compilationError);
- }
- this.onErrorObservable.notifyObservers(this);
- }
- if (fallbacks && fallbacks.isMoreFallbacks) {
- BABYLON.Tools.Error("Trying next fallback.");
- this.defines = fallbacks.reduce(this.defines);
- this._prepareEffect();
- }
- else {
- if (this.onError) {
- this.onError(this, this._compilationError);
- }
- this.onErrorObservable.notifyObservers(this);
- this.onErrorObservable.clear();
- // Unbind mesh reference in fallbacks
- if (this._fallbacks) {
- this._fallbacks.unBindMesh();
- }
- }
- }
- };
- 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), this.getUniform(channel), texture);
- };
- Effect.prototype.setTextureArray = function (channel, textures) {
- if (this._samplers.indexOf(channel + "Ex") === -1) {
- var initialPos = this._samplers.indexOf(channel);
- for (var index = 1; index < textures.length; index++) {
- this._samplers.splice(initialPos + index, 0, channel + "Ex");
- }
- }
- this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
- };
- Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
- this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
- };
- Effect.prototype._cacheMatrix = function (uniformName, matrix) {
- var cache = this._valueCache[uniformName];
- var flag = matrix.updateFlag;
- if (cache !== undefined && cache === flag) {
- return false;
- }
- this._valueCache[uniformName] = flag;
- return true;
- };
- Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
- var cache = this._valueCache[uniformName];
- if (!cache) {
- cache = [x, y];
- this._valueCache[uniformName] = cache;
- return true;
- }
- var changed = false;
- if (cache[0] !== x) {
- cache[0] = x;
- changed = true;
- }
- if (cache[1] !== y) {
- cache[1] = y;
- changed = true;
- }
- return changed;
- };
- Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
- var cache = this._valueCache[uniformName];
- if (!cache) {
- cache = [x, y, z];
- this._valueCache[uniformName] = cache;
- return true;
- }
- var changed = false;
- if (cache[0] !== x) {
- cache[0] = x;
- changed = true;
- }
- if (cache[1] !== y) {
- cache[1] = y;
- changed = true;
- }
- if (cache[2] !== z) {
- cache[2] = z;
- changed = true;
- }
- return changed;
- };
- Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
- var cache = this._valueCache[uniformName];
- if (!cache) {
- cache = [x, y, z, w];
- this._valueCache[uniformName] = cache;
- return true;
- }
- var changed = false;
- if (cache[0] !== x) {
- cache[0] = x;
- changed = true;
- }
- if (cache[1] !== y) {
- cache[1] = y;
- changed = true;
- }
- if (cache[2] !== z) {
- cache[2] = z;
- changed = true;
- }
- if (cache[3] !== w) {
- cache[3] = w;
- changed = true;
- }
- return changed;
- };
- Effect.prototype.bindUniformBuffer = function (buffer, name) {
- var bufferName = this._uniformBuffersNames[name];
- if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
- return;
- }
- Effect._baseCache[bufferName] = buffer;
- this._engine.bindUniformBufferBase(buffer, bufferName);
- };
- Effect.prototype.bindUniformBlock = function (blockName, index) {
- this._engine.bindUniformBlock(this._program, blockName, index);
- };
- Effect.prototype.setInt = function (uniformName, value) {
- var cache = this._valueCache[uniformName];
- if (cache !== undefined && cache === value)
- return this;
- this._valueCache[uniformName] = value;
- this._engine.setInt(this.getUniform(uniformName), value);
- return this;
- };
- Effect.prototype.setIntArray = function (uniformName, array) {
- this._valueCache[uniformName] = null;
- this._engine.setIntArray(this.getUniform(uniformName), array);
- return this;
- };
- Effect.prototype.setIntArray2 = function (uniformName, array) {
- this._valueCache[uniformName] = null;
- this._engine.setIntArray2(this.getUniform(uniformName), array);
- return this;
- };
- Effect.prototype.setIntArray3 = function (uniformName, array) {
- this._valueCache[uniformName] = null;
- this._engine.setIntArray3(this.getUniform(uniformName), array);
- return this;
- };
- Effect.prototype.setIntArray4 = function (uniformName, array) {
- this._valueCache[uniformName] = null;
- this._engine.setIntArray4(this.getUniform(uniformName), array);
- return this;
- };
- Effect.prototype.setFloatArray = function (uniformName, array) {
- this._valueCache[uniformName] = null;
- this._engine.setFloatArray(this.getUniform(uniformName), array);
- return this;
- };
- Effect.prototype.setFloatArray2 = function (uniformName, array) {
- this._valueCache[uniformName] = null;
- this._engine.setFloatArray2(this.getUniform(uniformName), array);
- return this;
- };
- Effect.prototype.setFloatArray3 = function (uniformName, array) {
- this._valueCache[uniformName] = null;
- this._engine.setFloatArray3(this.getUniform(uniformName), array);
- return this;
- };
- Effect.prototype.setFloatArray4 = function (uniformName, array) {
- this._valueCache[uniformName] = null;
- this._engine.setFloatArray4(this.getUniform(uniformName), array);
- return this;
- };
- Effect.prototype.setArray = function (uniformName, array) {
- this._valueCache[uniformName] = null;
- this._engine.setArray(this.getUniform(uniformName), array);
- return this;
- };
- Effect.prototype.setArray2 = function (uniformName, array) {
- this._valueCache[uniformName] = null;
- this._engine.setArray2(this.getUniform(uniformName), array);
- return this;
- };
- Effect.prototype.setArray3 = function (uniformName, array) {
- this._valueCache[uniformName] = null;
- this._engine.setArray3(this.getUniform(uniformName), array);
- return this;
- };
- Effect.prototype.setArray4 = function (uniformName, array) {
- this._valueCache[uniformName] = null;
- this._engine.setArray4(this.getUniform(uniformName), array);
- return this;
- };
- Effect.prototype.setMatrices = function (uniformName, matrices) {
- if (!matrices) {
- return this;
- }
- this._valueCache[uniformName] = null;
- this._engine.setMatrices(this.getUniform(uniformName), matrices);
- return this;
- };
- Effect.prototype.setMatrix = function (uniformName, matrix) {
- if (this._cacheMatrix(uniformName, matrix)) {
- this._engine.setMatrix(this.getUniform(uniformName), matrix);
- }
- return this;
- };
- Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
- this._valueCache[uniformName] = null;
- this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
- return this;
- };
- Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
- this._valueCache[uniformName] = null;
- this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
- return this;
- };
- Effect.prototype.setFloat = function (uniformName, value) {
- var cache = this._valueCache[uniformName];
- if (cache !== undefined && cache === value)
- return this;
- this._valueCache[uniformName] = value;
- this._engine.setFloat(this.getUniform(uniformName), value);
- return this;
- };
- Effect.prototype.setBool = function (uniformName, bool) {
- var cache = this._valueCache[uniformName];
- if (cache !== undefined && cache === 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._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._cacheFloat2(uniformName, x, y)) {
- this._engine.setFloat2(this.getUniform(uniformName), x, y);
- }
- return this;
- };
- Effect.prototype.setVector3 = function (uniformName, vector3) {
- if (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._cacheFloat3(uniformName, x, y, z)) {
- this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
- }
- return this;
- };
- Effect.prototype.setVector4 = function (uniformName, vector4) {
- if (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._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._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._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
- this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
- }
- return this;
- };
- Effect.ResetCache = function () {
- Effect._baseCache = {};
- };
- Effect._uniqueIdSeed = 0;
- Effect._baseCache = {};
- // Statics
- Effect.ShadersStore = {};
- Effect.IncludesShadersStore = {};
- return Effect;
- }());
- BABYLON.Effect = Effect;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.effect.js.map
- //# sourceMappingURL=babylon.types.js.map
- BABYLON.Effect.ShadersStore['defaultVertexShader'] = "#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\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<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,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 MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\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#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\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#if defined(OPACITY) && OPACITYDIRECTUV == 0\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#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\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(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\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) && SPECULARDIRECTUV == 0\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#if defined(BUMP) && BUMPDIRECTUV == 0\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<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}";
- BABYLON.Effect.ShadersStore['defaultPixelShader'] = "#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\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;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\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=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\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#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).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+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\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+uvOffset).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#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\ngl_FragColor=color;\n}";
- var BABYLON;
- (function (BABYLON) {
- var KeyboardEventTypes = /** @class */ (function () {
- function KeyboardEventTypes() {
- }
- Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
- get: function () {
- return KeyboardEventTypes._KEYDOWN;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(KeyboardEventTypes, "KEYUP", {
- get: function () {
- return KeyboardEventTypes._KEYUP;
- },
- enumerable: true,
- configurable: true
- });
- KeyboardEventTypes._KEYDOWN = 0x01;
- KeyboardEventTypes._KEYUP = 0x02;
- return KeyboardEventTypes;
- }());
- BABYLON.KeyboardEventTypes = KeyboardEventTypes;
- var KeyboardInfo = /** @class */ (function () {
- function KeyboardInfo(type, event) {
- this.type = type;
- this.event = event;
- }
- return KeyboardInfo;
- }());
- BABYLON.KeyboardInfo = KeyboardInfo;
- /**
- * This class is used to store keyboard related info for the onPreKeyboardObservable event.
- * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
- */
- var KeyboardInfoPre = /** @class */ (function (_super) {
- __extends(KeyboardInfoPre, _super);
- function KeyboardInfoPre(type, event) {
- var _this = _super.call(this, type, event) || this;
- _this.skipOnPointerObservable = false;
- return _this;
- }
- return KeyboardInfoPre;
- }(KeyboardInfo));
- BABYLON.KeyboardInfoPre = KeyboardInfoPre;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.keyboardEvents.js.map
- var BABYLON;
- (function (BABYLON) {
- var PointerEventTypes = /** @class */ (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
- });
- Object.defineProperty(PointerEventTypes, "POINTERTAP", {
- get: function () {
- return PointerEventTypes._POINTERTAP;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
- get: function () {
- return PointerEventTypes._POINTERDOUBLETAP;
- },
- enumerable: true,
- configurable: true
- });
- PointerEventTypes._POINTERDOWN = 0x01;
- PointerEventTypes._POINTERUP = 0x02;
- PointerEventTypes._POINTERMOVE = 0x04;
- PointerEventTypes._POINTERWHEEL = 0x08;
- PointerEventTypes._POINTERPICK = 0x10;
- PointerEventTypes._POINTERTAP = 0x20;
- PointerEventTypes._POINTERDOUBLETAP = 0x40;
- return PointerEventTypes;
- }());
- BABYLON.PointerEventTypes = PointerEventTypes;
- var PointerInfoBase = /** @class */ (function () {
- function PointerInfoBase(type, event) {
- this.type = type;
- this.event = event;
- }
- return PointerInfoBase;
- }());
- BABYLON.PointerInfoBase = PointerInfoBase;
- /**
- * This class is used to store pointer related info for the onPrePointerObservable event.
- * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
- */
- var PointerInfoPre = /** @class */ (function (_super) {
- __extends(PointerInfoPre, _super);
- function PointerInfoPre(type, event, localX, localY) {
- var _this = _super.call(this, type, event) || this;
- _this.skipOnPointerObservable = false;
- _this.localPosition = new BABYLON.Vector2(localX, localY);
- return _this;
- }
- return PointerInfoPre;
- }(PointerInfoBase));
- BABYLON.PointerInfoPre = PointerInfoPre;
- /**
- * 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 different event types can be found in the PointerEventTypes class.
- */
- var PointerInfo = /** @class */ (function (_super) {
- __extends(PointerInfo, _super);
- function PointerInfo(type, event, pickInfo) {
- var _this = _super.call(this, type, event) || this;
- _this.pickInfo = pickInfo;
- return _this;
- }
- return PointerInfo;
- }(PointerInfoBase));
- BABYLON.PointerInfo = PointerInfo;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.pointerEvents.js.map
- var BABYLON;
- (function (BABYLON) {
- BABYLON.ToGammaSpace = 1 / 2.2;
- BABYLON.ToLinearSpace = 2.2;
- BABYLON.Epsilon = 0.001;
- var Color3 = /** @class */ (function () {
- /**
- * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
- */
- 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;
- }
- /**
- * Returns a string with the Color3 current values.
- */
- Color3.prototype.toString = function () {
- return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
- };
- /**
- * Returns the string "Color3".
- */
- Color3.prototype.getClassName = function () {
- return "Color3";
- };
- /**
- * Returns the Color3 hash code.
- */
- Color3.prototype.getHashCode = function () {
- var hash = this.r || 0;
- hash = (hash * 397) ^ (this.g || 0);
- hash = (hash * 397) ^ (this.b || 0);
- return hash;
- };
- // Operators
- /**
- * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
- * Returns the Color3.
- */
- 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;
- };
- /**
- * Returns a new Color4 object from the current Color3 and the passed alpha.
- */
- Color3.prototype.toColor4 = function (alpha) {
- if (alpha === void 0) { alpha = 1; }
- return new Color4(this.r, this.g, this.b, alpha);
- };
- /**
- * Returns a new array populated with 3 numeric elements : red, green and blue values.
- */
- Color3.prototype.asArray = function () {
- var result = new Array();
- this.toArray(result, 0);
- return result;
- };
- /**
- * Returns the luminance value (float).
- */
- Color3.prototype.toLuminance = function () {
- return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
- };
- /**
- * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
- * Returns this new object.
- */
- Color3.prototype.multiply = function (otherColor) {
- return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
- };
- /**
- * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
- * Returns the current Color3.
- */
- 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;
- };
- /**
- * Boolean : True if the rgb values are equal to the passed ones.
- */
- Color3.prototype.equals = function (otherColor) {
- return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
- };
- /**
- * Boolean : True if the rgb values are equal to the passed ones.
- */
- Color3.prototype.equalsFloats = function (r, g, b) {
- return this.r === r && this.g === g && this.b === b;
- };
- /**
- * Multiplies in place each rgb value by scale.
- * Returns the updated Color3.
- */
- Color3.prototype.scale = function (scale) {
- return new Color3(this.r * scale, this.g * scale, this.b * scale);
- };
- /**
- * Multiplies the rgb values by scale and stores the result into "result".
- * Returns the unmodified current Color3.
- */
- Color3.prototype.scaleToRef = function (scale, result) {
- result.r = this.r * scale;
- result.g = this.g * scale;
- result.b = this.b * scale;
- return this;
- };
- /**
- * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
- */
- Color3.prototype.add = function (otherColor) {
- return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
- };
- /**
- * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
- * Returns the unmodified current Color3.
- */
- 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;
- };
- /**
- * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
- */
- Color3.prototype.subtract = function (otherColor) {
- return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
- };
- /**
- * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
- * Returns the unmodified current Color3.
- */
- 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;
- };
- /**
- * Returns a new Color3 copied the current one.
- */
- Color3.prototype.clone = function () {
- return new Color3(this.r, this.g, this.b);
- };
- /**
- * Copies the rgb values from the source in the current Color3.
- * Returns the updated Color3.
- */
- Color3.prototype.copyFrom = function (source) {
- this.r = source.r;
- this.g = source.g;
- this.b = source.b;
- return this;
- };
- /**
- * Updates the Color3 rgb values from the passed floats.
- * Returns the Color3.
- */
- Color3.prototype.copyFromFloats = function (r, g, b) {
- this.r = r;
- this.g = g;
- this.b = b;
- return this;
- };
- /**
- * Updates the Color3 rgb values from the passed floats.
- * Returns the Color3.
- */
- Color3.prototype.set = function (r, g, b) {
- return this.copyFromFloats(r, g, b);
- };
- /**
- * Returns the Color3 hexadecimal code as a string.
- */
- Color3.prototype.toHexString = function () {
- var intR = (this.r * 255) | 0;
- var intG = (this.g * 255) | 0;
- var intB = (this.b * 255) | 0;
- return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
- };
- /**
- * Returns a new Color3 converted to linear space.
- */
- Color3.prototype.toLinearSpace = function () {
- var convertedColor = new Color3();
- this.toLinearSpaceToRef(convertedColor);
- return convertedColor;
- };
- /**
- * Converts the Color3 values to linear space and stores the result in "convertedColor".
- * Returns the unmodified Color3.
- */
- 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;
- };
- /**
- * Returns a new Color3 converted to gamma space.
- */
- Color3.prototype.toGammaSpace = function () {
- var convertedColor = new Color3();
- this.toGammaSpaceToRef(convertedColor);
- return convertedColor;
- };
- /**
- * Converts the Color3 values to gamma space and stores the result in "convertedColor".
- * Returns the unmodified Color3.
- */
- 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
- /**
- * Creates a new Color3 from the string containing valid hexadecimal values.
- */
- 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);
- };
- /**
- * Creates a new Vector3 from the startind index of the passed array.
- */
- Color3.FromArray = function (array, offset) {
- if (offset === void 0) { offset = 0; }
- return new Color3(array[offset], array[offset + 1], array[offset + 2]);
- };
- /**
- * Creates a new Color3 from integer values ( < 256).
- */
- Color3.FromInts = function (r, g, b) {
- return new Color3(r / 255.0, g / 255.0, b / 255.0);
- };
- /**
- * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
- */
- 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); };
- Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
- Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
- return Color3;
- }());
- BABYLON.Color3 = Color3;
- var Color4 = /** @class */ (function () {
- /**
- * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
- */
- function Color4(r, g, b, a) {
- if (r === void 0) { r = 0; }
- if (g === void 0) { g = 0; }
- if (b === void 0) { b = 0; }
- if (a === void 0) { a = 1; }
- this.r = r;
- this.g = g;
- this.b = b;
- this.a = a;
- }
- // Operators
- /**
- * Adds in place the passed Color4 values to the current Color4.
- * Returns the updated Color4.
- */
- Color4.prototype.addInPlace = function (right) {
- this.r += right.r;
- this.g += right.g;
- this.b += right.b;
- this.a += right.a;
- return this;
- };
- /**
- * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
- */
- Color4.prototype.asArray = function () {
- var result = new Array();
- this.toArray(result, 0);
- return result;
- };
- /**
- * Stores from the starting index in the passed array the Color4 successive values.
- * Returns the Color4.
- */
- 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;
- };
- /**
- * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
- */
- Color4.prototype.add = function (right) {
- return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
- };
- /**
- * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
- */
- Color4.prototype.subtract = function (right) {
- return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
- };
- /**
- * Subtracts the passed ones from the current Color4 values and stores the results in "result".
- * Returns the Color4.
- */
- 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;
- };
- /**
- * Creates a new Color4 with the current Color4 values multiplied by scale.
- */
- Color4.prototype.scale = function (scale) {
- return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
- };
- /**
- * Multiplies the current Color4 values by scale and stores the result in "result".
- * Returns the Color4.
- */
- 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;
- };
- /**
- * Multipy an RGBA Color4 value by another and return a new Color4 object
- * @param color The Color4 (RGBA) value to multiply by
- * @returns A new Color4.
- */
- Color4.prototype.multiply = function (color) {
- return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
- };
- /**
- * Multipy an RGBA Color4 value by another and push the result in a reference value
- * @param color The Color4 (RGBA) value to multiply by
- * @param result The Color4 (RGBA) to fill the result in
- * @returns the result Color4.
- */
- Color4.prototype.multiplyToRef = function (color, result) {
- result.r = this.r * color.r;
- result.g = this.g * color.g;
- result.b = this.b * color.b;
- result.a = this.a * color.a;
- return result;
- };
- /**
- * Returns a string with the Color4 values.
- */
- Color4.prototype.toString = function () {
- return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
- };
- /**
- * Returns the string "Color4"
- */
- Color4.prototype.getClassName = function () {
- return "Color4";
- };
- /**
- * Return the Color4 hash code as a number.
- */
- Color4.prototype.getHashCode = function () {
- var hash = this.r || 0;
- hash = (hash * 397) ^ (this.g || 0);
- hash = (hash * 397) ^ (this.b || 0);
- hash = (hash * 397) ^ (this.a || 0);
- return hash;
- };
- /**
- * Creates a new Color4 copied from the current one.
- */
- Color4.prototype.clone = function () {
- return new Color4(this.r, this.g, this.b, this.a);
- };
- /**
- * Copies the passed Color4 values into the current one.
- * Returns the updated Color4.
- */
- Color4.prototype.copyFrom = function (source) {
- this.r = source.r;
- this.g = source.g;
- this.b = source.b;
- this.a = source.a;
- return this;
- };
- /**
- * Copies the passed float values into the current one.
- * Returns the updated Color4.
- */
- Color4.prototype.copyFromFloats = function (r, g, b, a) {
- this.r = r;
- this.g = g;
- this.b = b;
- this.a = a;
- return this;
- };
- /**
- * Copies the passed float values into the current one.
- * Returns the updated Color4.
- */
- Color4.prototype.set = function (r, g, b, a) {
- return this.copyFromFloats(r, g, b, a);
- };
- /**
- * Returns a string containing the hexadecimal Color4 code.
- */
- 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 "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
- };
- /**
- * Returns a new Color4 converted to linear space.
- */
- Color4.prototype.toLinearSpace = function () {
- var convertedColor = new Color4();
- this.toLinearSpaceToRef(convertedColor);
- return convertedColor;
- };
- /**
- * Converts the Color4 values to linear space and stores the result in "convertedColor".
- * Returns the unmodified Color4.
- */
- Color4.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);
- convertedColor.a = this.a;
- return this;
- };
- /**
- * Returns a new Color4 converted to gamma space.
- */
- Color4.prototype.toGammaSpace = function () {
- var convertedColor = new Color4();
- this.toGammaSpaceToRef(convertedColor);
- return convertedColor;
- };
- /**
- * Converts the Color4 values to gamma space and stores the result in "convertedColor".
- * Returns the unmodified Color4.
- */
- Color4.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);
- convertedColor.a = this.a;
- return this;
- };
- // Statics
- /**
- * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
- */
- 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, 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);
- };
- /**
- * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
- */
- Color4.Lerp = function (left, right, amount) {
- var result = new Color4(0.0, 0.0, 0.0, 0.0);
- Color4.LerpToRef(left, right, amount, result);
- return result;
- };
- /**
- * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
- */
- 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;
- };
- /**
- * Creates a new Color4 from the starting index element of the passed array.
- */
- 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]);
- };
- /**
- * Creates a new Color4 from the passed integers ( < 256 ).
- */
- 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 = /** @class */ (function () {
- /**
- * Creates a new Vector2 from the passed x and y coordinates.
- */
- function Vector2(x, y) {
- this.x = x;
- this.y = y;
- }
- /**
- * Returns a string with the Vector2 coordinates.
- */
- Vector2.prototype.toString = function () {
- return "{X: " + this.x + " Y:" + this.y + "}";
- };
- /**
- * Returns the string "Vector2"
- */
- Vector2.prototype.getClassName = function () {
- return "Vector2";
- };
- /**
- * Returns the Vector2 hash code as a number.
- */
- Vector2.prototype.getHashCode = function () {
- var hash = this.x || 0;
- hash = (hash * 397) ^ (this.y || 0);
- return hash;
- };
- // Operators
- /**
- * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
- * Returns the Vector2.
- */
- Vector2.prototype.toArray = function (array, index) {
- if (index === void 0) { index = 0; }
- array[index] = this.x;
- array[index + 1] = this.y;
- return this;
- };
- /**
- * Returns a new array with 2 elements : the Vector2 coordinates.
- */
- Vector2.prototype.asArray = function () {
- var result = new Array();
- this.toArray(result, 0);
- return result;
- };
- /**
- * Sets the Vector2 coordinates with the passed Vector2 coordinates.
- * Returns the updated Vector2.
- */
- Vector2.prototype.copyFrom = function (source) {
- this.x = source.x;
- this.y = source.y;
- return this;
- };
- /**
- * Sets the Vector2 coordinates with the passed floats.
- * Returns the updated Vector2.
- */
- Vector2.prototype.copyFromFloats = function (x, y) {
- this.x = x;
- this.y = y;
- return this;
- };
- /**
- * Sets the Vector2 coordinates with the passed floats.
- * Returns the updated Vector2.
- */
- Vector2.prototype.set = function (x, y) {
- return this.copyFromFloats(x, y);
- };
- /**
- * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
- */
- Vector2.prototype.add = function (otherVector) {
- return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
- };
- /**
- * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
- * Returns the Vector2.
- */
- Vector2.prototype.addToRef = function (otherVector, result) {
- result.x = this.x + otherVector.x;
- result.y = this.y + otherVector.y;
- return this;
- };
- /**
- * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
- * Returns the updated Vector2.
- */
- Vector2.prototype.addInPlace = function (otherVector) {
- this.x += otherVector.x;
- this.y += otherVector.y;
- return this;
- };
- /**
- * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
- */
- Vector2.prototype.addVector3 = function (otherVector) {
- return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
- };
- /**
- * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
- */
- Vector2.prototype.subtract = function (otherVector) {
- return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
- };
- /**
- * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
- * Returns the Vector2.
- */
- Vector2.prototype.subtractToRef = function (otherVector, result) {
- result.x = this.x - otherVector.x;
- result.y = this.y - otherVector.y;
- return this;
- };
- /**
- * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
- * Returns the updated Vector2.
- */
- Vector2.prototype.subtractInPlace = function (otherVector) {
- this.x -= otherVector.x;
- this.y -= otherVector.y;
- return this;
- };
- /**
- * Multiplies in place the current Vector2 coordinates by the passed ones.
- * Returns the updated Vector2.
- */
- Vector2.prototype.multiplyInPlace = function (otherVector) {
- this.x *= otherVector.x;
- this.y *= otherVector.y;
- return this;
- };
- /**
- * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
- */
- Vector2.prototype.multiply = function (otherVector) {
- return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
- };
- /**
- * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
- * Returns the Vector2.
- */
- Vector2.prototype.multiplyToRef = function (otherVector, result) {
- result.x = this.x * otherVector.x;
- result.y = this.y * otherVector.y;
- return this;
- };
- /**
- * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
- */
- Vector2.prototype.multiplyByFloats = function (x, y) {
- return new Vector2(this.x * x, this.y * y);
- };
- /**
- * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
- */
- Vector2.prototype.divide = function (otherVector) {
- return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
- };
- /**
- * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
- * Returns the Vector2.
- */
- Vector2.prototype.divideToRef = function (otherVector, result) {
- result.x = this.x / otherVector.x;
- result.y = this.y / otherVector.y;
- return this;
- };
- /**
- * Divides the current Vector3 coordinates by the passed ones.
- * Returns the updated Vector3.
- */
- Vector2.prototype.divideInPlace = function (otherVector) {
- return this.divideToRef(otherVector, this);
- };
- /**
- * Returns a new Vector2 with current Vector2 negated coordinates.
- */
- Vector2.prototype.negate = function () {
- return new Vector2(-this.x, -this.y);
- };
- /**
- * Multiply the Vector2 coordinates by scale.
- * Returns the updated Vector2.
- */
- Vector2.prototype.scaleInPlace = function (scale) {
- this.x *= scale;
- this.y *= scale;
- return this;
- };
- /**
- * Returns a new Vector2 scaled by "scale" from the current Vector2.
- */
- Vector2.prototype.scale = function (scale) {
- return new Vector2(this.x * scale, this.y * scale);
- };
- /**
- * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
- */
- Vector2.prototype.equals = function (otherVector) {
- return otherVector && this.x === otherVector.x && this.y === otherVector.y;
- };
- /**
- * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
- */
- Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
- if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
- return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
- };
- // Properties
- /**
- * Returns the vector length (float).
- */
- Vector2.prototype.length = function () {
- return Math.sqrt(this.x * this.x + this.y * this.y);
- };
- /**
- * Returns the vector squared length (float);
- */
- Vector2.prototype.lengthSquared = function () {
- return (this.x * this.x + this.y * this.y);
- };
- // Methods
- /**
- * Normalize the vector.
- * Returns the updated Vector2.
- */
- 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;
- };
- /**
- * Returns a new Vector2 copied from the Vector2.
- */
- Vector2.prototype.clone = function () {
- return new Vector2(this.x, this.y);
- };
- // Statics
- /**
- * Returns a new Vector2(0, 0)
- */
- Vector2.Zero = function () {
- return new Vector2(0, 0);
- };
- /**
- * Returns a new Vector2(1, 1)
- */
- Vector2.One = function () {
- return new Vector2(1, 1);
- };
- /**
- * Returns a new Vector2 set from the passed index element of the passed array.
- */
- Vector2.FromArray = function (array, offset) {
- if (offset === void 0) { offset = 0; }
- return new Vector2(array[offset], array[offset + 1]);
- };
- /**
- * Sets "result" from the passed index element of the passed array.
- */
- Vector2.FromArrayToRef = function (array, offset, result) {
- result.x = array[offset];
- result.y = array[offset + 1];
- };
- /**
- * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
- */
- 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);
- };
- /**
- * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
- * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
- * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
- */
- 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);
- };
- /**
- * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
- */
- 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);
- };
- /**
- * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
- */
- 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);
- };
- /**
- * Returns the dot product (float) of the vector "left" and the vector "right".
- */
- Vector2.Dot = function (left, right) {
- return left.x * right.x + left.y * right.y;
- };
- /**
- * Returns a new Vector2 equal to the normalized passed vector.
- */
- Vector2.Normalize = function (vector) {
- var newVector = vector.clone();
- newVector.normalize();
- return newVector;
- };
- /**
- * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
- */
- 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);
- };
- /**
- * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
- */
- 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);
- };
- /**
- * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
- */
- Vector2.Transform = function (vector, transformation) {
- var r = Vector2.Zero();
- Vector2.TransformToRef(vector, transformation, r);
- return r;
- };
- /**
- * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
- */
- Vector2.TransformToRef = function (vector, transformation, result) {
- var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
- var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
- result.x = x;
- result.y = y;
- };
- /**
- * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
- */
- Vector2.PointInTriangle = function (p, p0, p1, p2) {
- var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
- var sign = a < 0 ? -1 : 1;
- var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
- var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
- return s > 0 && t > 0 && (s + t) < 2 * a * sign;
- };
- /**
- * Returns the distance (float) between the vectors "value1" and "value2".
- */
- Vector2.Distance = function (value1, value2) {
- return Math.sqrt(Vector2.DistanceSquared(value1, value2));
- };
- /**
- * Returns the squared distance (float) between the vectors "value1" and "value2".
- */
- Vector2.DistanceSquared = function (value1, value2) {
- var x = value1.x - value2.x;
- var y = value1.y - value2.y;
- return (x * x) + (y * y);
- };
- /**
- * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
- */
- Vector2.Center = function (value1, value2) {
- var center = value1.add(value2);
- center.scaleInPlace(0.5);
- return center;
- };
- /**
- * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
- */
- Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
- var l2 = Vector2.DistanceSquared(segA, segB);
- if (l2 === 0.0) {
- return Vector2.Distance(p, segA);
- }
- var v = segB.subtract(segA);
- var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
- var proj = segA.add(v.multiplyByFloats(t, t));
- return Vector2.Distance(p, proj);
- };
- return Vector2;
- }());
- BABYLON.Vector2 = Vector2;
- var Vector3 = /** @class */ (function () {
- /**
- * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
- * A Vector3 is the main object used in 3D geometry.
- * It can represent etiher the coordinates of a point the space, either a direction.
- */
- function Vector3(x, y, z) {
- this.x = x;
- this.y = y;
- this.z = z;
- }
- /**
- * Returns a string with the Vector3 coordinates.
- */
- Vector3.prototype.toString = function () {
- return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
- };
- /**
- * Returns the string "Vector3"
- */
- Vector3.prototype.getClassName = function () {
- return "Vector3";
- };
- /**
- * Returns the Vector hash code.
- */
- Vector3.prototype.getHashCode = function () {
- var hash = this.x || 0;
- hash = (hash * 397) ^ (this.y || 0);
- hash = (hash * 397) ^ (this.z || 0);
- return hash;
- };
- // Operators
- /**
- * Returns a new array with three elements : the coordinates the Vector3.
- */
- Vector3.prototype.asArray = function () {
- var result = [];
- this.toArray(result, 0);
- return result;
- };
- /**
- * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
- * Returns the Vector3.
- */
- 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;
- };
- /**
- * Returns a new Quaternion object, computed from the Vector3 coordinates.
- */
- Vector3.prototype.toQuaternion = function () {
- var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
- 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;
- };
- /**
- * Adds the passed vector to the current Vector3.
- * Returns the updated Vector3.
- */
- Vector3.prototype.addInPlace = function (otherVector) {
- this.x += otherVector.x;
- this.y += otherVector.y;
- this.z += otherVector.z;
- return this;
- };
- /**
- * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
- */
- Vector3.prototype.add = function (otherVector) {
- return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
- };
- /**
- * Adds the current Vector3 to the passed one and stores the result in the vector "result".
- * Returns the current Vector3.
- */
- 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;
- };
- /**
- * Subtract the passed vector from the current Vector3.
- * Returns the updated Vector3.
- */
- Vector3.prototype.subtractInPlace = function (otherVector) {
- this.x -= otherVector.x;
- this.y -= otherVector.y;
- this.z -= otherVector.z;
- return this;
- };
- /**
- * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
- */
- Vector3.prototype.subtract = function (otherVector) {
- return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
- };
- /**
- * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
- * Returns the current Vector3.
- */
- 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;
- };
- /**
- * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
- */
- Vector3.prototype.subtractFromFloats = function (x, y, z) {
- return new Vector3(this.x - x, this.y - y, this.z - z);
- };
- /**
- * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
- * Returns the current Vector3.
- */
- 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;
- };
- /**
- * Returns a new Vector3 set with the current Vector3 negated coordinates.
- */
- Vector3.prototype.negate = function () {
- return new Vector3(-this.x, -this.y, -this.z);
- };
- /**
- * Multiplies the Vector3 coordinates by the float "scale".
- * Returns the updated Vector3.
- */
- Vector3.prototype.scaleInPlace = function (scale) {
- this.x *= scale;
- this.y *= scale;
- this.z *= scale;
- return this;
- };
- /**
- * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
- */
- Vector3.prototype.scale = function (scale) {
- return new Vector3(this.x * scale, this.y * scale, this.z * scale);
- };
- /**
- * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
- * Returns the current Vector3.
- */
- Vector3.prototype.scaleToRef = function (scale, result) {
- result.x = this.x * scale;
- result.y = this.y * scale;
- result.z = this.z * scale;
- return this;
- };
- /**
- * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
- */
- Vector3.prototype.equals = function (otherVector) {
- return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
- };
- /**
- * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
- */
- Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
- if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
- return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
- };
- /**
- * Boolean : True if the current Vector3 coordinate equal the passed floats.
- */
- Vector3.prototype.equalsToFloats = function (x, y, z) {
- return this.x === x && this.y === y && this.z === z;
- };
- /**
- * Muliplies the current Vector3 coordinates by the passed ones.
- * Returns the updated Vector3.
- */
- Vector3.prototype.multiplyInPlace = function (otherVector) {
- this.x *= otherVector.x;
- this.y *= otherVector.y;
- this.z *= otherVector.z;
- return this;
- };
- /**
- * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
- */
- Vector3.prototype.multiply = function (otherVector) {
- return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
- };
- /**
- * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
- * Returns the current Vector3.
- */
- 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;
- };
- /**
- * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
- */
- Vector3.prototype.multiplyByFloats = function (x, y, z) {
- return new Vector3(this.x * x, this.y * y, this.z * z);
- };
- /**
- * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
- */
- Vector3.prototype.divide = function (otherVector) {
- return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
- };
- /**
- * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
- * Returns the current Vector3.
- */
- 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;
- };
- /**
- * Divides the current Vector3 coordinates by the passed ones.
- * Returns the updated Vector3.
- */
- Vector3.prototype.divideInPlace = function (otherVector) {
- return this.divideToRef(otherVector, this);
- };
- /**
- * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
- * Returns the updated Vector3.
- */
- 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;
- };
- /**
- * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
- * Returns the updated Vector3.
- */
- 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;
- };
- Object.defineProperty(Vector3.prototype, "isNonUniform", {
- /**
- * Return true is the vector is non uniform meaning x, y or z are not all the same.
- */
- get: function () {
- var absX = Math.abs(this.x);
- var absY = Math.abs(this.y);
- if (absX !== absY) {
- return true;
- }
- var absZ = Math.abs(this.z);
- if (absX !== absZ) {
- return true;
- }
- if (absY !== absZ) {
- return true;
- }
- return false;
- },
- enumerable: true,
- configurable: true
- });
- // Properties
- /**
- * Returns the length of the Vector3 (float).
- */
- Vector3.prototype.length = function () {
- return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
- };
- /**
- * Returns the squared length of the Vector3 (float).
- */
- Vector3.prototype.lengthSquared = function () {
- return (this.x * this.x + this.y * this.y + this.z * this.z);
- };
- /**
- * Normalize the current Vector3.
- * Returns the updated Vector3.
- * /!\ In place operation.
- */
- 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;
- };
- /**
- * Normalize the current Vector3 to a new vector.
- * @returns the new Vector3.
- */
- Vector3.prototype.normalizeToNew = function () {
- var normalized = new Vector3(0, 0, 0);
- this.normalizeToRef(normalized);
- return normalized;
- };
- /**
- * Normalize the current Vector3 to the reference.
- * @param the reference to update.
- * @returns the updated Vector3.
- */
- Vector3.prototype.normalizeToRef = function (reference) {
- var len = this.length();
- if (len === 0 || len === 1.0) {
- reference.set(this.x, this.y, this.z);
- return reference;
- }
- var scale = 1.0 / len;
- this.scaleToRef(scale, reference);
- return reference;
- };
- /**
- * Returns a new Vector3 copied from the current Vector3.
- */
- Vector3.prototype.clone = function () {
- return new Vector3(this.x, this.y, this.z);
- };
- /**
- * Copies the passed vector coordinates to the current Vector3 ones.
- * Returns the updated Vector3.
- */
- Vector3.prototype.copyFrom = function (source) {
- this.x = source.x;
- this.y = source.y;
- this.z = source.z;
- return this;
- };
- /**
- * Copies the passed floats to the current Vector3 coordinates.
- * Returns the updated Vector3.
- */
- Vector3.prototype.copyFromFloats = function (x, y, z) {
- this.x = x;
- this.y = y;
- this.z = z;
- return this;
- };
- /**
- * Copies the passed floats to the current Vector3 coordinates.
- * Returns the updated Vector3.
- */
- Vector3.prototype.set = function (x, y, z) {
- return this.copyFromFloats(x, y, z);
- };
- // 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;
- };
- /**
- * Returns a new Vector3 set from the index "offset" of the passed array.
- */
- Vector3.FromArray = function (array, offset) {
- if (!offset) {
- offset = 0;
- }
- return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
- };
- /**
- * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
- * This function is deprecated. Use FromArray instead.
- */
- Vector3.FromFloatArray = function (array, offset) {
- return Vector3.FromArray(array, offset);
- };
- /**
- * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
- */
- Vector3.FromArrayToRef = function (array, offset, result) {
- result.x = array[offset];
- result.y = array[offset + 1];
- result.z = array[offset + 2];
- };
- /**
- * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
- * This function is deprecated. Use FromArrayToRef instead.
- */
- Vector3.FromFloatArrayToRef = function (array, offset, result) {
- return Vector3.FromArrayToRef(array, offset, result);
- };
- /**
- * Sets the passed vector "result" with the passed floats.
- */
- Vector3.FromFloatsToRef = function (x, y, z, result) {
- result.x = x;
- result.y = y;
- result.z = z;
- };
- /**
- * Returns a new Vector3 set to (0.0, 0.0, 0.0).
- */
- Vector3.Zero = function () {
- return new Vector3(0.0, 0.0, 0.0);
- };
- /**
- * Returns a new Vector3 set to (1.0, 1.0, 1.0).
- */
- Vector3.One = function () {
- return new Vector3(1.0, 1.0, 1.0);
- };
- /**
- * Returns a new Vector3 set to (0.0, 1.0, 0.0)
- */
- Vector3.Up = function () {
- return new Vector3(0.0, 1.0, 0.0);
- };
- /**
- * Returns a new Vector3 set to (0.0, 0.0, 1.0)
- */
- Vector3.Forward = function () {
- return new Vector3(0.0, 0.0, 1.0);
- };
- /**
- * Returns a new Vector3 set to (1.0, 0.0, 0.0)
- */
- Vector3.Right = function () {
- return new Vector3(1.0, 0.0, 0.0);
- };
- /**
- * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
- */
- Vector3.Left = function () {
- return new Vector3(-1.0, 0.0, 0.0);
- };
- /**
- * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
- * This method computes tranformed coordinates only, not transformed direction vectors.
- */
- Vector3.TransformCoordinates = function (vector, transformation) {
- var result = Vector3.Zero();
- Vector3.TransformCoordinatesToRef(vector, transformation, result);
- return result;
- };
- /**
- * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
- * This method computes tranformed coordinates only, not transformed direction vectors.
- */
- 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;
- };
- /**
- * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
- * This method computes tranformed coordinates only, not transformed direction vectors.
- */
- 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;
- };
- /**
- * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
- * This methods computes transformed normalized direction vectors only.
- */
- Vector3.TransformNormal = function (vector, transformation) {
- var result = Vector3.Zero();
- Vector3.TransformNormalToRef(vector, transformation, result);
- return result;
- };
- /**
- * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
- * This methods computes transformed normalized direction vectors only.
- */
- Vector3.TransformNormalToRef = function (vector, transformation, result) {
- var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
- var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
- var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
- result.x = x;
- result.y = y;
- result.z = z;
- };
- /**
- * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
- * This methods computes transformed normalized direction vectors only.
- */
- 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]);
- };
- /**
- * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
- */
- 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);
- };
- /**
- * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max".
- * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
- * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
- */
- 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);
- };
- /**
- * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
- */
- 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);
- };
- /**
- * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
- */
- Vector3.Lerp = function (start, end, amount) {
- var result = new Vector3(0, 0, 0);
- Vector3.LerpToRef(start, end, amount, result);
- return result;
- };
- /**
- * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
- */
- Vector3.LerpToRef = function (start, end, amount, result) {
- result.x = start.x + ((end.x - start.x) * amount);
- result.y = start.y + ((end.y - start.y) * amount);
- result.z = start.z + ((end.z - start.z) * amount);
- };
- /**
- * Returns the dot product (float) between the vectors "left" and "right".
- */
- Vector3.Dot = function (left, right) {
- return (left.x * right.x + left.y * right.y + left.z * right.z);
- };
- /**
- * Returns a new Vector3 as the cross product of the vectors "left" and "right".
- * The cross product is then orthogonal to both "left" and "right".
- */
- Vector3.Cross = function (left, right) {
- var result = Vector3.Zero();
- Vector3.CrossToRef(left, right, result);
- return result;
- };
- /**
- * Sets the passed vector "result" with the cross product of "left" and "right".
- * The cross product is then orthogonal to both "left" and "right".
- */
- Vector3.CrossToRef = function (left, right, result) {
- MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
- MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
- MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
- result.copyFrom(MathTmp.Vector3[0]);
- };
- /**
- * Returns a new Vector3 as the normalization of the passed vector.
- */
- Vector3.Normalize = function (vector) {
- var result = Vector3.Zero();
- Vector3.NormalizeToRef(vector, result);
- return result;
- };
- /**
- * Sets the passed vector "result" with the normalization of the passed first vector.
- */
- 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 = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
- Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
- var matrix = MathTmp.Matrix[0];
- world.multiplyToRef(transform, matrix);
- matrix.multiplyToRef(viewportMatrix, matrix);
- return Vector3.TransformCoordinates(vector, matrix);
- };
- Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
- var matrix = MathTmp.Matrix[0];
- world.multiplyToRef(transform, matrix);
- 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 (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
- vector = vector.scale(1.0 / num);
- }
- return vector;
- };
- Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
- var result = Vector3.Zero();
- Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
- return result;
- };
- Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
- Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
- };
- Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
- var matrix = MathTmp.Matrix[0];
- world.multiplyToRef(view, matrix);
- matrix.multiplyToRef(projection, matrix);
- matrix.invert();
- var screenSource = MathTmp.Vector3[0];
- screenSource.x = sourceX / viewportWidth * 2 - 1;
- screenSource.y = -(sourceY / viewportHeight * 2 - 1);
- screenSource.z = 2 * sourceZ - 1.0;
- Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
- var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
- if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
- result.scaleInPlace(1.0 / num);
- }
- };
- 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;
- };
- /**
- * Returns the distance (float) between the vectors "value1" and "value2".
- */
- Vector3.Distance = function (value1, value2) {
- return Math.sqrt(Vector3.DistanceSquared(value1, value2));
- };
- /**
- * Returns the squared distance (float) between the vectors "value1" and "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);
- };
- /**
- * Returns a new Vector3 located at the center between "value1" and "value2".
- */
- 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.
- * Note : axis1, axis2 and axis3 are normalized during this operation.
- * Returns a new Vector3.
- */
- 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 instead of returning a new Vector3.
- */
- Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
- var quat = MathTmp.Quaternion[0];
- Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
- quat.toEulerAnglesToRef(ref);
- };
- return Vector3;
- }());
- BABYLON.Vector3 = Vector3;
- //Vector4 class created for EulerAngle class conversion to Quaternion
- var Vector4 = /** @class */ (function () {
- /**
- * Creates a Vector4 object from the passed floats.
- */
- function Vector4(x, y, z, w) {
- this.x = x;
- this.y = y;
- this.z = z;
- this.w = w;
- }
- /**
- * Returns the string with the Vector4 coordinates.
- */
- Vector4.prototype.toString = function () {
- return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
- };
- /**
- * Returns the string "Vector4".
- */
- Vector4.prototype.getClassName = function () {
- return "Vector4";
- };
- /**
- * Returns the Vector4 hash code.
- */
- Vector4.prototype.getHashCode = function () {
- var hash = this.x || 0;
- hash = (hash * 397) ^ (this.y || 0);
- hash = (hash * 397) ^ (this.z || 0);
- hash = (hash * 397) ^ (this.w || 0);
- return hash;
- };
- // Operators
- /**
- * Returns a new array populated with 4 elements : the Vector4 coordinates.
- */
- Vector4.prototype.asArray = function () {
- var result = new Array();
- this.toArray(result, 0);
- return result;
- };
- /**
- * Populates the passed array from the passed index with the Vector4 coordinates.
- * Returns the Vector4.
- */
- 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;
- };
- /**
- * Adds the passed vector to the current Vector4.
- * Returns the updated Vector4.
- */
- Vector4.prototype.addInPlace = function (otherVector) {
- this.x += otherVector.x;
- this.y += otherVector.y;
- this.z += otherVector.z;
- this.w += otherVector.w;
- return this;
- };
- /**
- * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
- */
- Vector4.prototype.add = function (otherVector) {
- return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
- };
- /**
- * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
- * Returns the current Vector4.
- */
- 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;
- };
- /**
- * Subtract in place the passed vector from the current Vector4.
- * Returns the updated Vector4.
- */
- Vector4.prototype.subtractInPlace = function (otherVector) {
- this.x -= otherVector.x;
- this.y -= otherVector.y;
- this.z -= otherVector.z;
- this.w -= otherVector.w;
- return this;
- };
- /**
- * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
- */
- Vector4.prototype.subtract = function (otherVector) {
- return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
- };
- /**
- * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
- * Returns the current Vector4.
- */
- 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;
- };
- /**
- * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
- */
- Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
- return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
- };
- /**
- * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
- * Returns the current Vector4.
- */
- 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;
- };
- /**
- * Returns a new Vector4 set with the current Vector4 negated coordinates.
- */
- Vector4.prototype.negate = function () {
- return new Vector4(-this.x, -this.y, -this.z, -this.w);
- };
- /**
- * Multiplies the current Vector4 coordinates by scale (float).
- * Returns the updated Vector4.
- */
- Vector4.prototype.scaleInPlace = function (scale) {
- this.x *= scale;
- this.y *= scale;
- this.z *= scale;
- this.w *= scale;
- return this;
- };
- /**
- * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
- */
- Vector4.prototype.scale = function (scale) {
- return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
- };
- /**
- * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
- * Returns the current Vector4.
- */
- 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;
- return this;
- };
- /**
- * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
- */
- Vector4.prototype.equals = function (otherVector) {
- return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
- };
- /**
- * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
- */
- Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
- if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
- return otherVector
- && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
- && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
- && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
- && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
- };
- /**
- * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
- */
- Vector4.prototype.equalsToFloats = function (x, y, z, w) {
- return this.x === x && this.y === y && this.z === z && this.w === w;
- };
- /**
- * Multiplies in place the current Vector4 by the passed one.
- * Returns the updated Vector4.
- */
- Vector4.prototype.multiplyInPlace = function (otherVector) {
- this.x *= otherVector.x;
- this.y *= otherVector.y;
- this.z *= otherVector.z;
- this.w *= otherVector.w;
- return this;
- };
- /**
- * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
- */
- Vector4.prototype.multiply = function (otherVector) {
- return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
- };
- /**
- * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
- * Returns the current Vector4.
- */
- 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;
- };
- /**
- * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
- */
- Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
- return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
- };
- /**
- * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
- */
- Vector4.prototype.divide = function (otherVector) {
- return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
- };
- /**
- * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
- * Returns the current Vector4.
- */
- 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;
- };
- /**
- * Divides the current Vector3 coordinates by the passed ones.
- * Returns the updated Vector3.
- */
- Vector4.prototype.divideInPlace = function (otherVector) {
- return this.divideToRef(otherVector, this);
- };
- /**
- * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
- */
- 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;
- };
- /**
- * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
- */
- 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
- /**
- * Returns the Vector4 length (float).
- */
- Vector4.prototype.length = function () {
- return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
- };
- /**
- * Returns the Vector4 squared length (float).
- */
- Vector4.prototype.lengthSquared = function () {
- return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
- };
- // Methods
- /**
- * Normalizes in place the Vector4.
- * Returns the updated Vector4.
- */
- 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;
- };
- /**
- * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
- */
- Vector4.prototype.toVector3 = function () {
- return new Vector3(this.x, this.y, this.z);
- };
- /**
- * Returns a new Vector4 copied from the current one.
- */
- Vector4.prototype.clone = function () {
- return new Vector4(this.x, this.y, this.z, this.w);
- };
- /**
- * Updates the current Vector4 with the passed one coordinates.
- * Returns the updated Vector4.
- */
- Vector4.prototype.copyFrom = function (source) {
- this.x = source.x;
- this.y = source.y;
- this.z = source.z;
- this.w = source.w;
- return this;
- };
- /**
- * Updates the current Vector4 coordinates with the passed floats.
- * Returns the updated Vector4.
- */
- Vector4.prototype.copyFromFloats = function (x, y, z, w) {
- this.x = x;
- this.y = y;
- this.z = z;
- this.w = w;
- return this;
- };
- /**
- * Updates the current Vector4 coordinates with the passed floats.
- * Returns the updated Vector4.
- */
- Vector4.prototype.set = function (x, y, z, w) {
- return this.copyFromFloats(x, y, z, w);
- };
- // Statics
- /**
- * Returns a new Vector4 set from the starting index of the passed array.
- */
- Vector4.FromArray = function (array, offset) {
- if (!offset) {
- offset = 0;
- }
- return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
- };
- /**
- * Updates the passed vector "result" from the starting index of the passed array.
- */
- 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];
- };
- /**
- * Updates the passed vector "result" from the starting index of the passed Float32Array.
- */
- Vector4.FromFloatArrayToRef = function (array, offset, result) {
- Vector4.FromArrayToRef(array, offset, result);
- };
- /**
- * Updates the passed vector "result" coordinates from the passed floats.
- */
- Vector4.FromFloatsToRef = function (x, y, z, w, result) {
- result.x = x;
- result.y = y;
- result.z = z;
- result.w = w;
- };
- /**
- * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
- */
- Vector4.Zero = function () {
- return new Vector4(0.0, 0.0, 0.0, 0.0);
- };
- /**
- * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
- */
- Vector4.One = function () {
- return new Vector4(1.0, 1.0, 1.0, 1.0);
- };
- /**
- * Returns a new normalized Vector4 from the passed one.
- */
- Vector4.Normalize = function (vector) {
- var result = Vector4.Zero();
- Vector4.NormalizeToRef(vector, result);
- return result;
- };
- /**
- * Updates the passed vector "result" from the normalization of the passed one.
- */
- 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;
- };
- /**
- * Returns the distance (float) between the vectors "value1" and "value2".
- */
- Vector4.Distance = function (value1, value2) {
- return Math.sqrt(Vector4.DistanceSquared(value1, value2));
- };
- /**
- * Returns the squared distance (float) between the vectors "value1" and "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);
- };
- /**
- * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
- */
- Vector4.Center = function (value1, value2) {
- var center = value1.add(value2);
- center.scaleInPlace(0.5);
- return center;
- };
- /**
- * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
- * This methods computes transformed normalized direction vectors only.
- */
- Vector4.TransformNormal = function (vector, transformation) {
- var result = Vector4.Zero();
- Vector4.TransformNormalToRef(vector, transformation, result);
- return result;
- };
- /**
- * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
- * This methods computes transformed normalized direction vectors only.
- */
- Vector4.TransformNormalToRef = function (vector, transformation, result) {
- var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
- var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
- var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
- result.x = x;
- result.y = y;
- result.z = z;
- result.w = vector.w;
- };
- /**
- * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
- * This methods computes transformed normalized direction vectors only.
- */
- Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, 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]);
- result.w = w;
- };
- return Vector4;
- }());
- BABYLON.Vector4 = Vector4;
- var Size = /** @class */ (function () {
- /**
- * Creates a Size object from the passed width and height (floats).
- */
- function Size(width, height) {
- this.width = width;
- this.height = height;
- }
- // Returns a string with the Size width and height.
- Size.prototype.toString = function () {
- return "{W: " + this.width + ", H: " + this.height + "}";
- };
- /**
- * Returns the string "Size"
- */
- Size.prototype.getClassName = function () {
- return "Size";
- };
- /**
- * Returns the Size hash code.
- */
- Size.prototype.getHashCode = function () {
- var hash = this.width || 0;
- hash = (hash * 397) ^ (this.height || 0);
- return hash;
- };
- /**
- * Updates the current size from the passed one.
- * Returns the updated Size.
- */
- Size.prototype.copyFrom = function (src) {
- this.width = src.width;
- this.height = src.height;
- };
- /**
- * Updates in place the current Size from the passed floats.
- * Returns the updated Size.
- */
- Size.prototype.copyFromFloats = function (width, height) {
- this.width = width;
- this.height = height;
- return this;
- };
- /**
- * Updates in place the current Size from the passed floats.
- * Returns the updated Size.
- */
- Size.prototype.set = function (width, height) {
- return this.copyFromFloats(width, height);
- };
- /**
- * Returns a new Size set with the multiplication result of the current Size and the passed floats.
- */
- Size.prototype.multiplyByFloats = function (w, h) {
- return new Size(this.width * w, this.height * h);
- };
- /**
- * Returns a new Size copied from the passed one.
- */
- Size.prototype.clone = function () {
- return new Size(this.width, this.height);
- };
- /**
- * Boolean : True if the current Size and the passed one width and height are strictly equal.
- */
- Size.prototype.equals = function (other) {
- if (!other) {
- return false;
- }
- return (this.width === other.width) && (this.height === other.height);
- };
- Object.defineProperty(Size.prototype, "surface", {
- /**
- * Returns the surface of the Size : width * height (float).
- */
- get: function () {
- return this.width * this.height;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Returns a new Size set to (0.0, 0.0)
- */
- Size.Zero = function () {
- return new Size(0.0, 0.0);
- };
- /**
- * Returns a new Size set as the addition result of the current Size and the passed one.
- */
- Size.prototype.add = function (otherSize) {
- var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
- return r;
- };
- /**
- * Returns a new Size set as the subtraction result of the passed one from the current Size.
- */
- Size.prototype.subtract = function (otherSize) {
- var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
- return r;
- };
- /**
- * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
- */
- Size.Lerp = function (start, end, amount) {
- var w = start.width + ((end.width - start.width) * amount);
- var h = start.height + ((end.height - start.height) * amount);
- return new Size(w, h);
- };
- return Size;
- }());
- BABYLON.Size = Size;
- var Quaternion = /** @class */ (function () {
- /**
- * Creates a new Quaternion from the passed floats.
- */
- function Quaternion(x, y, z, w) {
- if (x === void 0) { x = 0.0; }
- if (y === void 0) { y = 0.0; }
- if (z === void 0) { z = 0.0; }
- if (w === void 0) { w = 1.0; }
- this.x = x;
- this.y = y;
- this.z = z;
- this.w = w;
- }
- /**
- * Returns a string with the Quaternion coordinates.
- */
- Quaternion.prototype.toString = function () {
- return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
- };
- /**
- * Returns the string "Quaternion".
- */
- Quaternion.prototype.getClassName = function () {
- return "Quaternion";
- };
- /**
- * Returns the Quaternion hash code.
- */
- Quaternion.prototype.getHashCode = function () {
- var hash = this.x || 0;
- hash = (hash * 397) ^ (this.y || 0);
- hash = (hash * 397) ^ (this.z || 0);
- hash = (hash * 397) ^ (this.w || 0);
- return hash;
- };
- /**
- * Returns a new array populated with 4 elements : the Quaternion coordinates.
- */
- Quaternion.prototype.asArray = function () {
- return [this.x, this.y, this.z, this.w];
- };
- /**
- * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
- */
- Quaternion.prototype.equals = function (otherQuaternion) {
- return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
- };
- /**
- * Returns a new Quaternion copied from the current one.
- */
- Quaternion.prototype.clone = function () {
- return new Quaternion(this.x, this.y, this.z, this.w);
- };
- /**
- * Updates the current Quaternion from the passed one coordinates.
- * Returns the updated Quaterion.
- */
- Quaternion.prototype.copyFrom = function (other) {
- this.x = other.x;
- this.y = other.y;
- this.z = other.z;
- this.w = other.w;
- return this;
- };
- /**
- * Updates the current Quaternion from the passed float coordinates.
- * Returns the updated Quaterion.
- */
- Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
- this.x = x;
- this.y = y;
- this.z = z;
- this.w = w;
- return this;
- };
- /**
- * Updates the current Quaternion from the passed float coordinates.
- * Returns the updated Quaterion.
- */
- Quaternion.prototype.set = function (x, y, z, w) {
- return this.copyFromFloats(x, y, z, w);
- };
- /**
- * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
- */
- Quaternion.prototype.add = function (other) {
- return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
- };
- /**
- * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
- */
- Quaternion.prototype.subtract = function (other) {
- return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
- };
- /**
- * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
- */
- Quaternion.prototype.scale = function (value) {
- return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
- };
- /**
- * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
- */
- Quaternion.prototype.multiply = function (q1) {
- var result = new Quaternion(0, 0, 0, 1.0);
- this.multiplyToRef(q1, result);
- return result;
- };
- /**
- * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
- * Returns the current Quaternion.
- */
- 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;
- };
- /**
- * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
- * Returns the updated Quaternion.
- */
- Quaternion.prototype.multiplyInPlace = function (q1) {
- this.multiplyToRef(q1, this);
- return this;
- };
- /**
- * Sets the passed "ref" with the conjugation of the current Quaternion.
- * Returns the current Quaternion.
- */
- Quaternion.prototype.conjugateToRef = function (ref) {
- ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
- return this;
- };
- /**
- * Conjugates in place the current Quaternion.
- * Returns the updated Quaternion.
- */
- Quaternion.prototype.conjugateInPlace = function () {
- this.x *= -1;
- this.y *= -1;
- this.z *= -1;
- return this;
- };
- /**
- * Returns a new Quaternion as the conjugate of the current Quaternion.
- */
- Quaternion.prototype.conjugate = function () {
- var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
- return result;
- };
- /**
- * Returns the Quaternion length (float).
- */
- Quaternion.prototype.length = function () {
- return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
- };
- /**
- * Normalize in place the current Quaternion.
- * Returns the updated Quaternion.
- */
- Quaternion.prototype.normalize = function () {
- var length = 1.0 / this.length();
- this.x *= length;
- this.y *= length;
- this.z *= length;
- this.w *= length;
- return this;
- };
- /**
- * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
- */
- Quaternion.prototype.toEulerAngles = function (order) {
- if (order === void 0) { order = "YZX"; }
- var result = Vector3.Zero();
- this.toEulerAnglesToRef(result, order);
- return result;
- };
- /**
- * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
- * Returns the current Quaternion.
- */
- Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
- if (order === void 0) { order = "YZX"; }
- var qz = this.z;
- var qx = this.x;
- var qy = this.y;
- var qw = this.w;
- var sqw = qw * qw;
- var sqz = qz * qz;
- var sqx = qx * qx;
- var sqy = qy * qy;
- var zAxisY = qy * qz - qx * qw;
- var limit = .4999999;
- if (zAxisY < -limit) {
- result.y = 2 * Math.atan2(qy, qw);
- result.x = Math.PI / 2;
- result.z = 0;
- }
- else if (zAxisY > limit) {
- result.y = 2 * Math.atan2(qy, qw);
- result.x = -Math.PI / 2;
- result.z = 0;
- }
- else {
- result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
- result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
- result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
- }
- return this;
- };
- /**
- * Updates the passed rotation matrix with the current Quaternion values.
- * Returns the current Quaternion.
- */
- 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;
- result._markAsUpdated();
- return this;
- };
- /**
- * Updates the current Quaternion from the passed rotation matrix values.
- * Returns the updated Quaternion.
- */
- Quaternion.prototype.fromRotationMatrix = function (matrix) {
- Quaternion.FromRotationMatrixToRef(matrix, this);
- return this;
- };
- // Statics
- /**
- * Returns a new Quaternion set from the passed rotation matrix values.
- */
- Quaternion.FromRotationMatrix = function (matrix) {
- var result = new Quaternion();
- Quaternion.FromRotationMatrixToRef(matrix, result);
- return result;
- };
- /**
- * Updates the passed quaternion "result" with the passed rotation matrix values.
- */
- 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;
- }
- };
- /**
- * Returns a new Quaternion set to (0.0, 0.0, 0.0).
- */
- Quaternion.Zero = function () {
- return new Quaternion(0.0, 0.0, 0.0, 0.0);
- };
- /**
- * Returns a new Quaternion as the inverted current Quaternion.
- */
- Quaternion.Inverse = function (q) {
- return new Quaternion(-q.x, -q.y, -q.z, q.w);
- };
- /**
- * Returns the identity Quaternion.
- */
- Quaternion.Identity = function () {
- return new Quaternion(0.0, 0.0, 0.0, 1.0);
- };
- Quaternion.IsIdentity = function (quaternion) {
- return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
- };
- /**
- * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
- */
- Quaternion.RotationAxis = function (axis, angle) {
- return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
- };
- /**
- * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
- */
- Quaternion.RotationAxisToRef = function (axis, angle, result) {
- 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;
- };
- /**
- * Retuns a new Quaternion set from the starting index of the passed array.
- */
- Quaternion.FromArray = function (array, offset) {
- if (!offset) {
- offset = 0;
- }
- return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
- };
- /**
- * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
- */
- Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
- var q = new Quaternion();
- Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
- return q;
- };
- /**
- * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
- */
- 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);
- };
- /**
- * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
- */
- Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
- var result = new Quaternion();
- Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
- return result;
- };
- /**
- * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
- */
- 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);
- };
- /**
- * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
- * cf to Vector3.RotationFromAxis() documentation.
- * Note : axis1, axis2 and axis3 are normalized during this operation.
- */
- Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
- var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
- Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
- return quat;
- };
- /**
- * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
- * cf to Vector3.RotationFromAxis() documentation.
- * Note : axis1, axis2 and axis3 are normalized during this operation.
- */
- Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
- var rotMat = MathTmp.Matrix[0];
- Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
- Quaternion.FromRotationMatrixToRef(rotMat, ref);
- };
- Quaternion.Slerp = function (left, right, amount) {
- var result = Quaternion.Identity();
- Quaternion.SlerpToRef(left, right, amount, result);
- return result;
- };
- Quaternion.SlerpToRef = function (left, right, amount, result) {
- 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);
- }
- result.x = (num3 * left.x) + (num2 * right.x);
- result.y = (num3 * left.y) + (num2 * right.y);
- result.z = (num3 * left.z) + (num2 * right.z);
- result.w = (num3 * left.w) + (num2 * right.w);
- };
- /**
- * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
- */
- Quaternion.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);
- var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
- return new Quaternion(x, y, z, w);
- };
- return Quaternion;
- }());
- BABYLON.Quaternion = Quaternion;
- var Matrix = /** @class */ (function () {
- function Matrix() {
- this._isIdentity = false;
- this._isIdentityDirty = true;
- this.m = new Float32Array(16);
- this._markAsUpdated();
- }
- Matrix.prototype._markAsUpdated = function () {
- this.updateFlag = Matrix._updateFlagSeed++;
- this._isIdentityDirty = true;
- };
- // Properties
- /**
- * Boolean : True is the matrix is the identity matrix
- */
- Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
- if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
- if (this._isIdentityDirty) {
- this._isIdentityDirty = false;
- if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
- this._isIdentity = false;
- }
- else 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) {
- this._isIdentity = false;
- }
- else {
- this._isIdentity = true;
- }
- if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
- this._isIdentity = false;
- }
- }
- return this._isIdentity;
- };
- /**
- * Returns the matrix determinant (float).
- */
- 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
- /**
- * Returns the matrix underlying array.
- */
- Matrix.prototype.toArray = function () {
- return this.m;
- };
- /**
- * Returns the matrix underlying array.
- */
- Matrix.prototype.asArray = function () {
- return this.toArray();
- };
- /**
- * Inverts in place the Matrix.
- * Returns the Matrix inverted.
- */
- Matrix.prototype.invert = function () {
- this.invertToRef(this);
- return this;
- };
- /**
- * Sets all the matrix elements to zero.
- * Returns the Matrix.
- */
- Matrix.prototype.reset = function () {
- for (var index = 0; index < 16; index++) {
- this.m[index] = 0.0;
- }
- this._markAsUpdated();
- return this;
- };
- /**
- * Returns a new Matrix as the addition result of the current Matrix and the passed one.
- */
- Matrix.prototype.add = function (other) {
- var result = new Matrix();
- this.addToRef(other, result);
- return result;
- };
- /**
- * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
- * Returns the Matrix.
- */
- Matrix.prototype.addToRef = function (other, result) {
- for (var index = 0; index < 16; index++) {
- result.m[index] = this.m[index] + other.m[index];
- }
- result._markAsUpdated();
- return this;
- };
- /**
- * Adds in place the passed matrix to the current Matrix.
- * Returns the updated Matrix.
- */
- Matrix.prototype.addToSelf = function (other) {
- for (var index = 0; index < 16; index++) {
- this.m[index] += other.m[index];
- }
- this._markAsUpdated();
- return this;
- };
- /**
- * Sets the passed matrix with the current inverted Matrix.
- * Returns the unmodified current Matrix.
- */
- 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;
- other._markAsUpdated();
- return this;
- };
- /**
- * Inserts the translation vector (using 3 x floats) in the current Matrix.
- * Returns the updated Matrix.
- */
- Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
- this.m[12] = x;
- this.m[13] = y;
- this.m[14] = z;
- this._markAsUpdated();
- return this;
- };
- /**
- * Inserts the translation vector in the current Matrix.
- * Returns the updated Matrix.
- */
- Matrix.prototype.setTranslation = function (vector3) {
- this.m[12] = vector3.x;
- this.m[13] = vector3.y;
- this.m[14] = vector3.z;
- this._markAsUpdated();
- return this;
- };
- /**
- * Returns a new Vector3 as the extracted translation from the Matrix.
- */
- Matrix.prototype.getTranslation = function () {
- return new Vector3(this.m[12], this.m[13], this.m[14]);
- };
- /**
- * Fill a Vector3 with the extracted translation from the Matrix.
- */
- Matrix.prototype.getTranslationToRef = function (result) {
- result.x = this.m[12];
- result.y = this.m[13];
- result.z = this.m[14];
- return this;
- };
- /**
- * Remove rotation and scaling part from the Matrix.
- * Returns the updated Matrix.
- */
- Matrix.prototype.removeRotationAndScaling = function () {
- this.setRowFromFloats(0, 1, 0, 0, 0);
- this.setRowFromFloats(1, 0, 1, 0, 0);
- this.setRowFromFloats(2, 0, 0, 1, 0);
- return this;
- };
- /**
- * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
- */
- Matrix.prototype.multiply = function (other) {
- var result = new Matrix();
- this.multiplyToRef(other, result);
- return result;
- };
- /**
- * Updates the current Matrix from the passed one values.
- * Returns the updated Matrix.
- */
- Matrix.prototype.copyFrom = function (other) {
- for (var index = 0; index < 16; index++) {
- this.m[index] = other.m[index];
- }
- this._markAsUpdated();
- return this;
- };
- /**
- * Populates the passed array from the starting index with the Matrix values.
- * Returns the Matrix.
- */
- 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;
- };
- /**
- * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
- */
- Matrix.prototype.multiplyToRef = function (other, result) {
- this.multiplyToArray(other, result.m, 0);
- result._markAsUpdated();
- return this;
- };
- /**
- * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
- */
- 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;
- };
- /**
- * Boolean : True is the current Matrix and the passed one values are strictly equal.
- */
- 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]);
- };
- /**
- * Returns a new Matrix from the current Matrix.
- */
- 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]);
- };
- /**
- * Returns the string "Matrix"
- */
- Matrix.prototype.getClassName = function () {
- return "Matrix";
- };
- /**
- * Returns the Matrix hash code.
- */
- Matrix.prototype.getHashCode = function () {
- var hash = this.m[0] || 0;
- for (var i = 1; i < 16; i++) {
- hash = (hash * 397) ^ (this.m[i] || 0);
- }
- return hash;
- };
- /**
- * Decomposes the current Matrix into :
- * - a scale vector3 passed as a reference to update,
- * - a rotation quaternion passed as a reference to update,
- * - a translation vector3 passed as a reference to update.
- * Returns the boolean `true`.
- */
- Matrix.prototype.decompose = function (scale, rotation, translation) {
- translation.x = this.m[12];
- translation.y = this.m[13];
- translation.z = this.m[14];
- scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
- scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
- scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
- if (this.determinant() <= 0) {
- scale.y *= -1;
- }
- if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
- rotation.x = 0;
- rotation.y = 0;
- rotation.z = 0;
- rotation.w = 1;
- return false;
- }
- Matrix.FromValuesToRef(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, MathTmp.Matrix[0]);
- Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
- return true;
- };
- /**
- * Returns a new Matrix as the extracted rotation matrix from the current one.
- */
- Matrix.prototype.getRotationMatrix = function () {
- var result = Matrix.Identity();
- this.getRotationMatrixToRef(result);
- return result;
- };
- /**
- * Extracts the rotation matrix from the current one and sets it as the passed "result".
- * Returns the current Matrix.
- */
- Matrix.prototype.getRotationMatrixToRef = function (result) {
- var m = this.m;
- var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
- var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
- var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
- var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
- var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
- var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
- Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
- return this;
- };
- // Statics
- /**
- * Returns a new Matrix set from the starting index of the passed array.
- */
- Matrix.FromArray = function (array, offset) {
- var result = new Matrix();
- if (!offset) {
- offset = 0;
- }
- Matrix.FromArrayToRef(array, offset, result);
- return result;
- };
- /**
- * Sets the passed "result" matrix from the starting index of the passed array.
- */
- Matrix.FromArrayToRef = function (array, offset, result) {
- for (var index = 0; index < 16; index++) {
- result.m[index] = array[index + offset];
- }
- result._markAsUpdated();
- };
- /**
- * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
- */
- Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
- for (var index = 0; index < 16; index++) {
- result.m[index] = array[index + offset] * scale;
- }
- result._markAsUpdated();
- };
- /**
- * Sets the passed matrix "result" with the 16 passed floats.
- */
- 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;
- result._markAsUpdated();
- };
- /**
- * Returns the index-th row of the current matrix as a new Vector4.
- */
- 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]);
- };
- /**
- * Sets the index-th row of the current matrix with the passed Vector4 values.
- * Returns the updated Matrix.
- */
- 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;
- this._markAsUpdated();
- return this;
- };
- /**
- * Compute the transpose of the matrix.
- * Returns a new Matrix.
- */
- Matrix.prototype.transpose = function () {
- return Matrix.Transpose(this);
- };
- /**
- * Compute the transpose of the matrix.
- * Returns the current matrix.
- */
- Matrix.prototype.transposeToRef = function (result) {
- Matrix.TransposeToRef(this, result);
- return this;
- };
- /**
- * Sets the index-th row of the current matrix with the passed 4 x float values.
- * Returns the updated Matrix.
- */
- Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
- if (index < 0 || index > 3) {
- return this;
- }
- var i = index * 4;
- this.m[i + 0] = x;
- this.m[i + 1] = y;
- this.m[i + 2] = z;
- this.m[i + 3] = w;
- this._markAsUpdated();
- return this;
- };
- Object.defineProperty(Matrix, "IdentityReadOnly", {
- /**
- * Static identity matrix to be used as readonly matrix
- * Must not be updated.
- */
- get: function () {
- return Matrix._identityReadOnly;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Returns a new Matrix set from the 16 passed floats.
- */
- 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;
- };
- /**
- * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
- */
- Matrix.Compose = function (scale, rotation, translation) {
- var result = Matrix.Identity();
- Matrix.ComposeToRef(scale, rotation, translation, result);
- return result;
- };
- /**
- * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
- */
- Matrix.ComposeToRef = function (scale, rotation, translation, result) {
- Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
- rotation.toRotationMatrix(MathTmp.Matrix[0]);
- MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
- result.setTranslation(translation);
- };
- /**
- * Returns a new indentity Matrix.
- */
- Matrix.Identity = function () {
- return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
- };
- /**
- * Sets the passed "result" as an identity matrix.
- */
- Matrix.IdentityToRef = function (result) {
- Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
- };
- /**
- * Returns a new zero Matrix.
- */
- Matrix.Zero = function () {
- return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
- };
- /**
- * Returns a new rotation matrix for "angle" radians around the X axis.
- */
- Matrix.RotationX = function (angle) {
- var result = new Matrix();
- Matrix.RotationXToRef(angle, result);
- return result;
- };
- /**
- * Returns a new Matrix as the passed inverted one.
- */
- Matrix.Invert = function (source) {
- var result = new Matrix();
- source.invertToRef(result);
- return result;
- };
- /**
- * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
- */
- 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.0;
- result.m[2] = 0.0;
- result.m[3] = 0.0;
- result.m[4] = 0.0;
- result.m[7] = 0.0;
- result.m[8] = 0.0;
- result.m[11] = 0.0;
- result.m[12] = 0.0;
- result.m[13] = 0.0;
- result.m[14] = 0.0;
- result._markAsUpdated();
- };
- /**
- * Returns a new rotation matrix for "angle" radians around the Y axis.
- */
- Matrix.RotationY = function (angle) {
- var result = new Matrix();
- Matrix.RotationYToRef(angle, result);
- return result;
- };
- /**
- * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
- */
- 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.0;
- result.m[3] = 0.0;
- result.m[4] = 0.0;
- result.m[6] = 0.0;
- result.m[7] = 0.0;
- result.m[9] = 0.0;
- result.m[11] = 0.0;
- result.m[12] = 0.0;
- result.m[13] = 0.0;
- result.m[14] = 0.0;
- result._markAsUpdated();
- };
- /**
- * Returns a new rotation matrix for "angle" radians around the Z axis.
- */
- Matrix.RotationZ = function (angle) {
- var result = new Matrix();
- Matrix.RotationZToRef(angle, result);
- return result;
- };
- /**
- * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
- */
- 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.0;
- result.m[3] = 0.0;
- result.m[6] = 0.0;
- result.m[7] = 0.0;
- result.m[8] = 0.0;
- result.m[9] = 0.0;
- result.m[11] = 0.0;
- result.m[12] = 0.0;
- result.m[13] = 0.0;
- result.m[14] = 0.0;
- result._markAsUpdated();
- };
- /**
- * Returns a new rotation matrix for "angle" radians around the passed axis.
- */
- Matrix.RotationAxis = function (axis, angle) {
- var result = Matrix.Zero();
- Matrix.RotationAxisToRef(axis, angle, result);
- return result;
- };
- /**
- * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
- */
- 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;
- result._markAsUpdated();
- };
- /**
- * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
- */
- Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
- var result = new Matrix();
- Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
- return result;
- };
- /**
- * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
- */
- Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
- Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
- this._tempQuaternion.toRotationMatrix(result);
- };
- /**
- * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
- */
- Matrix.Scaling = function (x, y, z) {
- var result = Matrix.Zero();
- Matrix.ScalingToRef(x, y, z, result);
- return result;
- };
- /**
- * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
- */
- Matrix.ScalingToRef = function (x, y, z, result) {
- result.m[0] = x;
- result.m[1] = 0.0;
- result.m[2] = 0.0;
- result.m[3] = 0.0;
- result.m[4] = 0.0;
- result.m[5] = y;
- result.m[6] = 0.0;
- result.m[7] = 0.0;
- result.m[8] = 0.0;
- result.m[9] = 0.0;
- result.m[10] = z;
- result.m[11] = 0.0;
- result.m[12] = 0.0;
- result.m[13] = 0.0;
- result.m[14] = 0.0;
- result.m[15] = 1.0;
- result._markAsUpdated();
- };
- /**
- * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
- */
- Matrix.Translation = function (x, y, z) {
- var result = Matrix.Identity();
- Matrix.TranslationToRef(x, y, z, result);
- return result;
- };
- /**
- * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
- */
- Matrix.TranslationToRef = function (x, y, z, result) {
- Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
- };
- /**
- * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
- */
- Matrix.Lerp = function (startValue, endValue, gradient) {
- var result = Matrix.Zero();
- for (var index = 0; index < 16; index++) {
- result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
- }
- result._markAsUpdated();
- return result;
- };
- /**
- * Returns a new Matrix whose values are computed by :
- * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
- * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
- * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
- */
- Matrix.DecomposeLerp = 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);
- };
- /**
- * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
- * This methods works for a Left-Handed system.
- */
- Matrix.LookAtLH = function (eye, target, up) {
- var result = Matrix.Zero();
- Matrix.LookAtLHToRef(eye, target, up, result);
- return result;
- };
- /**
- * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
- * This methods works for a Left-Handed system.
- */
- 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);
- };
- /**
- * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
- * This methods works for a Right-Handed system.
- */
- Matrix.LookAtRH = function (eye, target, up) {
- var result = Matrix.Zero();
- Matrix.LookAtRHToRef(eye, target, up, result);
- return result;
- };
- /**
- * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
- * This methods works for a Left-Handed system.
- */
- Matrix.LookAtRHToRef = function (eye, target, up, result) {
- // Z axis
- eye.subtractToRef(target, 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);
- };
- /**
- * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
- */
- Matrix.OrthoLH = function (width, height, znear, zfar) {
- var matrix = Matrix.Zero();
- Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
- return matrix;
- };
- /**
- * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
- */
- Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
- var n = znear;
- var f = zfar;
- var a = 2.0 / width;
- var b = 2.0 / height;
- var c = 2.0 / (f - n);
- var d = -(f + n) / (f - n);
- Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
- };
- /**
- * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
- */
- Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
- var matrix = Matrix.Zero();
- Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
- return matrix;
- };
- /**
- * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
- */
- Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
- var n = znear;
- var f = zfar;
- var a = 2.0 / (right - left);
- var b = 2.0 / (top - bottom);
- var c = 2.0 / (f - n);
- var d = -(f + n) / (f - n);
- var i0 = (left + right) / (left - right);
- var i1 = (top + bottom) / (bottom - top);
- Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
- };
- /**
- * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
- */
- Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
- var matrix = Matrix.Zero();
- Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
- return matrix;
- };
- /**
- * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
- */
- Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
- Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
- result.m[10] *= -1.0;
- };
- /**
- * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
- */
- Matrix.PerspectiveLH = function (width, height, znear, zfar) {
- var matrix = Matrix.Zero();
- var n = znear;
- var f = zfar;
- var a = 2.0 * n / width;
- var b = 2.0 * n / height;
- var c = (f + n) / (f - n);
- var d = -2.0 * f * n / (f - n);
- Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
- return matrix;
- };
- /**
- * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
- */
- Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
- var matrix = Matrix.Zero();
- Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
- return matrix;
- };
- /**
- * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
- */
- Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
- if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
- var n = znear;
- var f = zfar;
- var t = 1.0 / (Math.tan(fov * 0.5));
- var a = isVerticalFovFixed ? (t / aspect) : t;
- var b = isVerticalFovFixed ? t : (t * aspect);
- var c = (f + n) / (f - n);
- var d = -2.0 * f * n / (f - n);
- Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
- };
- /**
- * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
- */
- Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
- var matrix = Matrix.Zero();
- Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
- return matrix;
- };
- /**
- * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
- */
- Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
- //alternatively this could be expressed as:
- // m = PerspectiveFovLHToRef
- // m[10] *= -1.0;
- // m[11] *= -1.0;
- if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
- var n = znear;
- var f = zfar;
- var t = 1.0 / (Math.tan(fov * 0.5));
- var a = isVerticalFovFixed ? (t / aspect) : t;
- var b = isVerticalFovFixed ? t : (t * aspect);
- var c = -(f + n) / (f - n);
- var d = -2 * f * n / (f - n);
- Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
- };
- /**
- * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
- */
- Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
- if (rightHanded === void 0) { rightHanded = false; }
- var rightHandedFactor = rightHanded ? -1 : 1;
- var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
- var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
- var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
- var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
- var xScale = 2.0 / (leftTan + rightTan);
- var yScale = 2.0 / (upTan + downTan);
- result.m[0] = xScale;
- result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
- result.m[5] = yScale;
- result.m[6] = result.m[7] = 0.0;
- result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
- result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
- //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
- result.m[10] = -zfar / (znear - zfar);
- result.m[11] = 1.0 * rightHandedFactor;
- result.m[12] = result.m[13] = result.m[15] = 0.0;
- result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
- // result.m[14] = (znear * zfar) / (znear - zfar);
- result._markAsUpdated();
- };
- /**
- * Returns the final transformation matrix : world * view * projection * viewport
- */
- 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, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
- return world.multiply(view).multiply(projection).multiply(viewportMatrix);
- };
- /**
- * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
- */
- Matrix.GetAsMatrix2x2 = function (matrix) {
- return new Float32Array([
- matrix.m[0], matrix.m[1],
- matrix.m[4], matrix.m[5]
- ]);
- };
- /**
- * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
- */
- 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]
- ]);
- };
- /**
- * Compute the transpose of the passed Matrix.
- * Returns a new Matrix.
- */
- Matrix.Transpose = function (matrix) {
- var result = new Matrix();
- Matrix.TransposeToRef(matrix, result);
- return result;
- };
- /**
- * Compute the transpose of the passed Matrix and store it in the result matrix.
- */
- Matrix.TransposeToRef = function (matrix, result) {
- 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];
- };
- /**
- * Returns a new Matrix as the reflection matrix across the passed plane.
- */
- Matrix.Reflection = function (plane) {
- var matrix = new Matrix();
- Matrix.ReflectionToRef(plane, matrix);
- return matrix;
- };
- /**
- * Sets the passed matrix "result" as the reflection matrix across the passed plane.
- */
- 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;
- result._markAsUpdated();
- };
- /**
- * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
- */
- Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
- result.m[0] = xaxis.x;
- result.m[1] = xaxis.y;
- result.m[2] = xaxis.z;
- result.m[3] = 0.0;
- result.m[4] = yaxis.x;
- result.m[5] = yaxis.y;
- result.m[6] = yaxis.z;
- result.m[7] = 0.0;
- result.m[8] = zaxis.x;
- result.m[9] = zaxis.y;
- result.m[10] = zaxis.z;
- result.m[11] = 0.0;
- result.m[12] = 0.0;
- result.m[13] = 0.0;
- result.m[14] = 0.0;
- result.m[15] = 1.0;
- result._markAsUpdated();
- };
- /**
- * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
- */
- Matrix.FromQuaternionToRef = function (quat, result) {
- var xx = quat.x * quat.x;
- var yy = quat.y * quat.y;
- var zz = quat.z * quat.z;
- var xy = quat.x * quat.y;
- var zw = quat.z * quat.w;
- var zx = quat.z * quat.x;
- var yw = quat.y * quat.w;
- var yz = quat.y * quat.z;
- var xw = quat.x * quat.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.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.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.0;
- result.m[12] = 0.0;
- result.m[13] = 0.0;
- result.m[14] = 0.0;
- result.m[15] = 1.0;
- result._markAsUpdated();
- };
- Matrix._tempQuaternion = new Quaternion();
- Matrix._xAxis = Vector3.Zero();
- Matrix._yAxis = Vector3.Zero();
- Matrix._zAxis = Vector3.Zero();
- Matrix._updateFlagSeed = 0;
- Matrix._identityReadOnly = Matrix.Identity();
- return Matrix;
- }());
- BABYLON.Matrix = Matrix;
- var Plane = /** @class */ (function () {
- /**
- * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
- */
- function Plane(a, b, c, d) {
- this.normal = new Vector3(a, b, c);
- this.d = d;
- }
- /**
- * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
- */
- Plane.prototype.asArray = function () {
- return [this.normal.x, this.normal.y, this.normal.z, this.d];
- };
- // Methods
- /**
- * Returns a new plane copied from the current Plane.
- */
- Plane.prototype.clone = function () {
- return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
- };
- /**
- * Returns the string "Plane".
- */
- Plane.prototype.getClassName = function () {
- return "Plane";
- };
- /**
- * Returns the Plane hash code.
- */
- Plane.prototype.getHashCode = function () {
- var hash = this.normal.getHashCode();
- hash = (hash * 397) ^ (this.d || 0);
- return hash;
- };
- /**
- * Normalize the current Plane in place.
- * Returns the updated Plane.
- */
- 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.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;
- };
- /**
- * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
- */
- 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);
- };
- /**
- * Returns the dot product (float) of the point coordinates and the plane normal.
- */
- Plane.prototype.dotCoordinate = function (point) {
- return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
- };
- /**
- * Updates the current Plane from the plane defined by the three passed points.
- * Returns the updated Plane.
- */
- 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.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;
- };
- /**
- * Boolean : True is the vector "direction" is the same side than the plane normal.
- */
- Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
- var dot = Vector3.Dot(this.normal, direction);
- return (dot <= epsilon);
- };
- /**
- * Returns the signed distance (float) from the passed point to the Plane.
- */
- Plane.prototype.signedDistanceTo = function (point) {
- return Vector3.Dot(point, this.normal) + this.d;
- };
- // Statics
- /**
- * Returns a new Plane from the passed array.
- */
- Plane.FromArray = function (array) {
- return new Plane(array[0], array[1], array[2], array[3]);
- };
- /**
- * Returns a new Plane defined by the three passed points.
- */
- Plane.FromPoints = function (point1, point2, point3) {
- var result = new Plane(0.0, 0.0, 0.0, 0.0);
- result.copyFromPoints(point1, point2, point3);
- return result;
- };
- /**
- * Returns a new Plane the normal vector to this plane at the passed origin point.
- * Note : the vector "normal" is updated because normalized.
- */
- Plane.FromPositionAndNormal = function (origin, normal) {
- var result = new Plane(0.0, 0.0, 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;
- };
- /**
- * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
- */
- 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 = /** @class */ (function () {
- /**
- * Creates a Viewport object located at (x, y) and sized (width, height).
- */
- function Viewport(x, y, width, height) {
- this.x = x;
- this.y = y;
- this.width = width;
- this.height = height;
- }
- Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
- if (renderWidthOrEngine.getRenderWidth) {
- var engine = renderWidthOrEngine;
- return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
- }
- var renderWidth = renderWidthOrEngine;
- return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
- };
- /**
- * Returns a new Viewport copied from the current one.
- */
- Viewport.prototype.clone = function () {
- return new Viewport(this.x, this.y, this.width, this.height);
- };
- return Viewport;
- }());
- BABYLON.Viewport = Viewport;
- var Frustum = /** @class */ (function () {
- function Frustum() {
- }
- /**
- * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
- */
- Frustum.GetPlanes = function (transform) {
- var frustumPlanes = [];
- for (var index = 0; index < 6; index++) {
- frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
- }
- Frustum.GetPlanesToRef(transform, frustumPlanes);
- return frustumPlanes;
- };
- Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
- frustumPlane.normal.x = transform.m[3] + transform.m[2];
- frustumPlane.normal.y = transform.m[7] + transform.m[6];
- frustumPlane.normal.z = transform.m[11] + transform.m[10];
- frustumPlane.d = transform.m[15] + transform.m[14];
- frustumPlane.normalize();
- };
- Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
- frustumPlane.normal.x = transform.m[3] - transform.m[2];
- frustumPlane.normal.y = transform.m[7] - transform.m[6];
- frustumPlane.normal.z = transform.m[11] - transform.m[10];
- frustumPlane.d = transform.m[15] - transform.m[14];
- frustumPlane.normalize();
- };
- Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
- frustumPlane.normal.x = transform.m[3] + transform.m[0];
- frustumPlane.normal.y = transform.m[7] + transform.m[4];
- frustumPlane.normal.z = transform.m[11] + transform.m[8];
- frustumPlane.d = transform.m[15] + transform.m[12];
- frustumPlane.normalize();
- };
- Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
- frustumPlane.normal.x = transform.m[3] - transform.m[0];
- frustumPlane.normal.y = transform.m[7] - transform.m[4];
- frustumPlane.normal.z = transform.m[11] - transform.m[8];
- frustumPlane.d = transform.m[15] - transform.m[12];
- frustumPlane.normalize();
- };
- Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
- frustumPlane.normal.x = transform.m[3] - transform.m[1];
- frustumPlane.normal.y = transform.m[7] - transform.m[5];
- frustumPlane.normal.z = transform.m[11] - transform.m[9];
- frustumPlane.d = transform.m[15] - transform.m[13];
- frustumPlane.normalize();
- };
- Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
- frustumPlane.normal.x = transform.m[3] + transform.m[1];
- frustumPlane.normal.y = transform.m[7] + transform.m[5];
- frustumPlane.normal.z = transform.m[11] + transform.m[9];
- frustumPlane.d = transform.m[15] + transform.m[13];
- frustumPlane.normalize();
- };
- /**
- * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
- */
- Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
- // Near
- Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
- // Far
- Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
- // Left
- Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
- // Right
- Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
- // Top
- Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
- // Bottom
- Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
- };
- return Frustum;
- }());
- BABYLON.Frustum = Frustum;
- var Space;
- (function (Space) {
- Space[Space["LOCAL"] = 0] = "LOCAL";
- Space[Space["WORLD"] = 1] = "WORLD";
- Space[Space["BONE"] = 2] = "BONE";
- })(Space = BABYLON.Space || (BABYLON.Space = {}));
- var Axis = /** @class */ (function () {
- function Axis() {
- }
- Axis.X = new Vector3(1.0, 0.0, 0.0);
- Axis.Y = new Vector3(0.0, 1.0, 0.0);
- Axis.Z = new Vector3(0.0, 0.0, 1.0);
- return Axis;
- }());
- BABYLON.Axis = Axis;
- ;
- var BezierCurve = /** @class */ (function () {
- function BezierCurve() {
- }
- /**
- * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
- */
- 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;
- var Orientation;
- (function (Orientation) {
- Orientation[Orientation["CW"] = 0] = "CW";
- Orientation[Orientation["CCW"] = 1] = "CCW";
- })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
- var Angle = /** @class */ (function () {
- /**
- * Creates an Angle object of "radians" radians (float).
- */
- function Angle(radians) {
- var _this = this;
- /**
- * Returns the Angle value in degrees (float).
- */
- this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
- /**
- * Returns the Angle value in radians (float).
- */
- this.radians = function () { return _this._radians; };
- this._radians = radians;
- if (this._radians < 0.0)
- this._radians += (2.0 * Math.PI);
- }
- /**
- * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
- */
- Angle.BetweenTwoPoints = function (a, b) {
- var delta = b.subtract(a);
- var theta = Math.atan2(delta.y, delta.x);
- return new Angle(theta);
- };
- /**
- * Returns a new Angle object from the passed float in radians.
- */
- Angle.FromRadians = function (radians) {
- return new Angle(radians);
- };
- /**
- * Returns a new Angle object from the passed float in degrees.
- */
- Angle.FromDegrees = function (degrees) {
- return new Angle(degrees * Math.PI / 180.0);
- };
- return Angle;
- }());
- BABYLON.Angle = Angle;
- var Arc2 = /** @class */ (function () {
- /**
- * Creates an Arc object from the three passed points : start, middle and end.
- */
- 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 = /** @class */ (function () {
- /**
- * Creates a Path2 object from the starting 2D coordinates x and y.
- */
- function Path2(x, y) {
- this._points = new Array();
- this._length = 0.0;
- this.closed = false;
- this._points.push(new Vector2(x, y));
- }
- /**
- * Adds a new segment until the passed coordinates (x, y) to the current Path2.
- * Returns the updated Path2.
- */
- Path2.prototype.addLineTo = function (x, y) {
- if (this.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;
- };
- /**
- * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
- * Returns the updated Path2.
- */
- Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
- if (numberOfSegments === void 0) { numberOfSegments = 36; }
- if (this.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;
- };
- /**
- * Closes the Path2.
- * Returns the Path2.
- */
- Path2.prototype.close = function () {
- this.closed = true;
- return this;
- };
- /**
- * Returns the Path2 total length (float).
- */
- 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;
- };
- /**
- * Returns the Path2 internal array of points.
- */
- Path2.prototype.getPoints = function () {
- return this._points;
- };
- /**
- * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
- */
- 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();
- };
- /**
- * Returns a new Path2 starting at the coordinates (x, y).
- */
- Path2.StartingAt = function (x, y) {
- return new Path2(x, y);
- };
- return Path2;
- }());
- BABYLON.Path2 = Path2;
- var Path3D = /** @class */ (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) {
- if (firstNormal === void 0) { firstNormal = null; }
- 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) {
- if (firstNormal === void 0) { firstNormal = null; }
- 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.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;
- var tgl = vt.length();
- if (tgl === 0.0) {
- tgl = 1.0;
- }
- if (va === undefined || va === null) {
- var point;
- if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
- point = new Vector3(0.0, -1.0, 0.0);
- }
- else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
- point = new Vector3(1.0, 0.0, 0.0);
- }
- else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
- point = new Vector3(0.0, 0.0, 1.0);
- }
- else {
- point = Vector3.Zero();
- }
- 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 = /** @class */ (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.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.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - 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.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
- 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.0 / nbPoints;
- for (var i = 0; i <= nbPoints; i++) {
- hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
- }
- return new Curve3(hermite);
- };
- /**
- * Returns a Curve3 object along a CatmullRom Spline curve :
- * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
- * @param nbPoints (integer) the wanted number of points between each curve control points.
- */
- Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
- var totalPoints = new Array();
- totalPoints.push(points[0].clone());
- Array.prototype.push.apply(totalPoints, points);
- totalPoints.push(points[points.length - 1].clone());
- var catmullRom = new Array();
- var step = 1.0 / nbPoints;
- var amount = 0.0;
- for (var i = 0; i < totalPoints.length - 3; i++) {
- amount = 0;
- for (var c = 0; c < nbPoints; c++) {
- catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
- amount += step;
- }
- }
- i--;
- catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
- return new Curve3(catmullRom);
- };
- /**
- * 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;
- // Vertex formats
- var PositionNormalVertex = /** @class */ (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 = /** @class */ (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 = /** @class */ (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 = [Quaternion.Zero(), Quaternion.Zero()]; // 2 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;
- // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
- var MathTmp = /** @class */ (function () {
- function MathTmp() {
- }
- MathTmp.Vector3 = [Vector3.Zero()];
- MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
- MathTmp.Quaternion = [Quaternion.Zero()];
- return MathTmp;
- }());
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.math.js.map
- var BABYLON;
- (function (BABYLON) {
- var Scalar = /** @class */ (function () {
- function Scalar() {
- }
- /**
- * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
- */
- Scalar.WithinEpsilon = function (a, b, epsilon) {
- if (epsilon === void 0) { epsilon = 1.401298E-45; }
- var num = a - b;
- return -epsilon <= num && num <= epsilon;
- };
- /**
- * Returns a string : the upper case translation of the number i to hexadecimal.
- */
- Scalar.ToHex = function (i) {
- var str = i.toString(16);
- if (i <= 15) {
- return ("0" + str).toUpperCase();
- }
- return str.toUpperCase();
- };
- /**
- * Returns -1 if value is negative and +1 is value is positive.
- * Returns the value itself if it's equal to zero.
- */
- Scalar.Sign = function (value) {
- value = +value; // convert to a number
- if (value === 0 || isNaN(value))
- return value;
- return value > 0 ? 1 : -1;
- };
- /**
- * Returns the value itself if it's between min and max.
- * Returns min if the value is lower than min.
- * Returns max if the value is greater than max.
- */
- Scalar.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));
- };
- /**
- * Returns the log2 of value.
- */
- Scalar.Log2 = function (value) {
- return Math.log(value) * Math.LOG2E;
- };
- /**
- * Loops the value, so that it is never larger than length and never smaller than 0.
- *
- * This is similar to the modulo operator but it works with floating point numbers.
- * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
- * With t = 5 and length = 2.5, the result would be 0.0.
- * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
- */
- Scalar.Repeat = function (value, length) {
- return value - Math.floor(value / length) * length;
- };
- /**
- * Normalize the value between 0.0 and 1.0 using min and max values
- */
- Scalar.Normalize = function (value, min, max) {
- return (value - min) / (max - min);
- };
- /**
- * Denormalize the value from 0.0 and 1.0 using min and max values
- */
- Scalar.Denormalize = function (normalized, min, max) {
- return (normalized * (max - min) + min);
- };
- /**
- * Calculates the shortest difference between two given angles given in degrees.
- */
- Scalar.DeltaAngle = function (current, target) {
- var num = Scalar.Repeat(target - current, 360.0);
- if (num > 180.0) {
- num -= 360.0;
- }
- return num;
- };
- /**
- * PingPongs the value t, so that it is never larger than length and never smaller than 0.
- *
- * The returned value will move back and forth between 0 and length
- */
- Scalar.PingPong = function (tx, length) {
- var t = Scalar.Repeat(tx, length * 2.0);
- return length - Math.abs(t - length);
- };
- /**
- * Interpolates between min and max with smoothing at the limits.
- *
- * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
- * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
- */
- Scalar.SmoothStep = function (from, to, tx) {
- var t = Scalar.Clamp(tx);
- t = -2.0 * t * t * t + 3.0 * t * t;
- return to * t + from * (1.0 - t);
- };
- /**
- * Moves a value current towards target.
- *
- * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
- * Negative values of maxDelta pushes the value away from target.
- */
- Scalar.MoveTowards = function (current, target, maxDelta) {
- var result = 0;
- if (Math.abs(target - current) <= maxDelta) {
- result = target;
- }
- else {
- result = current + Scalar.Sign(target - current) * maxDelta;
- }
- return result;
- };
- /**
- * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
- *
- * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
- * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
- */
- Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
- var num = Scalar.DeltaAngle(current, target);
- var result = 0;
- if (-maxDelta < num && num < maxDelta) {
- result = target;
- }
- else {
- target = current + num;
- result = Scalar.MoveTowards(current, target, maxDelta);
- }
- return result;
- };
- /**
- * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
- */
- Scalar.Lerp = function (start, end, amount) {
- return start + ((end - start) * amount);
- };
- /**
- * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
- * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
- */
- Scalar.LerpAngle = function (start, end, amount) {
- var num = Scalar.Repeat(end - start, 360.0);
- if (num > 180.0) {
- num -= 360.0;
- }
- return start + num * Scalar.Clamp(amount);
- };
- /**
- * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
- */
- Scalar.InverseLerp = function (a, b, value) {
- var result = 0;
- if (a != b) {
- result = Scalar.Clamp((value - a) / (b - a));
- }
- else {
- result = 0.0;
- }
- return result;
- };
- /**
- * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
- */
- Scalar.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;
- return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
- };
- /**
- * Returns a random float number between and min and max values
- */
- Scalar.RandomRange = function (min, max) {
- if (min === max)
- return min;
- return ((Math.random() * (max - min)) + min);
- };
- /**
- * This function returns percentage of a number in a given range.
- *
- * RangeToPercent(40,20,60) will return 0.5 (50%)
- * RangeToPercent(34,0,100) will return 0.34 (34%)
- */
- Scalar.RangeToPercent = function (number, min, max) {
- return ((number - min) / (max - min));
- };
- /**
- * This function returns number that corresponds to the percentage in a given range.
- *
- * PercentToRange(0.34,0,100) will return 34.
- */
- Scalar.PercentToRange = function (percent, min, max) {
- return ((max - min) * percent + min);
- };
- /**
- * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
- * @param angle The angle to normalize in radian.
- * @return The converted angle.
- */
- Scalar.NormalizeRadians = function (angle) {
- // More precise but slower version kept for reference.
- // angle = angle % Tools.TwoPi;
- // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
- //if (angle > Math.PI) {
- // angle -= Tools.TwoPi;
- //}
- angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
- return angle;
- };
- /**
- * Two pi constants convenient for computation.
- */
- Scalar.TwoPi = Math.PI * 2;
- return Scalar;
- }());
- BABYLON.Scalar = Scalar;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.math.scalar.js.map
- //# sourceMappingURL=babylon.mixins.js.map
- // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
- // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
- // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
- // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
- //# sourceMappingURL=babylon.webgl2.js.map
- var BABYLON;
- (function (BABYLON) {
- var __decoratorInitialStore = {};
- var __mergedStore = {};
- var _copySource = function (creationFunction, source, instanciate) {
- var destination = creationFunction();
- // Tags
- if (BABYLON.Tags) {
- BABYLON.Tags.AddTagsTo(destination, source.tags);
- }
- var classStore = getMergedStore(destination);
- // Properties
- for (var property in classStore) {
- var propertyDescriptor = classStore[property];
- var sourceProperty = source[property];
- var propertyType = propertyDescriptor.type;
- if (sourceProperty !== undefined && sourceProperty !== null) {
- switch (propertyType) {
- case 0: // Value
- case 6:// Mesh reference
- destination[property] = sourceProperty;
- break;
- case 1:// Texture
- destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
- break;
- case 2: // Color3
- case 3: // FresnelParameters
- case 4: // Vector2
- case 5: // Vector3
- case 7: // Color Curves
- case 10:// Quaternion
- destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
- break;
- }
- }
- }
- return destination;
- };
- function getDirectStore(target) {
- var classKey = target.getClassName();
- if (!__decoratorInitialStore[classKey]) {
- __decoratorInitialStore[classKey] = {};
- }
- return __decoratorInitialStore[classKey];
- }
- /**
- * Return the list of properties flagged as serializable
- * @param target: host object
- */
- function getMergedStore(target) {
- var classKey = target.getClassName();
- if (__mergedStore[classKey]) {
- return __mergedStore[classKey];
- }
- __mergedStore[classKey] = {};
- var store = __mergedStore[classKey];
- var currentTarget = target;
- var currentKey = classKey;
- while (currentKey) {
- var initialStore = __decoratorInitialStore[currentKey];
- for (var property in initialStore) {
- store[property] = initialStore[property];
- }
- var parent_1 = void 0;
- var done = false;
- do {
- parent_1 = Object.getPrototypeOf(currentTarget);
- if (!parent_1.getClassName) {
- done = true;
- break;
- }
- if (parent_1.getClassName() !== currentKey) {
- break;
- }
- currentTarget = parent_1;
- } while (parent_1);
- if (done) {
- break;
- }
- currentKey = parent_1.getClassName();
- currentTarget = parent_1;
- }
- return store;
- }
- function generateSerializableMember(type, sourceName) {
- return function (target, propertyKey) {
- var classStore = getDirectStore(target);
- if (!classStore[propertyKey]) {
- classStore[propertyKey] = { type: type, sourceName: sourceName };
- }
- };
- }
- function generateExpandMember(setCallback, targetKey) {
- if (targetKey === void 0) { targetKey = null; }
- return function (target, propertyKey) {
- var key = targetKey || ("_" + propertyKey);
- Object.defineProperty(target, propertyKey, {
- get: function () {
- return this[key];
- },
- set: function (value) {
- if (this[key] === value) {
- return;
- }
- this[key] = value;
- target[setCallback].apply(this);
- },
- enumerable: true,
- configurable: true
- });
- };
- }
- function expandToProperty(callback, targetKey) {
- if (targetKey === void 0) { targetKey = null; }
- return generateExpandMember(callback, targetKey);
- }
- BABYLON.expandToProperty = expandToProperty;
- 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;
- function serializeAsColorCurves(sourceName) {
- return generateSerializableMember(7, sourceName); // color curves
- }
- BABYLON.serializeAsColorCurves = serializeAsColorCurves;
- function serializeAsColor4(sourceName) {
- return generateSerializableMember(8, sourceName); // color 4
- }
- BABYLON.serializeAsColor4 = serializeAsColor4;
- function serializeAsImageProcessingConfiguration(sourceName) {
- return generateSerializableMember(9, sourceName); // image processing
- }
- BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
- function serializeAsQuaternion(sourceName) {
- return generateSerializableMember(10, sourceName); // quaternion member
- }
- BABYLON.serializeAsQuaternion = serializeAsQuaternion;
- var SerializationHelper = /** @class */ (function () {
- function SerializationHelper() {
- }
- SerializationHelper.Serialize = function (entity, serializationObject) {
- if (!serializationObject) {
- serializationObject = {};
- }
- // Tags
- if (BABYLON.Tags) {
- serializationObject.tags = BABYLON.Tags.GetTags(entity);
- }
- var serializedProperties = getMergedStore(entity);
- // Properties
- for (var property in serializedProperties) {
- var propertyDescriptor = serializedProperties[property];
- var targetPropertyName = propertyDescriptor.sourceName || property;
- var propertyType = propertyDescriptor.type;
- var sourceProperty = entity[property];
- if (sourceProperty !== undefined && sourceProperty !== null) {
- switch (propertyType) {
- case 0:// Value
- serializationObject[targetPropertyName] = sourceProperty;
- break;
- case 1:// Texture
- serializationObject[targetPropertyName] = sourceProperty.serialize();
- break;
- case 2:// Color3
- serializationObject[targetPropertyName] = sourceProperty.asArray();
- break;
- case 3:// FresnelParameters
- serializationObject[targetPropertyName] = sourceProperty.serialize();
- break;
- case 4:// Vector2
- serializationObject[targetPropertyName] = sourceProperty.asArray();
- break;
- case 5:// Vector3
- serializationObject[targetPropertyName] = sourceProperty.asArray();
- break;
- case 6:// Mesh reference
- serializationObject[targetPropertyName] = sourceProperty.id;
- break;
- case 7:// Color Curves
- serializationObject[targetPropertyName] = sourceProperty.serialize();
- break;
- case 8:// Color 4
- serializationObject[targetPropertyName] = sourceProperty.asArray();
- break;
- case 9:// Image Processing
- serializationObject[targetPropertyName] = sourceProperty.serialize();
- break;
- }
- }
- }
- return serializationObject;
- };
- SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
- if (rootUrl === void 0) { rootUrl = null; }
- var destination = creationFunction();
- if (!rootUrl) {
- rootUrl = "";
- }
- // Tags
- if (BABYLON.Tags) {
- BABYLON.Tags.AddTagsTo(destination, source.tags);
- }
- var classStore = getMergedStore(destination);
- // Properties
- for (var property in classStore) {
- var propertyDescriptor = classStore[property];
- var sourceProperty = source[propertyDescriptor.sourceName || property];
- var propertyType = propertyDescriptor.type;
- if (sourceProperty !== undefined && sourceProperty !== null) {
- var dest = destination;
- switch (propertyType) {
- case 0:// Value
- dest[property] = sourceProperty;
- break;
- case 1:// Texture
- if (scene) {
- dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
- }
- break;
- case 2:// Color3
- dest[property] = BABYLON.Color3.FromArray(sourceProperty);
- break;
- case 3:// FresnelParameters
- dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
- break;
- case 4:// Vector2
- dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
- break;
- case 5:// Vector3
- dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
- break;
- case 6:// Mesh reference
- if (scene) {
- dest[property] = scene.getLastMeshByID(sourceProperty);
- }
- break;
- case 7:// Color Curves
- dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
- break;
- case 8:// Color 4
- dest[property] = BABYLON.Color4.FromArray(sourceProperty);
- break;
- case 9:// Image Processing
- dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
- break;
- }
- }
- }
- return destination;
- };
- SerializationHelper.Clone = function (creationFunction, source) {
- return _copySource(creationFunction, source, false);
- };
- SerializationHelper.Instanciate = function (creationFunction, source) {
- return _copySource(creationFunction, source, true);
- };
- return SerializationHelper;
- }());
- BABYLON.SerializationHelper = SerializationHelper;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.decorators.js.map
- var BABYLON;
- (function (BABYLON) {
- /**
- * A class serves as a medium between the observable and its observers
- */
- var EventState = /** @class */ (function () {
- /**
- * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
- */
- function EventState(mask, skipNextObservers, target, currentTarget) {
- if (skipNextObservers === void 0) { skipNextObservers = false; }
- this.initalize(mask, skipNextObservers, target, currentTarget);
- }
- EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
- if (skipNextObservers === void 0) { skipNextObservers = false; }
- this.mask = mask;
- this.skipNextObservers = skipNextObservers;
- this.target = target;
- this.currentTarget = currentTarget;
- return this;
- };
- return EventState;
- }());
- BABYLON.EventState = EventState;
- /**
- * Represent an Observer registered to a given Observable object.
- */
- var Observer = /** @class */ (function () {
- function Observer(callback, mask, scope) {
- if (scope === void 0) { scope = null; }
- this.callback = callback;
- this.mask = mask;
- this.scope = scope;
- }
- return Observer;
- }());
- BABYLON.Observer = Observer;
- /**
- * Represent a list of observers registered to multiple Observables object.
- */
- var MultiObserver = /** @class */ (function () {
- function MultiObserver() {
- }
- MultiObserver.prototype.dispose = function () {
- if (this._observers && this._observables) {
- for (var index = 0; index < this._observers.length; index++) {
- this._observables[index].remove(this._observers[index]);
- }
- }
- this._observers = null;
- this._observables = null;
- };
- MultiObserver.Watch = function (observables, callback, mask, scope) {
- if (mask === void 0) { mask = -1; }
- if (scope === void 0) { scope = null; }
- var result = new MultiObserver();
- result._observers = new Array();
- result._observables = observables;
- for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
- var observable = observables_1[_i];
- var observer = observable.add(callback, mask, false, scope);
- if (observer) {
- result._observers.push(observer);
- }
- }
- return result;
- };
- return MultiObserver;
- }());
- BABYLON.MultiObserver = MultiObserver;
- /**
- * The Observable class is a simple implementation of the Observable pattern.
- * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
- * This enable a more fine grained execution without having to rely on multiple different Observable objects.
- * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
- * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
- */
- var Observable = /** @class */ (function () {
- function Observable(onObserverAdded) {
- this._observers = new Array();
- this._eventState = new EventState(0);
- if (onObserverAdded) {
- this._onObserverAdded = onObserverAdded;
- }
- }
- /**
- * Create a new Observer with the specified callback
- * @param callback the callback that will be executed for that Observer
- * @param mask 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.
- * @param scope optional scope for the callback to be called from
- */
- Observable.prototype.add = function (callback, mask, insertFirst, scope) {
- if (mask === void 0) { mask = -1; }
- if (insertFirst === void 0) { insertFirst = false; }
- if (scope === void 0) { scope = null; }
- if (!callback) {
- return null;
- }
- var observer = new Observer(callback, mask, scope);
- if (insertFirst) {
- this._observers.unshift(observer);
- }
- else {
- this._observers.push(observer);
- }
- if (this._onObserverAdded) {
- this._onObserverAdded(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) {
- if (!observer) {
- return false;
- }
- 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.
- * @param scope optional scope. If used only the callbacks with this scope will be removed.
- */
- Observable.prototype.removeCallback = function (callback, scope) {
- for (var index = 0; index < this._observers.length; index++) {
- if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
- this._observers.splice(index, 1);
- return true;
- }
- }
- return false;
- };
- /**
- * Notify all Observers by calling their respective callback with the given data
- * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
- * @param eventData
- * @param mask
- */
- Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
- if (mask === void 0) { mask = -1; }
- if (!this._observers.length) {
- return true;
- }
- var state = this._eventState;
- state.mask = mask;
- state.target = target;
- state.currentTarget = currentTarget;
- state.skipNextObservers = false;
- for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
- var obs = _a[_i];
- if (obs.mask & mask) {
- if (obs.scope) {
- obs.callback.apply(obs.scope, [eventData, state]);
- }
- else {
- obs.callback(eventData, state);
- }
- }
- if (state.skipNextObservers) {
- return false;
- }
- }
- return true;
- };
- /**
- * Notify a specific observer
- * @param eventData
- * @param mask
- */
- Observable.prototype.notifyObserver = function (observer, eventData, mask) {
- if (mask === void 0) { mask = -1; }
- var state = this._eventState;
- state.mask = mask;
- state.skipNextObservers = false;
- observer.callback(eventData, state);
- };
- /**
- * 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();
- this._onObserverAdded = null;
- };
- /**
- * Clone the current observable
- */
- Observable.prototype.clone = function () {
- var result = new Observable();
- result._observers = this._observers.slice(0);
- return result;
- };
- /**
- * Does this observable handles observer registered with a given mask
- * @param {number} trigger - the mask to be tested
- * @return {boolean} whether or not one observer registered with the given mask is handeled
- **/
- Observable.prototype.hasSpecificMask = function (mask) {
- if (mask === void 0) { mask = -1; }
- for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
- var obs = _a[_i];
- if (obs.mask & mask || obs.mask === mask) {
- return true;
- }
- }
- return false;
- };
- return Observable;
- }());
- BABYLON.Observable = Observable;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.observable.js.map
- var BABYLON;
- (function (BABYLON) {
- var SmartArray = /** @class */ (function () {
- function SmartArray(capacity) {
- this.length = 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;
- }
- };
- SmartArray.prototype.forEach = function (func) {
- for (var index = 0; index < this.length; index++) {
- func(this.data[index]);
- }
- };
- SmartArray.prototype.sort = function (compareFn) {
- this.data.sort(compareFn);
- };
- SmartArray.prototype.reset = function () {
- this.length = 0;
- };
- SmartArray.prototype.dispose = function () {
- this.reset();
- if (this.data) {
- this.data.length = 0;
- this.data = [];
- }
- };
- 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.indexOf = function (value) {
- var position = this.data.indexOf(value);
- if (position >= this.length) {
- return -1;
- }
- return position;
- };
- SmartArray.prototype.contains = function (value) {
- return this.data.indexOf(value) !== -1;
- };
- // Statics
- SmartArray._GlobalId = 0;
- return SmartArray;
- }());
- BABYLON.SmartArray = SmartArray;
- var SmartArrayNoDuplicate = /** @class */ (function (_super) {
- __extends(SmartArrayNoDuplicate, _super);
- function SmartArrayNoDuplicate() {
- var _this = _super !== null && _super.apply(this, arguments) || this;
- _this._duplicateId = 0;
- return _this;
- }
- SmartArrayNoDuplicate.prototype.push = function (value) {
- _super.prototype.push.call(this, value);
- if (!value.__smartArrayFlags) {
- value.__smartArrayFlags = {};
- }
- value.__smartArrayFlags[this._id] = this._duplicateId;
- };
- SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
- if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
- return false;
- }
- this.push(value);
- return true;
- };
- SmartArrayNoDuplicate.prototype.reset = function () {
- _super.prototype.reset.call(this);
- this._duplicateId++;
- };
- SmartArrayNoDuplicate.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);
- }
- };
- return SmartArrayNoDuplicate;
- }(SmartArray));
- BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.smartArray.js.map
- var BABYLON;
- (function (BABYLON) {
- // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
- // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
- var LoadFileError = /** @class */ (function (_super) {
- __extends(LoadFileError, _super);
- function LoadFileError(message, request) {
- var _this = _super.call(this, message) || this;
- _this.request = request;
- _this.name = "LoadFileError";
- LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
- return _this;
- }
- // Polyfill for Object.setPrototypeOf if necessary.
- LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
- return LoadFileError;
- }(Error));
- BABYLON.LoadFileError = LoadFileError;
- var RetryStrategy = /** @class */ (function () {
- function RetryStrategy() {
- }
- RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
- if (maxRetries === void 0) { maxRetries = 3; }
- if (baseInterval === void 0) { baseInterval = 500; }
- return function (url, request, retryIndex) {
- if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
- return -1;
- }
- return Math.pow(2, retryIndex) * baseInterval;
- };
- };
- return RetryStrategy;
- }());
- BABYLON.RetryStrategy = RetryStrategy;
- // 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 = /** @class */ (function () {
- function Tools() {
- }
- /**
- * Interpolates between a and b via alpha
- * @param a The lower value (returned when alpha = 0)
- * @param b The upper value (returned when alpha = 1)
- * @param alpha The interpolation-factor
- * @return The mixed value
- */
- Tools.Mix = function (a, b, alpha) {
- return a * (1 - alpha) + b * alpha;
- };
- Tools.Instantiate = function (className) {
- if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
- return Tools.RegisteredExternalClasses[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;
- };
- /**
- * Find the next highest power of two.
- * @param x Number to start search from.
- * @return Next highest power of two.
- */
- Tools.CeilingPOT = function (x) {
- x--;
- x |= x >> 1;
- x |= x >> 2;
- x |= x >> 4;
- x |= x >> 8;
- x |= x >> 16;
- x++;
- return x;
- };
- /**
- * Find the next lowest power of two.
- * @param x Number to start search from.
- * @return Next lowest power of two.
- */
- Tools.FloorPOT = function (x) {
- x = x | (x >> 1);
- x = x | (x >> 2);
- x = x | (x >> 4);
- x = x | (x >> 8);
- x = x | (x >> 16);
- return x - (x >> 1);
- };
- /**
- * Find the nearest power of two.
- * @param x Number to start search from.
- * @return Next nearest power of two.
- */
- Tools.NearestPOT = function (x) {
- var c = Tools.CeilingPOT(x);
- var f = Tools.FloorPOT(x);
- return (c - x) > (x - f) ? f : c;
- };
- Tools.GetExponentOfTwo = function (value, max, mode) {
- if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
- var pot;
- switch (mode) {
- case BABYLON.Engine.SCALEMODE_FLOOR:
- pot = Tools.FloorPOT(value);
- break;
- case BABYLON.Engine.SCALEMODE_NEAREST:
- pot = Tools.NearestPOT(value);
- break;
- case BABYLON.Engine.SCALEMODE_CEILING:
- default:
- pot = Tools.CeilingPOT(value);
- break;
- }
- return Math.min(pot, max);
- };
- Tools.GetFilename = function (path) {
- var index = path.lastIndexOf("/");
- if (index < 0)
- return path;
- return path.substring(index + 1);
- };
- Tools.GetFolderPath = function (uri) {
- var index = uri.lastIndexOf("/");
- if (index < 0)
- return "";
- return uri.substring(0, 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, stride) {
- 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);
- if (!stride) {
- stride = 3;
- }
- for (var index = start; index < start + count; index++) {
- var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 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.Vector2ArrayFeeder = function (array) {
- return function (index) {
- var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
- var length = isFloatArray ? array.length / 2 : array.length;
- if (index >= length) {
- return null;
- }
- if (isFloatArray) {
- var fa = array;
- return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
- }
- var a = array;
- return a[index];
- };
- };
- Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
- if (bias === void 0) { bias = null; }
- var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
- var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
- var i = 0;
- var cur = feeder(i++);
- while (cur) {
- minimum = BABYLON.Vector2.Minimize(cur, minimum);
- maximum = BABYLON.Vector2.Maximize(cur, maximum);
- cur = feeder(i++);
- }
- if (bias) {
- minimum.x -= minimum.x * bias.x + bias.y;
- minimum.y -= minimum.y * bias.x + bias.y;
- maximum.x += maximum.x * bias.x + bias.y;
- maximum.y += maximum.y * bias.x + bias.y;
- }
- return {
- minimum: minimum,
- maximum: maximum
- };
- };
- Tools.MakeArray = function (obj, allowsNullUndefined) {
- if (allowsNullUndefined !== true && (obj === undefined || obj == null))
- return null;
- return Array.isArray(obj) ? obj : [obj];
- };
- // Misc.
- Tools.GetPointerPrefix = function () {
- var eventPrefix = "pointer";
- // Check if pointer events are supported
- if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
- eventPrefix = "mouse";
- }
- return eventPrefix;
- };
- /**
- * @param func - the function to be called
- * @param requester - the object that will request the next frame. Falls back to window.
- */
- Tools.QueueNewFrame = function (func, requester) {
- if (!Tools.IsWindowObjectExist()) {
- return setTimeout(func, 16);
- }
- if (!requester) {
- requester = window;
- }
- if (requester.requestAnimationFrame) {
- return requester.requestAnimationFrame(func);
- }
- else if (requester.msRequestAnimationFrame) {
- return requester.msRequestAnimationFrame(func);
- }
- else if (requester.webkitRequestAnimationFrame) {
- return requester.webkitRequestAnimationFrame(func);
- }
- else if (requester.mozRequestAnimationFrame) {
- return requester.mozRequestAnimationFrame(func);
- }
- else if (requester.oRequestAnimationFrame) {
- return requester.oRequestAnimationFrame(func);
- }
- else {
- return window.setTimeout(func, 16);
- }
- };
- Tools.RequestFullscreen = function (element) {
- var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
- if (!requestFunction)
- return;
- requestFunction.call(element);
- };
- 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();
- }
- };
- Tools.SetCorsBehavior = function (url, element) {
- if (url && url.indexOf("data:") === 0) {
- return;
- }
- if (Tools.CorsBehavior) {
- if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
- element.crossOrigin = Tools.CorsBehavior;
- }
- else {
- var result = Tools.CorsBehavior(url);
- if (result) {
- element.crossOrigin = result;
- }
- }
- }
- };
- // 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);
- url = Tools.PreprocessUrl(url);
- var img = new Image();
- Tools.SetCorsBehavior(url, img);
- img.onload = function () {
- onLoad(img);
- };
- img.onerror = function (err) {
- Tools.Error("Error while trying to load image: " + url);
- if (onError) {
- onError("Error while trying to load image: " + url, err);
- }
- };
- var noIndexedDB = function () {
- img.src = url;
- };
- var loadFromIndexedDB = function () {
- if (database) {
- 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) {
- var textureName = decodeURIComponent(url.substring(5).toLowerCase());
- if (BABYLON.FilesInput.FilesToLoad[textureName]) {
- try {
- var blobURL;
- try {
- blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
- }
- catch (ex) {
- // Chrome doesn't support oneTimeOnly parameter
- blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
- }
- img.src = blobURL;
- }
- catch (e) {
- img.src = "";
- }
- return img;
- }
- }
- noIndexedDB();
- }
- return img;
- };
- Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
- url = Tools.CleanUrl(url);
- url = Tools.PreprocessUrl(url);
- // If file and file input are set
- if (url.indexOf("file:") !== -1) {
- var fileName = decodeURIComponent(url.substring(5).toLowerCase());
- if (BABYLON.FilesInput.FilesToLoad[fileName]) {
- return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
- }
- }
- var loadUrl = Tools.BaseUrl + url;
- var aborted = false;
- var fileRequest = {
- onCompleteObservable: new BABYLON.Observable(),
- abort: function () { return aborted = true; },
- };
- var requestFile = function () {
- var request = new XMLHttpRequest();
- var retryHandle = null;
- fileRequest.abort = function () {
- aborted = true;
- if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
- request.abort();
- }
- if (retryHandle !== null) {
- clearTimeout(retryHandle);
- retryHandle = null;
- }
- };
- var retryLoop = function (retryIndex) {
- request.open('GET', loadUrl, true);
- if (useArrayBuffer) {
- request.responseType = "arraybuffer";
- }
- if (onProgress) {
- request.addEventListener("progress", onProgress);
- }
- var onLoadEnd = function () {
- fileRequest.onCompleteObservable.notifyObservers(fileRequest);
- };
- request.addEventListener("loadend", onLoadEnd);
- var onReadyStateChange = function () {
- if (aborted) {
- return;
- }
- // In case of undefined state in some browsers.
- if (request.readyState === (XMLHttpRequest.DONE || 4)) {
- // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
- request.removeEventListener("readystatechange", onReadyStateChange);
- if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
- onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
- return;
- }
- var retryStrategy = Tools.DefaultRetryStrategy;
- if (retryStrategy) {
- var waitTime = retryStrategy(loadUrl, request, retryIndex);
- if (waitTime !== -1) {
- // Prevent the request from completing for retry.
- request.removeEventListener("loadend", onLoadEnd);
- request = new XMLHttpRequest();
- retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
- return;
- }
- }
- var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
- if (onError) {
- onError(request, e);
- }
- else {
- throw e;
- }
- }
- };
- request.addEventListener("readystatechange", onReadyStateChange);
- request.send();
- };
- retryLoop(0);
- };
- // Caching all files
- if (database && database.enableSceneOffline) {
- var noIndexedDB_1 = function () {
- if (!aborted) {
- requestFile();
- }
- };
- var loadFromIndexedDB = function () {
- // TODO: database needs to support aborting and should return a IFileRequest
- if (aborted) {
- return;
- }
- if (database) {
- database.loadFileFromDB(url, function (data) {
- if (!aborted) {
- onSuccess(data);
- }
- fileRequest.onCompleteObservable.notifyObservers(fileRequest);
- }, onProgress ? function (event) {
- if (!aborted) {
- onProgress(event);
- }
- } : undefined, noIndexedDB_1, useArrayBuffer);
- }
- };
- database.openAsync(loadFromIndexedDB, noIndexedDB_1);
- }
- else {
- requestFile();
- }
- return fileRequest;
- };
- /**
- * Load a script (identified by an url). When the url returns, the
- * content of this file is added into a new script element, attached to the DOM (body element)
- */
- Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
- var head = document.getElementsByTagName('head')[0];
- var script = document.createElement('script');
- script.type = 'text/javascript';
- script.src = scriptUrl;
- script.onload = function () {
- if (onSuccess) {
- onSuccess();
- }
- };
- script.onerror = function (e) {
- if (onError) {
- onError("Unable to load script", e);
- }
- };
- head.appendChild(script);
- };
- Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
- var reader = new FileReader();
- var request = {
- onCompleteObservable: new BABYLON.Observable(),
- abort: function () { return reader.abort(); },
- };
- reader.onloadend = function (e) {
- request.onCompleteObservable.notifyObservers(request);
- };
- reader.onload = function (e) {
- //target doesn't have result from ts 1.3
- callback(e.target['result']);
- };
- reader.onprogress = progressCallback;
- reader.readAsDataURL(fileToLoad);
- return request;
- };
- Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
- var reader = new FileReader();
- var request = {
- onCompleteObservable: new BABYLON.Observable(),
- abort: function () { return reader.abort(); },
- };
- reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
- 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']);
- };
- if (progressCallBack) {
- reader.onprogress = progressCallBack;
- }
- if (!useArrayBuffer) {
- // Asynchronous read
- reader.readAsText(fileToLoad);
- }
- else {
- reader.readAsArrayBuffer(fileToLoad);
- }
- return request;
- };
- //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) {
- if (obj.hasOwnProperty(i)) {
- 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) {
- // Silently fails...
- }
- }
- };
- 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) {
- // Silently fails...
- }
- }
- };
- Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
- if (mimeType === void 0) { mimeType = "image/png"; }
- // 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');
- if (context) {
- // Copy the pixels to a 2D canvas
- var imageData = context.createImageData(width, height);
- var castData = (imageData.data);
- castData.set(data);
- context.putImageData(imageData, 0, 0);
- Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
- }
- };
- Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
- if (mimeType === void 0) { mimeType = "image/png"; }
- var base64Image = screenshotCanvas.toDataURL(mimeType);
- if (successCallback) {
- successCallback(base64Image);
- }
- else {
- // We need HTMLCanvasElement.toBlob for HD screenshots
- if (!screenshotCanvas.toBlob) {
- // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
- screenshotCanvas.toBlob = function (callback, type, quality) {
- var _this = this;
- setTimeout(function () {
- var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
- for (var i = 0; i < len; i++) {
- arr[i] = binStr.charCodeAt(i);
- }
- callback(new Blob([arr], { type: type || 'image/png' }));
- });
- };
- }
- screenshotCanvas.toBlob(function (blob) {
- var url = URL.createObjectURL(blob);
- //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 = url;
- if (fileName) {
- a.setAttribute("download", fileName);
- }
- else {
- 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 () {
- if (a.parentElement) {
- a.parentElement.removeChild(a);
- }
- });
- a.click();
- }
- else {
- var newWindow = window.open("");
- if (!newWindow)
- return;
- var img = newWindow.document.createElement("img");
- img.onload = function () {
- // no longer need to read the blob so it's revoked
- URL.revokeObjectURL(url);
- };
- img.src = url;
- newWindow.document.body.appendChild(img);
- }
- });
- }
- };
- Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
- if (mimeType === void 0) { mimeType = "image/png"; }
- 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));
- }
- 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));
- }
- else if (size.height && !size.width) {
- height = size.height;
- width = Math.round(height * engine.getAspectRatio(camera));
- }
- else if (!isNaN(size)) {
- height = size;
- width = size;
- }
- else {
- Tools.Error("Invalid 'size' parameter !");
- return;
- }
- if (!screenshotCanvas) {
- screenshotCanvas = document.createElement('canvas');
- }
- screenshotCanvas.width = width;
- screenshotCanvas.height = height;
- var renderContext = screenshotCanvas.getContext("2d");
- var ratio = engine.getRenderWidth() / engine.getRenderHeight();
- var newWidth = width;
- var newHeight = newWidth / ratio;
- if (newHeight > height) {
- newHeight = height;
- newWidth = newHeight * ratio;
- }
- var offsetX = Math.max(0, width - newWidth) / 2;
- var offsetY = Math.max(0, height - newHeight) / 2;
- var renderingCanvas = engine.getRenderingCanvas();
- if (renderContext && renderingCanvas) {
- renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
- }
- Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
- };
- Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
- if (mimeType === void 0) { mimeType = "image/png"; }
- if (samples === void 0) { samples = 1; }
- if (antialiasing === void 0) { antialiasing = false; }
- 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, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
- texture.renderList = null;
- texture.samples = samples;
- if (antialiasing) {
- texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
- }
- texture.onAfterRenderObservable.add(function () {
- Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
- });
- scene.incrementRenderId();
- scene.resetCachedMaterial();
- 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.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) {
- // Global protection
- }
- return false;
- };
- /**
- * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
- * Be aware Math.random() could cause collisions, but:
- * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
- */
- Tools.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);
- });
- };
- 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
- });
- Tools.IsWindowObjectExist = function () {
- return (typeof window) !== "undefined";
- };
- 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 (!Tools._performance) {
- if (!Tools.IsWindowObjectExist()) {
- return;
- }
- Tools._performance = window.performance;
- }
- 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 (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
- return window.performance.now();
- }
- return new Date().getTime();
- },
- enumerable: true,
- configurable: true
- });
- /**
- * This method will return the name of the class used to create the instance of the given object.
- * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
- * @param object the object to get the class name from
- * @return the name of the class, will be "object" for a custom data type not using the @className decorator
- */
- Tools.GetClassName = function (object, isType) {
- if (isType === void 0) { isType = false; }
- var name = null;
- if (!isType && object.getClassName) {
- name = object.getClassName();
- }
- else {
- if (object instanceof Object) {
- var classObj = isType ? object : Object.getPrototypeOf(object);
- name = classObj.constructor["__bjsclassName__"];
- }
- if (!name) {
- name = typeof object;
- }
- }
- return name;
- };
- Tools.First = function (array, predicate) {
- for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
- var el = array_1[_i];
- if (predicate(el)) {
- return el;
- }
- }
- return null;
- };
- /**
- * This method will return the name of the full name of the class, including its owning module (if any).
- * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
- * @param object the object to get the class name from
- * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
- */
- Tools.getFullClassName = function (object, isType) {
- if (isType === void 0) { isType = false; }
- var className = null;
- var moduleName = null;
- if (!isType && object.getClassName) {
- className = object.getClassName();
- }
- else {
- if (object instanceof Object) {
- var classObj = isType ? object : Object.getPrototypeOf(object);
- className = classObj.constructor["__bjsclassName__"];
- moduleName = classObj.constructor["__bjsmoduleName__"];
- }
- if (!className) {
- className = typeof object;
- }
- }
- if (!className) {
- return null;
- }
- return ((moduleName != null) ? (moduleName + ".") : "") + className;
- };
- /**
- * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
- * @param array
- */
- Tools.arrayOrStringFeeder = function (array) {
- return function (index) {
- if (index >= array.length) {
- return null;
- }
- var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
- if (val && val.getHashCode) {
- val = val.getHashCode();
- }
- if (typeof val === "string") {
- return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
- }
- return val;
- };
- };
- /**
- * Compute the hashCode of a stream of number
- * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
- * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
- * @return the hash code computed
- */
- Tools.hashCodeFromStream = function (feeder) {
- // Based from here: http://stackoverflow.com/a/7616484/802124
- var hash = 0;
- var index = 0;
- var chr = feeder(index++);
- while (chr != null) {
- hash = ((hash << 5) - hash) + chr;
- hash |= 0; // Convert to 32bit integer
- chr = feeder(index++);
- }
- return hash;
- };
- Tools.BaseUrl = "";
- Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
- /**
- * Default behaviour for cors in the application.
- * It can be a string if the expected behavior is identical in the entire app.
- * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
- */
- Tools.CorsBehavior = "anonymous";
- Tools.UseFallbackTexture = true;
- /**
- * Use this object to register external classes like custom textures or material
- * to allow the laoders to instantiate them
- */
- Tools.RegisteredExternalClasses = {};
- // Used in case of a texture loading problem
- Tools.fallbackTexture = "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";
- Tools.PreprocessUrl = function (url) {
- return url;
- };
- // 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.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
- Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
- return Tools;
- }());
- BABYLON.Tools = Tools;
- /**
- * This class is used to track a performance counter which is number based.
- * The user has access to many properties which give statistics of different nature
- *
- * The implementer can track two kinds of Performance Counter: time and count
- * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
- * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
- */
- var PerfCounter = /** @class */ (function () {
- function PerfCounter() {
- this._startMonitoringTime = 0;
- this._min = 0;
- this._max = 0;
- this._average = 0;
- this._lastSecAverage = 0;
- this._current = 0;
- this._totalValueCount = 0;
- this._totalAccumulated = 0;
- this._lastSecAccumulated = 0;
- this._lastSecTime = 0;
- this._lastSecValueCount = 0;
- }
- Object.defineProperty(PerfCounter.prototype, "min", {
- /**
- * Returns the smallest value ever
- */
- get: function () {
- return this._min;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PerfCounter.prototype, "max", {
- /**
- * Returns the biggest value ever
- */
- get: function () {
- return this._max;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PerfCounter.prototype, "average", {
- /**
- * Returns the average value since the performance counter is running
- */
- get: function () {
- return this._average;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
- /**
- * Returns the average value of the last second the counter was monitored
- */
- get: function () {
- return this._lastSecAverage;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PerfCounter.prototype, "current", {
- /**
- * Returns the current value
- */
- get: function () {
- return this._current;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PerfCounter.prototype, "total", {
- get: function () {
- return this._totalAccumulated;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PerfCounter.prototype, "count", {
- get: function () {
- return this._totalValueCount;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Call this method to start monitoring a new frame.
- * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
- */
- PerfCounter.prototype.fetchNewFrame = function () {
- this._totalValueCount++;
- this._current = 0;
- this._lastSecValueCount++;
- };
- /**
- * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
- * @param newCount the count value to add to the monitored count
- * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
- */
- PerfCounter.prototype.addCount = function (newCount, fetchResult) {
- if (!PerfCounter.Enabled) {
- return;
- }
- this._current += newCount;
- if (fetchResult) {
- this._fetchResult();
- }
- };
- /**
- * Start monitoring this performance counter
- */
- PerfCounter.prototype.beginMonitoring = function () {
- if (!PerfCounter.Enabled) {
- return;
- }
- this._startMonitoringTime = Tools.Now;
- };
- /**
- * Compute the time lapsed since the previous beginMonitoring() call.
- * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
- */
- PerfCounter.prototype.endMonitoring = function (newFrame) {
- if (newFrame === void 0) { newFrame = true; }
- if (!PerfCounter.Enabled) {
- return;
- }
- if (newFrame) {
- this.fetchNewFrame();
- }
- var currentTime = Tools.Now;
- this._current = currentTime - this._startMonitoringTime;
- if (newFrame) {
- this._fetchResult();
- }
- };
- PerfCounter.prototype._fetchResult = function () {
- this._totalAccumulated += this._current;
- this._lastSecAccumulated += this._current;
- // Min/Max update
- this._min = Math.min(this._min, this._current);
- this._max = Math.max(this._max, this._current);
- this._average = this._totalAccumulated / this._totalValueCount;
- // Reset last sec?
- var now = Tools.Now;
- if ((now - this._lastSecTime) > 1000) {
- this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
- this._lastSecTime = now;
- this._lastSecAccumulated = 0;
- this._lastSecValueCount = 0;
- }
- };
- PerfCounter.Enabled = true;
- return PerfCounter;
- }());
- BABYLON.PerfCounter = PerfCounter;
- /**
- * Use this className as a decorator on a given class definition to add it a name and optionally its module.
- * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
- * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
- * @param name The name of the class, case should be preserved
- * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
- */
- function className(name, module) {
- return function (target) {
- target["__bjsclassName__"] = name;
- target["__bjsmoduleName__"] = (module != null) ? module : null;
- };
- }
- BABYLON.className = className;
- /**
- * An implementation of a loop for asynchronous functions.
- */
- var AsyncLoop = /** @class */ (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 = {}));
- //# sourceMappingURL=babylon.tools.js.map
- var BABYLON;
- (function (BABYLON) {
- var _AlphaState = /** @class */ (function () {
- /**
- * Initializes the state.
- */
- function _AlphaState() {
- this._isAlphaBlendDirty = false;
- this._isBlendFunctionParametersDirty = false;
- this._isBlendEquationParametersDirty = false;
- this._isBlendConstantsDirty = false;
- this._alphaBlend = false;
- this._blendFunctionParameters = new Array(4);
- this._blendEquationParameters = new Array(2);
- this._blendConstants = new Array(4);
- this.reset();
- }
- 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.setAlphaBlendConstants = function (r, g, b, a) {
- if (this._blendConstants[0] === r &&
- this._blendConstants[1] === g &&
- this._blendConstants[2] === b &&
- this._blendConstants[3] === a) {
- return;
- }
- this._blendConstants[0] = r;
- this._blendConstants[1] = g;
- this._blendConstants[2] = b;
- this._blendConstants[3] = a;
- this._isBlendConstantsDirty = 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.setAlphaEquationParameters = function (rgb, alpha) {
- if (this._blendEquationParameters[0] === rgb &&
- this._blendEquationParameters[1] === alpha) {
- return;
- }
- this._blendEquationParameters[0] = rgb;
- this._blendEquationParameters[1] = alpha;
- this._isBlendEquationParametersDirty = 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._blendEquationParameters[0] = null;
- this._blendEquationParameters[1] = null;
- this._blendConstants[0] = null;
- this._blendConstants[1] = null;
- this._blendConstants[2] = null;
- this._blendConstants[3] = null;
- this._isAlphaBlendDirty = true;
- this._isBlendFunctionParametersDirty = false;
- this._isBlendEquationParametersDirty = false;
- this._isBlendConstantsDirty = 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;
- }
- // Alpha equation
- if (this._isBlendEquationParametersDirty) {
- gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
- this._isBlendEquationParametersDirty = false;
- }
- // Constants
- if (this._isBlendConstantsDirty) {
- gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
- this._isBlendConstantsDirty = false;
- }
- };
- return _AlphaState;
- }());
- BABYLON._AlphaState = _AlphaState;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.alphaCullingState.js.map
- var BABYLON;
- (function (BABYLON) {
- var _DepthCullingState = /** @class */ (function () {
- /**
- * Initializes the state.
- */
- function _DepthCullingState() {
- this._isDepthTestDirty = false;
- this._isDepthMaskDirty = false;
- this._isDepthFuncDirty = false;
- this._isCullFaceDirty = false;
- this._isCullDirty = false;
- this._isZOffsetDirty = false;
- this._isFrontFaceDirty = false;
- this.reset();
- }
- Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
- get: function () {
- return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
- },
- 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
- });
- Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
- get: function () {
- return this._frontFace;
- },
- set: function (value) {
- if (this._frontFace === value) {
- return;
- }
- this._frontFace = value;
- this._isFrontFaceDirty = true;
- },
- enumerable: true,
- configurable: true
- });
- _DepthCullingState.prototype.reset = function () {
- this._depthMask = true;
- this._depthTest = true;
- this._depthFunc = null;
- this._cullFace = null;
- this._cull = null;
- this._zOffset = 0;
- this._frontFace = null;
- this._isDepthTestDirty = true;
- this._isDepthMaskDirty = true;
- this._isDepthFuncDirty = false;
- this._isCullFaceDirty = false;
- this._isCullDirty = false;
- this._isZOffsetDirty = false;
- this._isFrontFaceDirty = 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;
- }
- // Front face
- if (this._isFrontFaceDirty) {
- gl.frontFace(this.frontFace);
- this._isFrontFaceDirty = false;
- }
- };
- return _DepthCullingState;
- }());
- BABYLON._DepthCullingState = _DepthCullingState;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.depthCullingState.js.map
- var BABYLON;
- (function (BABYLON) {
- var _StencilState = /** @class */ (function () {
- function _StencilState() {
- this._isStencilTestDirty = false;
- this._isStencilMaskDirty = false;
- this._isStencilFuncDirty = false;
- this._isStencilOpDirty = false;
- this.reset();
- }
- Object.defineProperty(_StencilState.prototype, "isDirty", {
- get: function () {
- return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(_StencilState.prototype, "stencilFunc", {
- get: function () {
- return this._stencilFunc;
- },
- set: function (value) {
- if (this._stencilFunc === value) {
- return;
- }
- this._stencilFunc = value;
- this._isStencilFuncDirty = true;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
- get: function () {
- return this._stencilFuncRef;
- },
- set: function (value) {
- if (this._stencilFuncRef === value) {
- return;
- }
- this._stencilFuncRef = value;
- this._isStencilFuncDirty = true;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
- get: function () {
- return this._stencilFuncMask;
- },
- set: function (value) {
- if (this._stencilFuncMask === value) {
- return;
- }
- this._stencilFuncMask = value;
- this._isStencilFuncDirty = true;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
- get: function () {
- return this._stencilOpStencilFail;
- },
- set: function (value) {
- if (this._stencilOpStencilFail === value) {
- return;
- }
- this._stencilOpStencilFail = value;
- this._isStencilOpDirty = true;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
- get: function () {
- return this._stencilOpDepthFail;
- },
- set: function (value) {
- if (this._stencilOpDepthFail === value) {
- return;
- }
- this._stencilOpDepthFail = value;
- this._isStencilOpDirty = true;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
- get: function () {
- return this._stencilOpStencilDepthPass;
- },
- set: function (value) {
- if (this._stencilOpStencilDepthPass === value) {
- return;
- }
- this._stencilOpStencilDepthPass = value;
- this._isStencilOpDirty = true;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(_StencilState.prototype, "stencilMask", {
- get: function () {
- return this._stencilMask;
- },
- set: function (value) {
- if (this._stencilMask === value) {
- return;
- }
- this._stencilMask = value;
- this._isStencilMaskDirty = true;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(_StencilState.prototype, "stencilTest", {
- get: function () {
- return this._stencilTest;
- },
- set: function (value) {
- if (this._stencilTest === value) {
- return;
- }
- this._stencilTest = value;
- this._isStencilTestDirty = true;
- },
- enumerable: true,
- configurable: true
- });
- _StencilState.prototype.reset = function () {
- this._stencilTest = false;
- this._stencilMask = 0xFF;
- this._stencilFunc = BABYLON.Engine.ALWAYS;
- this._stencilFuncRef = 1;
- this._stencilFuncMask = 0xFF;
- this._stencilOpStencilFail = BABYLON.Engine.KEEP;
- this._stencilOpDepthFail = BABYLON.Engine.KEEP;
- this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
- this._isStencilTestDirty = true;
- this._isStencilMaskDirty = true;
- this._isStencilFuncDirty = true;
- this._isStencilOpDirty = true;
- };
- _StencilState.prototype.apply = function (gl) {
- if (!this.isDirty) {
- return;
- }
- // Stencil test
- if (this._isStencilTestDirty) {
- if (this.stencilTest) {
- gl.enable(gl.STENCIL_TEST);
- }
- else {
- gl.disable(gl.STENCIL_TEST);
- }
- this._isStencilTestDirty = false;
- }
- // Stencil mask
- if (this._isStencilMaskDirty) {
- gl.stencilMask(this.stencilMask);
- this._isStencilMaskDirty = false;
- }
- // Stencil func
- if (this._isStencilFuncDirty) {
- gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
- this._isStencilFuncDirty = false;
- }
- // Stencil op
- if (this._isStencilOpDirty) {
- gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
- this._isStencilOpDirty = false;
- }
- };
- return _StencilState;
- }());
- BABYLON._StencilState = _StencilState;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.stencilState.js.map
- var BABYLON;
- (function (BABYLON) {
- var compileShader = function (gl, source, type, defines, shaderVersion) {
- return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
- };
- var compileRawShader = function (gl, source, type) {
- var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
- gl.shaderSource(shader, source);
- gl.compileShader(shader);
- if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
- var log = gl.getShaderInfoLog(shader);
- if (log) {
- throw new Error(log);
- }
- }
- if (!shader) {
- throw new Error("Something went wrong while compile the shader.");
- }
- return shader;
- };
- var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
- var magFilter = gl.NEAREST;
- var minFilter = gl.NEAREST;
- switch (samplingMode) {
- case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
- magFilter = gl.LINEAR;
- if (generateMipMaps) {
- minFilter = gl.LINEAR_MIPMAP_NEAREST;
- }
- else {
- minFilter = gl.LINEAR;
- }
- break;
- case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
- magFilter = gl.LINEAR;
- if (generateMipMaps) {
- minFilter = gl.LINEAR_MIPMAP_LINEAR;
- }
- else {
- minFilter = gl.LINEAR;
- }
- break;
- case BABYLON.Texture.NEAREST_SAMPLINGMODE:
- magFilter = gl.NEAREST;
- if (generateMipMaps) {
- minFilter = gl.NEAREST_MIPMAP_LINEAR;
- }
- else {
- minFilter = gl.NEAREST;
- }
- break;
- case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
- magFilter = gl.NEAREST;
- if (generateMipMaps) {
- minFilter = gl.NEAREST_MIPMAP_NEAREST;
- }
- else {
- minFilter = gl.NEAREST;
- }
- break;
- case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
- magFilter = gl.NEAREST;
- if (generateMipMaps) {
- minFilter = gl.LINEAR_MIPMAP_NEAREST;
- }
- else {
- minFilter = gl.LINEAR;
- }
- break;
- case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
- magFilter = gl.NEAREST;
- if (generateMipMaps) {
- minFilter = gl.LINEAR_MIPMAP_LINEAR;
- }
- else {
- minFilter = gl.LINEAR;
- }
- break;
- case BABYLON.Texture.NEAREST_LINEAR:
- magFilter = gl.NEAREST;
- minFilter = gl.LINEAR;
- break;
- case BABYLON.Texture.NEAREST_NEAREST:
- magFilter = gl.NEAREST;
- minFilter = gl.NEAREST;
- break;
- case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
- magFilter = gl.LINEAR;
- if (generateMipMaps) {
- minFilter = gl.NEAREST_MIPMAP_NEAREST;
- }
- else {
- minFilter = gl.NEAREST;
- }
- break;
- case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
- magFilter = gl.LINEAR;
- if (generateMipMaps) {
- minFilter = gl.NEAREST_MIPMAP_LINEAR;
- }
- else {
- minFilter = gl.NEAREST;
- }
- break;
- case BABYLON.Texture.LINEAR_LINEAR:
- magFilter = gl.LINEAR;
- minFilter = gl.LINEAR;
- break;
- case BABYLON.Texture.LINEAR_NEAREST:
- magFilter = gl.LINEAR;
- minFilter = gl.NEAREST;
- break;
- }
- return {
- min: minFilter,
- mag: magFilter
- };
- };
- var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
- if (onErrorCallBack === void 0) { onErrorCallBack = null; }
- var img;
- var onload = function () {
- loadedImages[index] = img;
- loadedImages._internalCount++;
- if (scene) {
- scene._removePendingData(img);
- }
- if (loadedImages._internalCount === 6) {
- onfinish(loadedImages);
- }
- };
- var onerror = function (message, exception) {
- if (scene) {
- scene._removePendingData(img);
- }
- if (onErrorCallBack) {
- onErrorCallBack(message, exception);
- }
- };
- img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
- if (scene) {
- scene._addPendingData(img);
- }
- };
- var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
- if (onError === void 0) { onError = null; }
- var loadedImages = [];
- loadedImages._internalCount = 0;
- for (var index = 0; index < 6; index++) {
- partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
- }
- };
- var BufferPointer = /** @class */ (function () {
- function BufferPointer() {
- }
- return BufferPointer;
- }());
- var InstancingAttributeInfo = /** @class */ (function () {
- function InstancingAttributeInfo() {
- }
- return InstancingAttributeInfo;
- }());
- BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
- /**
- * Define options used to create a render target texture
- */
- var RenderTargetCreationOptions = /** @class */ (function () {
- function RenderTargetCreationOptions() {
- }
- return RenderTargetCreationOptions;
- }());
- BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
- /**
- * Regroup several parameters relative to the browser in use
- */
- var EngineCapabilities = /** @class */ (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 = /** @class */ (function () {
- /**
- * @constructor
- * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
- * @param {boolean} [antialias] - enable antialias
- * @param options - further options to be sent to the getContext function
- */
- function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
- if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
- var _this = this;
- // Public members
- this.forcePOTTextures = false;
- this.isFullscreen = false;
- this.isPointerLock = false;
- this.cullBackFaces = true;
- this.renderEvenInBackground = true;
- this.preventCacheWipeBetweenFrames = false;
- // To enable/disable IDB support and avoid XHR on .manifest
- this.enableOfflineSupport = false;
- this.scenes = new Array();
- this.postProcesses = new Array();
- // Observables
- /**
- * Observable event triggered each time the rendering canvas is resized
- */
- this.onResizeObservable = new BABYLON.Observable();
- /**
- * Observable event triggered each time the canvas loses focus
- */
- this.onCanvasBlurObservable = new BABYLON.Observable();
- /**
- * Observable event triggered each time the canvas gains focus
- */
- this.onCanvasFocusObservable = new BABYLON.Observable();
- /**
- * Observable event triggered each time the canvas receives pointerout event
- */
- this.onCanvasPointerOutObservable = new BABYLON.Observable();
- /**
- * Observable event triggered before each texture is initialized
- */
- this.onBeforeTextureInitObservable = new BABYLON.Observable();
- //WebVR
- this._vrDisplay = undefined;
- this._vrSupported = false;
- this._vrExclusivePointerMode = false;
- // Uniform buffers list
- this.disableUniformBuffers = false;
- this._uniformBuffers = new Array();
- // Observables
- /**
- * Observable raised when the engine begins a new frame
- */
- this.onBeginFrameObservable = new BABYLON.Observable();
- /**
- * Observable raised when the engine ends the current frame
- */
- this.onEndFrameObservable = new BABYLON.Observable();
- /**
- * Observable raised when the engine is about to compile a shader
- */
- this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
- /**
- * Observable raised when the engine has jsut compiled a shader
- */
- this.onAfterShaderCompilationObservable = new BABYLON.Observable();
- this._windowIsBackground = false;
- this._webGLVersion = 1.0;
- this._badOS = false;
- this._badDesktopOS = false;
- this.onVRDisplayChangedObservable = new BABYLON.Observable();
- this.onVRRequestPresentComplete = new BABYLON.Observable();
- this.onVRRequestPresentStart = new BABYLON.Observable();
- this._colorWrite = true;
- this._drawCalls = new BABYLON.PerfCounter();
- this._textureCollisions = new BABYLON.PerfCounter();
- this._renderingQueueLaunched = false;
- this._activeRenderLoops = new Array();
- // Deterministic lockstepMaxSteps
- this._deterministicLockstep = false;
- this._lockstepMaxSteps = 4;
- // Lost context
- this.onContextLostObservable = new BABYLON.Observable();
- this.onContextRestoredObservable = new BABYLON.Observable();
- this._contextWasLost = false;
- this._doNotHandleContextLost = false;
- // FPS
- this._performanceMonitor = new BABYLON.PerformanceMonitor();
- this._fps = 60;
- this._deltaTime = 0;
- /**
- * Turn this value on if you want to pause FPS computation when in background
- */
- this.disablePerformanceMonitorInBackground = false;
- // States
- this._depthCullingState = new BABYLON._DepthCullingState();
- this._stencilState = new BABYLON._StencilState();
- this._alphaState = new BABYLON._AlphaState();
- this._alphaMode = Engine.ALPHA_DISABLE;
- // Cache
- this._internalTexturesCache = new Array();
- this._boundTexturesCache = {};
- this._boundTexturesStack = new Array();
- this._compiledEffects = {};
- this._vertexAttribArraysEnabled = [];
- this._uintIndicesCurrentlySet = false;
- this._currentBoundBuffer = new Array();
- this._currentBufferPointers = new Array();
- this._currentInstanceLocations = new Array();
- this._currentInstanceBuffers = new Array();
- this._vaoRecordInProgress = false;
- this._mustWipeVertexAttributes = false;
- this._nextFreeTextureSlots = new Array();
- this._activeRequests = new Array();
- // Hardware supported Compressed Textures
- this._texturesSupported = new Array();
- this._onVRFullScreenTriggered = function () {
- if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
- //get the old size before we change
- _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
- _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
- //get the width and height, change the render size
- var leftEye = _this._vrDisplay.getEyeParameters('left');
- _this.setHardwareScalingLevel(1);
- _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
- }
- else {
- _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
- _this.setSize(_this._oldSize.width, _this._oldSize.height);
- }
- };
- this._boundUniforms = {};
- var canvas = null;
- Engine.Instances.push(this);
- if (!canvasOrContext) {
- return;
- }
- options = options || {};
- if (canvasOrContext.getContext) {
- canvas = canvasOrContext;
- this._renderingCanvas = canvas;
- if (antialias != null) {
- options.antialias = antialias;
- }
- if (options.deterministicLockstep === undefined) {
- options.deterministicLockstep = false;
- }
- if (options.lockstepMaxSteps === undefined) {
- options.lockstepMaxSteps = 4;
- }
- if (options.preserveDrawingBuffer === undefined) {
- options.preserveDrawingBuffer = false;
- }
- if (options.audioEngine === undefined) {
- options.audioEngine = true;
- }
- if (options.stencil === undefined) {
- options.stencil = true;
- }
- this._deterministicLockstep = options.deterministicLockstep;
- this._lockstepMaxSteps = options.lockstepMaxSteps;
- this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
- // Exceptions
- if (navigator && navigator.userAgent) {
- var ua = navigator.userAgent;
- for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
- var exception = _a[_i];
- var key = exception.key;
- var targets = exception.targets;
- if (ua.indexOf(key) > -1) {
- if (exception.capture && exception.captureConstraint) {
- var capture = exception.capture;
- var constraint = exception.captureConstraint;
- var regex = new RegExp(capture);
- var matches = regex.exec(ua);
- if (matches && matches.length > 0) {
- var capturedValue = parseInt(matches[matches.length - 1]);
- if (capturedValue >= constraint) {
- continue;
- }
- }
- }
- for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
- var target = targets_1[_b];
- switch (target) {
- case "uniformBuffer":
- this.disableUniformBuffers = true;
- break;
- }
- }
- break;
- }
- }
- }
- // GL
- if (!options.disableWebGL2Support) {
- try {
- this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
- if (this._gl) {
- this._webGLVersion = 2.0;
- }
- }
- catch (e) {
- // Do nothing
- }
- }
- if (!this._gl) {
- if (!canvas) {
- throw new Error("The provided canvas is null or undefined.");
- }
- 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._onCanvasFocus = function () {
- _this.onCanvasFocusObservable.notifyObservers(_this);
- };
- this._onCanvasBlur = function () {
- _this.onCanvasBlurObservable.notifyObservers(_this);
- };
- canvas.addEventListener("focus", this._onCanvasFocus);
- canvas.addEventListener("blur", this._onCanvasBlur);
- this._onBlur = function () {
- if (_this.disablePerformanceMonitorInBackground) {
- _this._performanceMonitor.disable();
- }
- _this._windowIsBackground = true;
- };
- this._onFocus = function () {
- if (_this.disablePerformanceMonitorInBackground) {
- _this._performanceMonitor.enable();
- }
- _this._windowIsBackground = false;
- };
- this._onCanvasPointerOut = function () {
- _this.onCanvasPointerOutObservable.notifyObservers(_this);
- };
- window.addEventListener("blur", this._onBlur);
- window.addEventListener("focus", this._onFocus);
- canvas.addEventListener("pointerout", this._onCanvasPointerOut);
- // Context lost
- if (!this._doNotHandleContextLost) {
- this._onContextLost = function (evt) {
- evt.preventDefault();
- _this._contextWasLost = true;
- BABYLON.Tools.Warn("WebGL context lost.");
- _this.onContextLostObservable.notifyObservers(_this);
- };
- this._onContextRestored = function (evt) {
- // Adding a timeout to avoid race condition at browser level
- setTimeout(function () {
- // Rebuild gl context
- _this._initGLContext();
- // Rebuild effects
- _this._rebuildEffects();
- // Rebuild textures
- _this._rebuildInternalTextures();
- // Rebuild buffers
- _this._rebuildBuffers();
- // Cache
- _this.wipeCaches(true);
- BABYLON.Tools.Warn("WebGL context successfully restored.");
- _this.onContextRestoredObservable.notifyObservers(_this);
- _this._contextWasLost = false;
- }, 0);
- };
- canvas.addEventListener("webglcontextlost", this._onContextLost, false);
- canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
- }
- }
- else {
- this._gl = canvasOrContext;
- this._renderingCanvas = this._gl.canvas;
- if (this._gl.renderbufferStorageMultisample) {
- this._webGLVersion = 2.0;
- }
- options.stencil = this._gl.getContextAttributes().stencil;
- }
- // 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();
- this._isStencilEnable = options.stencil ? true : false;
- this._initGLContext();
- if (canvas) {
- // 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) {
- 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);
- this._onVRDisplayPointerRestricted = function () {
- if (canvas) {
- canvas.requestPointerLock();
- }
- };
- this._onVRDisplayPointerUnrestricted = function () {
- document.exitPointerLock();
- };
- window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
- window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
- }
- if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
- Engine.audioEngine = new BABYLON.AudioEngine();
- }
- // Prepare buffer pointers
- for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
- this._currentBufferPointers[i] = new BufferPointer();
- }
- // Load WebVR Devices
- if (options.autoEnableWebVR) {
- this.initWebVR();
- }
- // Detect if we are running on a faulty buggy OS.
- this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
- // Detect if we are running on a faulty buggy desktop OS.
- this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
- BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
- this.enableOfflineSupport = (BABYLON.Database !== undefined);
- }
- Object.defineProperty(Engine, "LastCreatedEngine", {
- get: function () {
- if (Engine.Instances.length === 0) {
- return null;
- }
- return Engine.Instances[Engine.Instances.length - 1];
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "LastCreatedScene", {
- get: function () {
- var lastCreatedEngine = Engine.LastCreatedEngine;
- if (!lastCreatedEngine) {
- return null;
- }
- if (lastCreatedEngine.scenes.length === 0) {
- return null;
- }
- return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
- */
- Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
- for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
- var engine = Engine.Instances[engineIndex];
- for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
- engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
- }
- }
- };
- Object.defineProperty(Engine, "NEVER", {
- get: function () {
- return Engine._NEVER;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "ALWAYS", {
- get: function () {
- return Engine._ALWAYS;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "LESS", {
- get: function () {
- return Engine._LESS;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "EQUAL", {
- get: function () {
- return Engine._EQUAL;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "LEQUAL", {
- get: function () {
- return Engine._LEQUAL;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "GREATER", {
- get: function () {
- return Engine._GREATER;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "GEQUAL", {
- get: function () {
- return Engine._GEQUAL;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "NOTEQUAL", {
- get: function () {
- return Engine._NOTEQUAL;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "KEEP", {
- get: function () {
- return Engine._KEEP;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "REPLACE", {
- get: function () {
- return Engine._REPLACE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "INCR", {
- get: function () {
- return Engine._INCR;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "DECR", {
- get: function () {
- return Engine._DECR;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "INVERT", {
- get: function () {
- return Engine._INVERT;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "INCR_WRAP", {
- get: function () {
- return Engine._INCR_WRAP;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "DECR_WRAP", {
- get: function () {
- return Engine._DECR_WRAP;
- },
- enumerable: true,
- configurable: true
- });
- 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, "ALPHA_PREMULTIPLIED", {
- get: function () {
- return Engine._ALPHA_PREMULTIPLIED;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
- get: function () {
- return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
- get: function () {
- return Engine._ALPHA_INTERPOLATE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
- get: function () {
- return Engine._ALPHA_SCREENMODE;
- },
- 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, "TEXTURETYPE_HALF_FLOAT", {
- get: function () {
- return Engine._TEXTURETYPE_HALF_FLOAT;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
- get: function () {
- return Engine._SCALEMODE_FLOOR;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
- get: function () {
- return Engine._SCALEMODE_NEAREST;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "SCALEMODE_CEILING", {
- get: function () {
- return Engine._SCALEMODE_CEILING;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine, "Version", {
- get: function () {
- return "3.2.0-alpha2";
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
- get: function () {
- return this._vrExclusivePointerMode;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
- get: function () {
- return this.webGLVersion > 1 && !this.disableUniformBuffers;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine.prototype, "needPOTTextures", {
- get: function () {
- return this._webGLVersion < 2 || this.forcePOTTextures;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine.prototype, "badOS", {
- get: function () {
- return this._badOS;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine.prototype, "badDesktopOS", {
- get: function () {
- return this._badDesktopOS;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine.prototype, "performanceMonitor", {
- get: function () {
- return this._performanceMonitor;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine.prototype, "texturesSupported", {
- get: function () {
- return this._texturesSupported;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine.prototype, "textureFormatInUse", {
- get: function () {
- return this._textureFormatInUse;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine.prototype, "currentViewport", {
- get: function () {
- return this._cachedViewport;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine.prototype, "emptyTexture", {
- // Empty texture
- get: function () {
- if (!this._emptyTexture) {
- this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
- }
- return this._emptyTexture;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine.prototype, "emptyTexture3D", {
- get: function () {
- if (!this._emptyTexture3D) {
- this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
- }
- return this._emptyTexture3D;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
- get: function () {
- if (!this._emptyCubeTexture) {
- var faceData = new Uint8Array(4);
- var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
- this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
- }
- return this._emptyCubeTexture;
- },
- enumerable: true,
- configurable: true
- });
- Engine.prototype._rebuildInternalTextures = function () {
- var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
- for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
- var internalTexture = currentState_1[_i];
- internalTexture._rebuild();
- }
- };
- Engine.prototype._rebuildEffects = function () {
- for (var key in this._compiledEffects) {
- var effect = this._compiledEffects[key];
- effect._prepareEffect();
- }
- BABYLON.Effect.ResetCache();
- };
- Engine.prototype._rebuildBuffers = function () {
- // Index / Vertex
- for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
- var scene = _a[_i];
- scene.resetCachedMaterial();
- scene._rebuildGeometries();
- scene._rebuildTextures();
- }
- // Uniforms
- for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
- var uniformBuffer = _c[_b];
- uniformBuffer._rebuild();
- }
- };
- Engine.prototype._initGLContext = function () {
- // Caps
- this._caps = new EngineCapabilities();
- this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
- this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
- this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_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);
- this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
- this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
- this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
- this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
- // 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";
- }
- // Constants
- this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
- if (this._gl.RGBA16F !== 0x881A) {
- this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
- }
- if (this._gl.RGBA32F !== 0x8814) {
- this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
- }
- if (this._gl.DEPTH24_STENCIL8 !== 35056) {
- this._gl.DEPTH24_STENCIL8 = 35056;
- }
- // Extensions
- this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
- this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
- this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
- this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
- this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
- this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
- this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
- 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.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
- this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
- this._caps.highPrecisionShaderSupported = true;
- this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
- if (this._caps.timerQuery) {
- if (this._webGLVersion === 1) {
- this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
- }
- this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
- }
- // Checks if some of the format renders first to allow the use of webgl inspector.
- this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
- this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
- this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
- this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
- this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
- this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
- if (this._webGLVersion > 1) {
- this._gl.HALF_FLOAT_OES = 0x140B;
- }
- this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
- this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
- // Draw buffers
- if (this._webGLVersion > 1) {
- this._caps.drawBuffersExtension = true;
- }
- else {
- var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
- if (drawBuffersExtension !== null) {
- this._caps.drawBuffersExtension = true;
- this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
- this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
- for (var i = 0; i < 16; i++) {
- this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
- }
- }
- else {
- this._caps.drawBuffersExtension = false;
- }
- }
- // Depth Texture
- if (this._webGLVersion > 1) {
- this._caps.depthTextureExtension = true;
- }
- else {
- var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
- if (depthTextureExtension != null) {
- this._caps.depthTextureExtension = true;
- }
- }
- // Vertex array object
- if (this._webGLVersion > 1) {
- this._caps.vertexArrayObject = true;
- }
- else {
- var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
- if (vertexArrayObjectExtension != null) {
- this._caps.vertexArrayObject = true;
- this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
- this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
- this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
- }
- else {
- this._caps.vertexArrayObject = false;
- }
- }
- // Instances count
- if (this._webGLVersion > 1) {
- this._caps.instancedArrays = true;
- }
- else {
- var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
- if (instanceExtension != null) {
- this._caps.instancedArrays = true;
- this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
- this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
- this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
- }
- else {
- this._caps.instancedArrays = false;
- }
- }
- // Intelligently add supported compressed formats in order to check for.
- // Check for ASTC support first as it is most powerful and to be very cross platform.
- // Next PVRTC & DXT, which are probably superior to ETC1/2.
- // Likely no hardware which supports both PVR & DXT, so order matters little.
- // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
- if (this._caps.astc)
- this.texturesSupported.push('-astc.ktx');
- if (this._caps.s3tc)
- this.texturesSupported.push('-dxt.ktx');
- if (this._caps.pvrtc)
- this.texturesSupported.push('-pvrtc.ktx');
- if (this._caps.etc2)
- this.texturesSupported.push('-etc2.ktx');
- if (this._caps.etc1)
- this.texturesSupported.push('-etc1.ktx');
- if (this._gl.getShaderPrecisionFormat) {
- var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
- if (highp) {
- this._caps.highPrecisionShaderSupported = highp.precision !== 0;
- }
- }
- // Depth buffer
- this.setDepthBuffer(true);
- this.setDepthFunctionToLessOrEqual();
- this.setDepthWrite(true);
- // Texture maps
- for (var slot = 0; slot < this._caps.maxCombinedTexturesImageUnits; slot++) {
- this._nextFreeTextureSlots.push(slot);
- }
- };
- Object.defineProperty(Engine.prototype, "webGLVersion", {
- get: function () {
- return this._webGLVersion;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine.prototype, "isStencilEnable", {
- /**
- * Returns true if the stencil buffer has been enabled through the creation option of the context.
- */
- get: function () {
- return this._isStencilEnable;
- },
- enumerable: true,
- configurable: true
- });
- Engine.prototype._prepareWorkingCanvas = function () {
- if (this._workingCanvas) {
- return;
- }
- this._workingCanvas = document.createElement("canvas");
- var context = this._workingCanvas.getContext("2d");
- if (context) {
- this._workingContext = context;
- }
- };
- Engine.prototype.resetTextureCache = function () {
- for (var key in this._boundTexturesCache) {
- var boundTexture = this._boundTexturesCache[key];
- if (boundTexture) {
- this._removeDesignatedSlot(boundTexture);
- }
- this._boundTexturesCache[key] = null;
- }
- this._nextFreeTextureSlots = [];
- for (var slot = 0; slot < this._caps.maxCombinedTexturesImageUnits; slot++) {
- this._nextFreeTextureSlots.push(slot);
- }
- this._activeChannel = -1;
- };
- Engine.prototype.isDeterministicLockStep = function () {
- return this._deterministicLockstep;
- };
- Engine.prototype.getLockstepMaxSteps = function () {
- return this._lockstepMaxSteps;
- };
- 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._gl.drawingBufferWidth;
- };
- Engine.prototype.getRenderHeight = function (useScreen) {
- if (useScreen === void 0) { useScreen = false; }
- if (!useScreen && this._currentRenderTarget) {
- return this._currentRenderTarget.height;
- }
- return this._gl.drawingBufferHeight;
- };
- Engine.prototype.getRenderingCanvas = function () {
- return this._renderingCanvas;
- };
- Engine.prototype.getRenderingCanvasClientRect = function () {
- if (!this._renderingCanvas) {
- return null;
- }
- 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._internalTexturesCache;
- };
- Engine.prototype.getCaps = function () {
- return this._caps;
- };
- Object.defineProperty(Engine.prototype, "drawCalls", {
- /** The number of draw calls submitted last frame */
- get: function () {
- BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
- return 0;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
- get: function () {
- BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
- return null;
- },
- enumerable: true,
- configurable: true
- });
- Engine.prototype.getDepthFunction = function () {
- return this._depthCullingState.depthFunc;
- };
- Engine.prototype.setDepthFunction = function (depthFunc) {
- this._depthCullingState.depthFunc = depthFunc;
- };
- 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;
- };
- Engine.prototype.getStencilBuffer = function () {
- return this._stencilState.stencilTest;
- };
- Engine.prototype.setStencilBuffer = function (enable) {
- this._stencilState.stencilTest = enable;
- };
- Engine.prototype.getStencilMask = function () {
- return this._stencilState.stencilMask;
- };
- Engine.prototype.setStencilMask = function (mask) {
- this._stencilState.stencilMask = mask;
- };
- Engine.prototype.getStencilFunction = function () {
- return this._stencilState.stencilFunc;
- };
- Engine.prototype.getStencilFunctionReference = function () {
- return this._stencilState.stencilFuncRef;
- };
- Engine.prototype.getStencilFunctionMask = function () {
- return this._stencilState.stencilFuncMask;
- };
- Engine.prototype.setStencilFunction = function (stencilFunc) {
- this._stencilState.stencilFunc = stencilFunc;
- };
- Engine.prototype.setStencilFunctionReference = function (reference) {
- this._stencilState.stencilFuncRef = reference;
- };
- Engine.prototype.setStencilFunctionMask = function (mask) {
- this._stencilState.stencilFuncMask = mask;
- };
- Engine.prototype.getStencilOperationFail = function () {
- return this._stencilState.stencilOpStencilFail;
- };
- Engine.prototype.getStencilOperationDepthFail = function () {
- return this._stencilState.stencilOpDepthFail;
- };
- Engine.prototype.getStencilOperationPass = function () {
- return this._stencilState.stencilOpStencilDepthPass;
- };
- Engine.prototype.setStencilOperationFail = function (operation) {
- this._stencilState.stencilOpStencilFail = operation;
- };
- Engine.prototype.setStencilOperationDepthFail = function (operation) {
- this._stencilState.stencilOpDepthFail = operation;
- };
- Engine.prototype.setStencilOperationPass = function (operation) {
- this._stencilState.stencilOpStencilDepthPass = operation;
- };
- Engine.prototype.setDitheringState = function (value) {
- if (value) {
- this._gl.enable(this._gl.DITHER);
- }
- else {
- this._gl.disable(this._gl.DITHER);
- }
- };
- Engine.prototype.setRasterizerState = function (value) {
- if (value) {
- this._gl.disable(this._gl.RASTERIZER_DISCARD);
- }
- else {
- this._gl.enable(this._gl.RASTERIZER_DISCARD);
- }
- };
- /**
- * 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 () {
- if (!this._contextWasLost) {
- 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
- var requester = null;
- if (this._vrDisplay && this._vrDisplay.isPresenting)
- requester = this._vrDisplay;
- this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
- }
- 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 continuously 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);
- this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
- }
- };
- /**
- * Toggle full screen mode.
- * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
- * @param {any} options - an options object to be sent to the requestFullscreen function
- */
- Engine.prototype.switchFullscreen = function (requestPointerLock) {
- if (this.isFullscreen) {
- BABYLON.Tools.ExitFullscreen();
- }
- else {
- this._pointerLockRequested = requestPointerLock;
- if (this._renderingCanvas) {
- BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
- }
- }
- };
- Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
- if (stencil === void 0) { stencil = false; }
- this.applyStates();
- var mode = 0;
- if (backBuffer && color) {
- this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
- mode |= this._gl.COLOR_BUFFER_BIT;
- }
- if (depth) {
- this._gl.clearDepth(1.0);
- mode |= this._gl.DEPTH_BUFFER_BIT;
- }
- if (stencil) {
- this._gl.clearStencil(0);
- mode |= this._gl.STENCIL_BUFFER_BIT;
- }
- this._gl.clear(mode);
- };
- Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
- var gl = this._gl;
- // Save state
- var curScissor = gl.getParameter(gl.SCISSOR_TEST);
- var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
- // Change state
- gl.enable(gl.SCISSOR_TEST);
- gl.scissor(x, y, width, height);
- // Clear
- this.clear(clearColor, true, true, true);
- // Restore state
- gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
- if (curScissor === true) {
- gl.enable(gl.SCISSOR_TEST);
- }
- else {
- gl.disable(gl.SCISSOR_TEST);
- }
- };
- /**
- * 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 || this.getRenderWidth();
- var height = requiredHeight || this.getRenderHeight();
- 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);
- };
- /**
- * Directly set the WebGL Viewport
- * The x, y, width & height are directly passed to the WebGL call
- * @return the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state.
- */
- Engine.prototype.setDirectViewport = function (x, y, width, height) {
- var currentViewport = this._cachedViewport;
- this._cachedViewport = null;
- this._gl.viewport(x, y, width, height);
- return currentViewport;
- };
- Engine.prototype.beginFrame = function () {
- this.onBeginFrameObservable.notifyObservers(this);
- this._measureFps();
- };
- Engine.prototype.endFrame = function () {
- //force a flush in case we are using a bad OS.
- if (this._badOS) {
- this.flushFramebuffer();
- }
- //submit frame to the vr device, if enabled
- if (this._vrDisplay && this._vrDisplay.isPresenting) {
- // TODO: We should only submit the frame if we read frameData successfully.
- this._vrDisplay.submitFrame();
- }
- this.onEndFrameObservable.notifyObservers(this);
- };
- /**
- * resize the view according to the canvas' size.
- * @example
- * window.addEventListener("resize", function () {
- * engine.resize();
- * });
- */
- Engine.prototype.resize = function () {
- // We're not resizing the size of the canvas while in VR mode & presenting
- if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
- var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
- var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
- this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
- }
- };
- /**
- * 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) {
- if (!this._renderingCanvas) {
- return;
- }
- if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
- return;
- }
- 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;
- }
- }
- if (this.onResizeObservable.hasObservers) {
- this.onResizeObservable.notifyObservers(this);
- }
- };
- // WebVR functions
- Engine.prototype.isVRDevicePresent = function () {
- return !!this._vrDisplay;
- };
- Engine.prototype.getVRDevice = function () {
- return this._vrDisplay;
- };
- Engine.prototype.initWebVR = function () {
- var _this = this;
- var notifyObservers = function () {
- var eventArgs = {
- vrDisplay: _this._vrDisplay,
- vrSupported: _this._vrSupported
- };
- _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
- };
- if (!this._onVrDisplayConnect) {
- this._onVrDisplayConnect = function (event) {
- _this._vrDisplay = event.display;
- notifyObservers();
- };
- this._onVrDisplayDisconnect = function () {
- _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
- _this._vrDisplay = undefined;
- _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
- notifyObservers();
- };
- this._onVrDisplayPresentChange = function () {
- _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
- };
- window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
- window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
- window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
- }
- this._getVRDisplays(notifyObservers);
- return this.onVRDisplayChangedObservable;
- };
- Engine.prototype.enableVR = function () {
- var _this = this;
- if (this._vrDisplay && !this._vrDisplay.isPresenting) {
- var onResolved = function () {
- _this.onVRRequestPresentComplete.notifyObservers(true);
- _this._onVRFullScreenTriggered();
- };
- var onRejected = function () {
- _this.onVRRequestPresentComplete.notifyObservers(false);
- };
- this.onVRRequestPresentStart.notifyObservers(this);
- this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
- }
- };
- Engine.prototype.disableVR = function () {
- if (this._vrDisplay && this._vrDisplay.isPresenting) {
- this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
- }
- };
- Engine.prototype._getVRDisplays = function (callback) {
- var _this = this;
- var getWebVRDevices = function (devices) {
- _this._vrSupported = true;
- // note that devices may actually be an empty array. This is fine;
- // we expect this._vrDisplay to be undefined in this case.
- return _this._vrDisplay = devices[0];
- };
- if (navigator.getVRDisplays) {
- navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
- // TODO: System CANNOT support WebVR, despite API presence.
- _this._vrSupported = false;
- callback();
- });
- }
- else {
- // TODO: Browser does not support WebVR
- this._vrDisplay = undefined;
- this._vrSupported = false;
- callback();
- }
- };
- Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
- if (this._currentRenderTarget) {
- this.unBindFramebuffer(this._currentRenderTarget);
- }
- this._currentRenderTarget = texture;
- this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
- var gl = this._gl;
- if (texture.isCube) {
- if (faceIndex === undefined) {
- faceIndex = 0;
- }
- gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
- }
- if (this._cachedViewport && !forceFullscreenViewport) {
- this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
- }
- else {
- gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
- }
- this.wipeCaches();
- };
- Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
- if (this._currentFramebuffer !== framebuffer) {
- this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
- this._currentFramebuffer = framebuffer;
- }
- };
- Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
- if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
- this._currentRenderTarget = null;
- // If MSAA, we need to bitblt back to main texture
- var gl = this._gl;
- if (texture._MSAAFramebuffer) {
- gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
- gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
- gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
- }
- if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
- this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
- gl.generateMipmap(gl.TEXTURE_2D);
- this._bindTextureDirectly(gl.TEXTURE_2D, null);
- }
- if (onBeforeUnbind) {
- if (texture._MSAAFramebuffer) {
- // Bind the correct framebuffer
- this.bindUnboundFramebuffer(texture._framebuffer);
- }
- onBeforeUnbind();
- }
- this.bindUnboundFramebuffer(null);
- };
- Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
- if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
- this._currentRenderTarget = null;
- // If MSAA, we need to bitblt back to main texture
- var gl = this._gl;
- if (textures[0]._MSAAFramebuffer) {
- gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
- gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
- var attachments = textures[0]._attachments;
- if (!attachments) {
- attachments = new Array(textures.length);
- textures[0]._attachments = attachments;
- }
- for (var i = 0; i < textures.length; i++) {
- var texture = textures[i];
- for (var j = 0; j < attachments.length; j++) {
- attachments[j] = gl.NONE;
- }
- attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
- gl.readBuffer(attachments[i]);
- gl.drawBuffers(attachments);
- gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
- }
- for (var i = 0; i < attachments.length; i++) {
- attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
- }
- gl.drawBuffers(attachments);
- }
- for (var i = 0; i < textures.length; i++) {
- var texture = textures[i];
- if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
- this._bindTextureDirectly(gl.TEXTURE_2D, texture);
- gl.generateMipmap(gl.TEXTURE_2D);
- this._bindTextureDirectly(gl.TEXTURE_2D, null);
- }
- }
- if (onBeforeUnbind) {
- if (textures[0]._MSAAFramebuffer) {
- // Bind the correct framebuffer
- this.bindUnboundFramebuffer(textures[0]._framebuffer);
- }
- onBeforeUnbind();
- }
- this.bindUnboundFramebuffer(null);
- };
- Engine.prototype.generateMipMapsForCubemap = function (texture) {
- if (texture.generateMipMaps) {
- var gl = this._gl;
- this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
- gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
- this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
- }
- };
- Engine.prototype.flushFramebuffer = function () {
- this._gl.flush();
- };
- Engine.prototype.restoreDefaultFramebuffer = function () {
- if (this._currentRenderTarget) {
- this.unBindFramebuffer(this._currentRenderTarget);
- }
- else {
- this.bindUnboundFramebuffer(null);
- }
- if (this._cachedViewport) {
- this.setViewport(this._cachedViewport);
- }
- this.wipeCaches();
- };
- // UBOs
- Engine.prototype.createUniformBuffer = function (elements) {
- var ubo = this._gl.createBuffer();
- if (!ubo) {
- throw new Error("Unable to create uniform buffer");
- }
- this.bindUniformBuffer(ubo);
- if (elements instanceof Float32Array) {
- this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
- }
- else {
- this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
- }
- this.bindUniformBuffer(null);
- ubo.references = 1;
- return ubo;
- };
- Engine.prototype.createDynamicUniformBuffer = function (elements) {
- var ubo = this._gl.createBuffer();
- if (!ubo) {
- throw new Error("Unable to create dynamic uniform buffer");
- }
- this.bindUniformBuffer(ubo);
- if (elements instanceof Float32Array) {
- this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
- }
- else {
- this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
- }
- this.bindUniformBuffer(null);
- ubo.references = 1;
- return ubo;
- };
- Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
- this.bindUniformBuffer(uniformBuffer);
- if (offset === undefined) {
- offset = 0;
- }
- if (count === undefined) {
- if (elements instanceof Float32Array) {
- this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
- }
- else {
- this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
- }
- }
- else {
- if (elements instanceof Float32Array) {
- this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
- }
- else {
- this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
- }
- }
- this.bindUniformBuffer(null);
- };
- // VBOs
- Engine.prototype._resetVertexBufferBinding = function () {
- this.bindArrayBuffer(null);
- this._cachedVertexBuffers = null;
- };
- Engine.prototype.createVertexBuffer = function (vertices) {
- var vbo = this._gl.createBuffer();
- if (!vbo) {
- throw new Error("Unable to create vertex buffer");
- }
- this.bindArrayBuffer(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 (vertices) {
- var vbo = this._gl.createBuffer();
- if (!vbo) {
- throw new Error("Unable to create dynamic vertex buffer");
- }
- this.bindArrayBuffer(vbo);
- if (vertices instanceof Float32Array) {
- this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
- }
- else {
- this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
- }
- this._resetVertexBufferBinding();
- vbo.references = 1;
- return vbo;
- };
- Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
- if (offset === void 0) { offset = 0; }
- // Force cache update
- this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
- this.bindIndexBuffer(indexBuffer);
- var arrayBuffer;
- if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
- arrayBuffer = indices;
- }
- else {
- arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
- }
- this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
- this._resetIndexBufferBinding();
- };
- Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
- this.bindArrayBuffer(vertexBuffer);
- if (offset === undefined) {
- offset = 0;
- }
- if (count === undefined) {
- 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));
- }
- }
- else {
- if (vertices instanceof Float32Array) {
- this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
- }
- else {
- this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
- }
- }
- this._resetVertexBufferBinding();
- };
- Engine.prototype._resetIndexBufferBinding = function () {
- this.bindIndexBuffer(null);
- this._cachedIndexBuffer = null;
- };
- Engine.prototype.createIndexBuffer = function (indices, updatable) {
- var vbo = this._gl.createBuffer();
- if (!vbo) {
- throw new Error("Unable to create index buffer");
- }
- this.bindIndexBuffer(vbo);
- // Check for 32 bits indices
- var arrayBuffer;
- var need32Bits = false;
- if (indices instanceof Uint16Array) {
- arrayBuffer = indices;
- }
- else {
- //check 32 bit support
- if (this._caps.uintIndices) {
- if (indices instanceof Uint32Array) {
- arrayBuffer = indices;
- need32Bits = true;
- }
- else {
- //number[] or Int32Array, check if 32 bit is necessary
- for (var index = 0; index < indices.length; index++) {
- if (indices[index] > 65535) {
- need32Bits = true;
- break;
- }
- }
- arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
- }
- }
- else {
- //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
- arrayBuffer = new Uint16Array(indices);
- }
- }
- this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
- this._resetIndexBufferBinding();
- vbo.references = 1;
- vbo.is32Bits = need32Bits;
- return vbo;
- };
- Engine.prototype.bindArrayBuffer = function (buffer) {
- if (!this._vaoRecordInProgress) {
- this._unbindVertexArrayObject();
- }
- this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
- };
- Engine.prototype.bindUniformBuffer = function (buffer) {
- this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
- };
- Engine.prototype.bindUniformBufferBase = function (buffer, location) {
- this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
- };
- Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
- var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
- this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
- };
- ;
- Engine.prototype.bindIndexBuffer = function (buffer) {
- if (!this._vaoRecordInProgress) {
- this._unbindVertexArrayObject();
- }
- this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
- };
- Engine.prototype.bindBuffer = function (buffer, target) {
- if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
- this._gl.bindBuffer(target, buffer);
- this._currentBoundBuffer[target] = buffer;
- }
- };
- Engine.prototype.updateArrayBuffer = function (data) {
- this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
- };
- Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
- var pointer = this._currentBufferPointers[indx];
- var changed = false;
- if (!pointer.active) {
- changed = true;
- pointer.active = true;
- pointer.index = indx;
- pointer.size = size;
- pointer.type = type;
- pointer.normalized = normalized;
- pointer.stride = stride;
- pointer.offset = offset;
- pointer.buffer = buffer;
- }
- else {
- if (pointer.buffer !== buffer) {
- pointer.buffer = buffer;
- changed = true;
- }
- if (pointer.size !== size) {
- pointer.size = size;
- changed = true;
- }
- if (pointer.type !== type) {
- pointer.type = type;
- changed = true;
- }
- if (pointer.normalized !== normalized) {
- pointer.normalized = normalized;
- changed = true;
- }
- if (pointer.stride !== stride) {
- pointer.stride = stride;
- changed = true;
- }
- if (pointer.offset !== offset) {
- pointer.offset = offset;
- changed = true;
- }
- }
- if (changed || this._vaoRecordInProgress) {
- this.bindArrayBuffer(buffer);
- this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
- }
- };
- Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
- if (indexBuffer == null) {
- return;
- }
- if (this._cachedIndexBuffer !== indexBuffer) {
- this._cachedIndexBuffer = indexBuffer;
- this.bindIndexBuffer(indexBuffer);
- this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
- }
- };
- Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
- var attributes = effect.getAttributesNames();
- if (!this._vaoRecordInProgress) {
- this._unbindVertexArrayObject();
- }
- this.unbindAllAttributes();
- for (var index = 0; index < attributes.length; index++) {
- var order = effect.getAttributeLocation(index);
- if (order >= 0) {
- var vertexBuffer = vertexBuffers[attributes[index]];
- if (!vertexBuffer) {
- continue;
- }
- this._gl.enableVertexAttribArray(order);
- if (!this._vaoRecordInProgress) {
- this._vertexAttribArraysEnabled[order] = true;
- }
- var buffer = vertexBuffer.getBuffer();
- if (buffer) {
- this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
- if (vertexBuffer.getIsInstanced()) {
- this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
- if (!this._vaoRecordInProgress) {
- this._currentInstanceLocations.push(order);
- this._currentInstanceBuffers.push(buffer);
- }
- }
- }
- }
- }
- };
- Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
- var vao = this._gl.createVertexArray();
- this._vaoRecordInProgress = true;
- this._gl.bindVertexArray(vao);
- this._mustWipeVertexAttributes = true;
- this._bindVertexBuffersAttributes(vertexBuffers, effect);
- this.bindIndexBuffer(indexBuffer);
- this._vaoRecordInProgress = false;
- this._gl.bindVertexArray(null);
- return vao;
- };
- Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
- if (this._cachedVertexArrayObject !== vertexArrayObject) {
- this._cachedVertexArrayObject = vertexArrayObject;
- this._gl.bindVertexArray(vertexArrayObject);
- this._cachedVertexBuffers = null;
- this._cachedIndexBuffer = null;
- this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
- this._mustWipeVertexAttributes = true;
- }
- };
- Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
- if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
- this._cachedVertexBuffers = vertexBuffer;
- this._cachedEffectForVertexBuffers = effect;
- var attributesCount = effect.getAttributesCount();
- this._unbindVertexArrayObject();
- this.unbindAllAttributes();
- var offset = 0;
- for (var index = 0; index < attributesCount; index++) {
- if (index < vertexDeclaration.length) {
- var order = effect.getAttributeLocation(index);
- if (order >= 0) {
- this._gl.enableVertexAttribArray(order);
- this._vertexAttribArraysEnabled[order] = true;
- this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
- }
- offset += vertexDeclaration[index] * 4;
- }
- }
- }
- this._bindIndexBufferWithCache(indexBuffer);
- };
- Engine.prototype._unbindVertexArrayObject = function () {
- if (!this._cachedVertexArrayObject) {
- return;
- }
- this._cachedVertexArrayObject = null;
- this._gl.bindVertexArray(null);
- };
- Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
- if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
- this._cachedVertexBuffers = vertexBuffers;
- this._cachedEffectForVertexBuffers = effect;
- this._bindVertexBuffersAttributes(vertexBuffers, effect);
- }
- this._bindIndexBufferWithCache(indexBuffer);
- };
- Engine.prototype.unbindInstanceAttributes = function () {
- var boundBuffer;
- for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
- var instancesBuffer = this._currentInstanceBuffers[i];
- if (boundBuffer != instancesBuffer && instancesBuffer.references) {
- boundBuffer = instancesBuffer;
- this.bindArrayBuffer(instancesBuffer);
- }
- var offsetLocation = this._currentInstanceLocations[i];
- this._gl.vertexAttribDivisor(offsetLocation, 0);
- }
- this._currentInstanceBuffers.length = 0;
- this._currentInstanceLocations.length = 0;
- };
- Engine.prototype.releaseVertexArrayObject = function (vao) {
- this._gl.deleteVertexArray(vao);
- };
- 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();
- if (!buffer) {
- throw new Error("Unable to create instance buffer");
- }
- buffer.capacity = capacity;
- this.bindArrayBuffer(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.bindArrayBuffer(instancesBuffer);
- if (data) {
- this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
- }
- if (offsetLocations[0].index !== undefined) {
- var stride = 0;
- for (var i = 0; i < offsetLocations.length; i++) {
- var ai = offsetLocations[i];
- stride += ai.attributeSize * 4;
- }
- for (var i = 0; i < offsetLocations.length; i++) {
- var ai = offsetLocations[i];
- if (!this._vertexAttribArraysEnabled[ai.index]) {
- this._gl.enableVertexAttribArray(ai.index);
- this._vertexAttribArraysEnabled[ai.index] = true;
- }
- this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
- this._gl.vertexAttribDivisor(ai.index, 1);
- this._currentInstanceLocations.push(ai.index);
- this._currentInstanceBuffers.push(instancesBuffer);
- }
- }
- else {
- for (var index = 0; index < 4; index++) {
- var offsetLocation = offsetLocations[index];
- if (!this._vertexAttribArraysEnabled[offsetLocation]) {
- this._gl.enableVertexAttribArray(offsetLocation);
- this._vertexAttribArraysEnabled[offsetLocation] = true;
- }
- this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
- this._gl.vertexAttribDivisor(offsetLocation, 1);
- this._currentInstanceLocations.push(offsetLocation);
- this._currentInstanceBuffers.push(instancesBuffer);
- }
- }
- };
- Engine.prototype.applyStates = function () {
- this._depthCullingState.apply(this._gl);
- this._stencilState.apply(this._gl);
- this._alphaState.apply(this._gl);
- };
- Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
- this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
- };
- Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
- this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
- };
- Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
- this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
- };
- Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
- // Apply states
- this.applyStates();
- this._drawCalls.addCount(1, false);
- // Render
- var drawMode = this.DrawMode(fillMode);
- var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
- var mult = this._uintIndicesCurrentlySet ? 4 : 2;
- if (instancesCount) {
- this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
- }
- else {
- this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
- }
- };
- Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
- // Apply states
- this.applyStates();
- this._drawCalls.addCount(1, false);
- var drawMode = this.DrawMode(fillMode);
- if (instancesCount) {
- this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
- }
- else {
- this._gl.drawArrays(drawMode, verticesStart, verticesCount);
- }
- };
- Engine.prototype.DrawMode = function (fillMode) {
- switch (fillMode) {
- // Triangle views
- case BABYLON.Material.TriangleFillMode:
- return this._gl.TRIANGLES;
- case BABYLON.Material.PointFillMode:
- return this._gl.POINTS;
- case BABYLON.Material.WireFrameFillMode:
- return this._gl.LINES;
- // Draw modes
- case BABYLON.Material.PointListDrawMode:
- return this._gl.POINTS;
- case BABYLON.Material.LineListDrawMode:
- return this._gl.LINES;
- case BABYLON.Material.LineLoopDrawMode:
- return this._gl.LINE_LOOP;
- case BABYLON.Material.LineStripDrawMode:
- return this._gl.LINE_STRIP;
- case BABYLON.Material.TriangleStripDrawMode:
- return this._gl.TRIANGLE_STRIP;
- case BABYLON.Material.TriangleFanDrawMode:
- return this._gl.TRIANGLE_FAN;
- default:
- return this._gl.TRIANGLES;
- }
- };
- // Shaders
- Engine.prototype._releaseEffect = function (effect) {
- if (this._compiledEffects[effect._key]) {
- delete this._compiledEffects[effect._key];
- this._deleteProgram(effect.getProgram());
- }
- };
- Engine.prototype._deleteProgram = function (program) {
- if (program) {
- program.__SPECTOR_rebuildProgram = null;
- if (program.transformFeedback) {
- this.deleteTransformFeedback(program.transformFeedback);
- program.transformFeedback = null;
- }
- this._gl.deleteProgram(program);
- }
- };
- /**
- * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
- * @param samplers An array of string used to represent textures
- */
- Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
- var vertex = baseName.vertexElement || baseName.vertex || baseName;
- var fragment = baseName.fragmentElement || baseName.fragment || baseName;
- var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
- if (this._compiledEffects[name]) {
- var compiledEffect = this._compiledEffects[name];
- if (onCompiled && compiledEffect.isReady()) {
- onCompiled(compiledEffect);
- }
- return compiledEffect;
- }
- var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
- 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.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
- if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
- context = context || this._gl;
- var vertexShader = compileRawShader(context, vertexCode, "vertex");
- var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
- return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
- };
- Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
- if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
- context = context || this._gl;
- this.onBeforeShaderCompilationObservable.notifyObservers(this);
- var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
- var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
- var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
- var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
- this.onAfterShaderCompilationObservable.notifyObservers(this);
- return program;
- };
- Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
- if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
- var shaderProgram = context.createProgram();
- if (!shaderProgram) {
- throw new Error("Unable to create program");
- }
- context.attachShader(shaderProgram, vertexShader);
- context.attachShader(shaderProgram, fragmentShader);
- if (this.webGLVersion > 1 && transformFeedbackVaryings) {
- var transformFeedback = this.createTransformFeedback();
- this.bindTransformFeedback(transformFeedback);
- this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
- shaderProgram.transformFeedback = transformFeedback;
- }
- context.linkProgram(shaderProgram);
- if (this.webGLVersion > 1 && transformFeedbackVaryings) {
- this.bindTransformFeedback(null);
- }
- var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
- if (!linked) {
- context.validateProgram(shaderProgram);
- var error = context.getProgramInfoLog(shaderProgram);
- if (error) {
- throw new Error(error);
- }
- }
- context.deleteShader(vertexShader);
- context.deleteShader(fragmentShader);
- return shaderProgram;
- };
- Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
- var results = new Array();
- 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) {
- return;
- }
- // Use program
- this.bindSamplers(effect);
- this._currentEffect = effect;
- if (effect.onBind) {
- effect.onBind(effect);
- }
- effect.onBindObservable.notifyObservers(effect);
- };
- Engine.prototype.setIntArray = function (uniform, array) {
- if (!uniform)
- return;
- this._gl.uniform1iv(uniform, array);
- };
- Engine.prototype.setIntArray2 = function (uniform, array) {
- if (!uniform || array.length % 2 !== 0)
- return;
- this._gl.uniform2iv(uniform, array);
- };
- Engine.prototype.setIntArray3 = function (uniform, array) {
- if (!uniform || array.length % 3 !== 0)
- return;
- this._gl.uniform3iv(uniform, array);
- };
- Engine.prototype.setIntArray4 = function (uniform, array) {
- if (!uniform || array.length % 4 !== 0)
- return;
- this._gl.uniform4iv(uniform, array);
- };
- Engine.prototype.setFloatArray = function (uniform, array) {
- if (!uniform)
- return;
- this._gl.uniform1fv(uniform, array);
- };
- Engine.prototype.setFloatArray2 = function (uniform, array) {
- if (!uniform || array.length % 2 !== 0)
- return;
- this._gl.uniform2fv(uniform, array);
- };
- Engine.prototype.setFloatArray3 = function (uniform, array) {
- if (!uniform || array.length % 3 !== 0)
- return;
- this._gl.uniform3fv(uniform, array);
- };
- Engine.prototype.setFloatArray4 = function (uniform, array) {
- if (!uniform || array.length % 4 !== 0)
- return;
- this._gl.uniform4fv(uniform, array);
- };
- 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.setInt = function (uniform, value) {
- if (!uniform)
- return;
- this._gl.uniform1i(uniform, value);
- };
- 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
- if (this._depthCullingState.cull !== culling || force) {
- this._depthCullingState.cull = culling;
- }
- // Cull face
- var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
- if (this._depthCullingState.cullFace !== cullFace || force) {
- this._depthCullingState.cullFace = cullFace;
- }
- // Z offset
- this.setZOffset(zOffset);
- // Front face
- var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
- if (this._depthCullingState.frontFace !== frontFace || force) {
- this._depthCullingState.frontFace = frontFace;
- }
- };
- Engine.prototype.setZOffset = function (value) {
- this._depthCullingState.zOffset = value;
- };
- Engine.prototype.getZOffset = function () {
- return this._depthCullingState.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);
- this._colorWrite = enable;
- };
- Engine.prototype.getColorWrite = function () {
- return this._colorWrite;
- };
- Engine.prototype.setAlphaConstants = function (r, g, b, a) {
- this._alphaState.setAlphaBlendConstants(r, g, b, a);
- };
- Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
- if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
- if (this._alphaMode === mode) {
- return;
- }
- switch (mode) {
- case Engine.ALPHA_DISABLE:
- this._alphaState.alphaBlend = false;
- break;
- case Engine.ALPHA_PREMULTIPLIED:
- this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
- this._alphaState.alphaBlend = true;
- break;
- case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
- this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
- this._alphaState.alphaBlend = true;
- break;
- case Engine.ALPHA_COMBINE:
- 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._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
- this._alphaState.alphaBlend = true;
- break;
- case Engine.ALPHA_ADD:
- 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._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._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._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
- this._alphaState.alphaBlend = true;
- break;
- case Engine.ALPHA_INTERPOLATE:
- this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
- this._alphaState.alphaBlend = true;
- break;
- case Engine.ALPHA_SCREENMODE:
- this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
- this._alphaState.alphaBlend = true;
- break;
- }
- if (!noDepthWriteChange) {
- this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
- }
- 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 (bruteForce) {
- if (this.preventCacheWipeBetweenFrames && !bruteForce) {
- return;
- }
- this._currentEffect = null;
- // 6/8/2017: deltakosh: Should not be required anymore.
- // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
- if (bruteForce) {
- this.resetTextureCache();
- this._currentProgram = null;
- this._stencilState.reset();
- this._depthCullingState.reset();
- this.setDepthFunctionToLessOrEqual();
- this._alphaState.reset();
- }
- this._resetVertexBufferBinding();
- this._cachedIndexBuffer = null;
- this._cachedEffectForVertexBuffers = null;
- this._unbindVertexArrayObject();
- this.bindIndexBuffer(null);
- };
- /**
- * Set the compressed texture format to use, based on the formats you have, and the formats
- * supported by the hardware / browser.
- *
- * Khronos Texture Container (.ktx) files are used to support this. This format has the
- * advantage of being specifically designed for OpenGL. Header elements directly correspond
- * to API arguments needed to compressed textures. This puts the burden on the container
- * generator to house the arcane code for determining these for current & future formats.
- *
- * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
- * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
- *
- * Note: The result of this call is not taken into account when a texture is base64.
- *
- * @param {Array<string>} formatsAvailable- The list of those format families you have created
- * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
- *
- * Current families are astc, dxt, pvrtc, etc2, & etc1.
- * @returns The extension selected.
- */
- Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
- for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
- for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
- if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
- return this._textureFormatInUse = this._texturesSupported[i];
- }
- }
- }
- // actively set format to nothing, to allow this to be called more than once
- // and possibly fail the 2nd time
- this._textureFormatInUse = null;
- return null;
- };
- Engine.prototype._createTexture = function () {
- var texture = this._gl.createTexture();
- if (!texture) {
- throw new Error("Unable to create texture");
- }
- return texture;
- };
- /**
- * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
- * @param {string} urlArg- This contains one of the following:
- * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
- * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
- * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
- *
- * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
- * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
- * @param {Scene} scene- Needed for loading to the correct scene.
- * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
- * @param {callback} onLoad- Optional callback to be called upon successful completion.
- * @param {callback} onError- Optional callback to be called upon failure.
- * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
- * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
- * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
- *
- * @returns {WebGLTexture} for assignment back into BABYLON.Texture
- */
- Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
- 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; }
- if (fallBack === void 0) { fallBack = null; }
- if (format === void 0) { format = null; }
- var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
- var fromData = url.substr(0, 5) === "data:";
- var fromBlob = url.substr(0, 5) === "blob:";
- var isBase64 = fromData && url.indexOf("base64") !== -1;
- var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
- // establish the file extension, if possible
- var lastDot = url.lastIndexOf('.');
- var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
- var isDDS = this.getCaps().s3tc && (extension === ".dds");
- var isTGA = (extension === ".tga");
- // determine if a ktx file should be substituted
- var isKTX = false;
- if (this._textureFormatInUse && !isBase64 && !fallBack) {
- url = url.substring(0, lastDot) + this._textureFormatInUse;
- isKTX = true;
- }
- if (scene) {
- scene._addPendingData(texture);
- }
- texture.url = url;
- texture.generateMipMaps = !noMipmap;
- texture.samplingMode = samplingMode;
- texture.invertY = invertY;
- if (!this._doNotHandleContextLost) {
- // Keep a link to the buffer only if we plan to handle context lost
- texture._buffer = buffer;
- }
- var onLoadObserver = null;
- if (onLoad && !fallBack) {
- onLoadObserver = texture.onLoadedObservable.add(onLoad);
- }
- if (!fallBack)
- this._internalTexturesCache.push(texture);
- var onerror = function (message, exception) {
- if (scene) {
- scene._removePendingData(texture);
- }
- if (onLoadObserver) {
- texture.onLoadedObservable.remove(onLoadObserver);
- }
- // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
- if (isKTX) {
- _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
- }
- else if (BABYLON.Tools.UseFallbackTexture) {
- _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
- }
- if (onError) {
- onError(message || "Unknown error", exception);
- }
- };
- var callback = null;
- // processing for non-image formats
- if (isKTX || isTGA || isDDS) {
- if (isKTX) {
- callback = function (data) {
- var ktx = new BABYLON.KhronosTextureContainer(data, 1);
- _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
- ktx.uploadLevels(_this._gl, !noMipmap);
- return false;
- }, samplingMode);
- };
- }
- else if (isTGA) {
- callback = function (arrayBuffer) {
- var data = new Uint8Array(arrayBuffer);
- var header = BABYLON.TGATools.GetTGAHeader(data);
- _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
- BABYLON.TGATools.UploadContent(_this._gl, data);
- return false;
- }, samplingMode);
- };
- }
- else if (isDDS) {
- callback = function (data) {
- var info = BABYLON.DDSTools.GetDDSInfo(data);
- var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
- _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
- BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
- return false;
- }, samplingMode);
- };
- }
- if (!buffer) {
- this._loadFile(url, function (data) {
- if (callback) {
- callback(data);
- }
- }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
- onerror("Unable to load " + (request ? request.responseURL : url, exception));
- });
- }
- else {
- if (callback) {
- callback(buffer);
- }
- }
- // image format processing
- }
- else {
- var onload = function (img) {
- if (fromBlob && !_this._doNotHandleContextLost) {
- // We need to store the image if we need to rebuild the texture
- // in case of a webgl context lost
- texture._buffer = img;
- }
- _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
- var gl = _this._gl;
- var isPot = (img.width === potWidth && img.height === potHeight);
- var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
- if (isPot) {
- gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
- return false;
- }
- // Using shaders to rescale because canvas.drawImage is lossy
- var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
- _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
- gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
- 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);
- _this._rescaleTexture(source, texture, scene, internalFormat, function () {
- _this._releaseTexture(source);
- _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
- continuationCallback();
- });
- return true;
- }, samplingMode);
- };
- if (!fromData || isBase64)
- if (buffer instanceof HTMLImageElement) {
- onload(buffer);
- }
- else {
- BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
- }
- else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
- BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
- else
- onload(buffer);
- }
- return texture;
- };
- Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
- var _this = this;
- var rtt = this.createRenderTargetTexture({
- width: destination.width,
- height: destination.height,
- }, {
- generateMipMaps: false,
- type: Engine.TEXTURETYPE_UNSIGNED_INT,
- samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
- generateDepthBuffer: false,
- generateStencilBuffer: false
- });
- if (!this._rescalePostProcess) {
- this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
- }
- this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
- _this._rescalePostProcess.onApply = function (effect) {
- effect._bindTexture("textureSampler", source);
- };
- var hostingScene = scene;
- if (!hostingScene) {
- hostingScene = _this.scenes[_this.scenes.length - 1];
- }
- hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
- _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
- _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
- _this.unBindFramebuffer(rtt);
- _this._releaseTexture(rtt);
- if (onComplete) {
- onComplete();
- }
- });
- };
- 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, type) {
- if (compression === void 0) { compression = null; }
- if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
- if (!texture) {
- return;
- }
- var internalFormat = this._getInternalFormat(format);
- var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
- var textureType = this._getWebGLTextureType(type);
- this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
- this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
- if (!this._doNotHandleContextLost) {
- texture._bufferView = data;
- texture.format = format;
- texture.type = type;
- texture.invertY = invertY;
- texture._compression = compression;
- }
- if (texture.width % 4 !== 0) {
- this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
- }
- if (compression && data) {
- 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, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
- }
- if (texture.generateMipMaps) {
- this._gl.generateMipmap(this._gl.TEXTURE_2D);
- }
- this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
- // this.resetTextureCache();
- texture.isReady = true;
- };
- Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
- if (compression === void 0) { compression = null; }
- if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
- var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
- texture.baseWidth = width;
- texture.baseHeight = height;
- texture.width = width;
- texture.height = height;
- texture.format = format;
- texture.generateMipMaps = generateMipMaps;
- texture.samplingMode = samplingMode;
- texture.invertY = invertY;
- texture._compression = compression;
- texture.type = type;
- if (!this._doNotHandleContextLost) {
- texture._bufferView = data;
- }
- this.updateRawTexture(texture, data, format, invertY, compression, type);
- this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
- // 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);
- if (generateMipMaps) {
- this._gl.generateMipmap(this._gl.TEXTURE_2D);
- }
- this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
- this._internalTexturesCache.push(texture);
- return texture;
- };
- Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
- var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
- texture.baseWidth = width;
- texture.baseHeight = height;
- if (generateMipMaps) {
- width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
- height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
- }
- // this.resetTextureCache();
- texture.width = width;
- texture.height = height;
- texture.isReady = false;
- texture.generateMipMaps = generateMipMaps;
- texture.samplingMode = samplingMode;
- this.updateTextureSamplingMode(samplingMode, texture);
- this._internalTexturesCache.push(texture);
- return texture;
- };
- Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
- var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
- if (texture.isCube) {
- this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
- 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._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
- }
- else if (texture.is3D) {
- this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
- this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
- this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
- this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
- }
- else {
- this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
- 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._bindTextureDirectly(this._gl.TEXTURE_2D, null);
- }
- texture.samplingMode = samplingMode;
- };
- Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
- if (premulAlpha === void 0) { premulAlpha = false; }
- if (!texture) {
- return;
- }
- this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
- this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
- if (premulAlpha) {
- this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
- }
- var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
- this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
- if (texture.generateMipMaps) {
- this._gl.generateMipmap(this._gl.TEXTURE_2D);
- }
- this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
- if (premulAlpha) {
- this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
- }
- texture.isReady = true;
- };
- Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
- if (!texture || texture._isDisabled) {
- return;
- }
- this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
- 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");
- var context = texture._workingCanvas.getContext("2d");
- if (!context) {
- throw new Error("Unable to get 2d context");
- }
- texture._workingContext = context;
- 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._bindTextureDirectly(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) {
- var fullOptions = new RenderTargetCreationOptions();
- if (options !== undefined && typeof options === "object") {
- fullOptions.generateMipMaps = options.generateMipMaps;
- fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
- fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
- fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
- fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
- }
- else {
- fullOptions.generateMipMaps = options;
- fullOptions.generateDepthBuffer = true;
- fullOptions.generateStencilBuffer = false;
- fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
- fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
- }
- if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
- // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
- fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
- }
- else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
- // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
- fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
- }
- var gl = this._gl;
- var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
- this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
- var width = size.width || size;
- var height = size.height || size;
- var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
- if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
- fullOptions.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, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
- // Create the framebuffer
- var framebuffer = gl.createFramebuffer();
- this.bindUnboundFramebuffer(framebuffer);
- gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
- texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
- if (fullOptions.generateMipMaps) {
- this._gl.generateMipmap(this._gl.TEXTURE_2D);
- }
- // Unbind
- this._bindTextureDirectly(gl.TEXTURE_2D, null);
- gl.bindRenderbuffer(gl.RENDERBUFFER, null);
- this.bindUnboundFramebuffer(null);
- texture._framebuffer = framebuffer;
- texture.baseWidth = width;
- texture.baseHeight = height;
- texture.width = width;
- texture.height = height;
- texture.isReady = true;
- texture.samples = 1;
- texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
- texture.samplingMode = fullOptions.samplingMode;
- texture.type = fullOptions.type;
- texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
- texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
- // this.resetTextureCache();
- this._internalTexturesCache.push(texture);
- return texture;
- };
- Engine.prototype.createMultipleRenderTarget = function (size, options) {
- var generateMipMaps = false;
- var generateDepthBuffer = true;
- var generateStencilBuffer = false;
- var generateDepthTexture = false;
- var textureCount = 1;
- var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
- var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
- var types = [], samplingModes = [];
- if (options !== undefined) {
- generateMipMaps = options.generateMipMaps;
- generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
- generateStencilBuffer = options.generateStencilBuffer;
- generateDepthTexture = options.generateDepthTexture;
- textureCount = options.textureCount || 1;
- if (options.types) {
- types = options.types;
- }
- if (options.samplingModes) {
- samplingModes = options.samplingModes;
- }
- }
- var gl = this._gl;
- // Create the framebuffer
- var framebuffer = gl.createFramebuffer();
- this.bindUnboundFramebuffer(framebuffer);
- var width = size.width || size;
- var height = size.height || size;
- var textures = [];
- var attachments = [];
- var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
- for (var i = 0; i < textureCount; i++) {
- var samplingMode = samplingModes[i] || defaultSamplingMode;
- var type = types[i] || defaultType;
- if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
- // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
- samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
- }
- else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
- // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
- samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
- }
- 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");
- }
- var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
- var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
- textures.push(texture);
- attachments.push(attachment);
- gl.activeTexture(gl["TEXTURE" + i]);
- gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
- 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, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
- gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
- if (generateMipMaps) {
- this._gl.generateMipmap(this._gl.TEXTURE_2D);
- }
- // Unbind
- this._bindTextureDirectly(gl.TEXTURE_2D, null);
- texture._framebuffer = framebuffer;
- texture._depthStencilBuffer = depthStencilBuffer;
- texture.baseWidth = width;
- texture.baseHeight = height;
- texture.width = width;
- texture.height = height;
- texture.isReady = true;
- texture.samples = 1;
- texture.generateMipMaps = generateMipMaps;
- texture.samplingMode = samplingMode;
- texture.type = type;
- texture._generateDepthBuffer = generateDepthBuffer;
- texture._generateStencilBuffer = generateStencilBuffer;
- texture._attachments = attachments;
- this._internalTexturesCache.push(texture);
- }
- if (generateDepthTexture && this._caps.depthTextureExtension) {
- // Depth texture
- var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
- gl.activeTexture(gl.TEXTURE0);
- gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
- 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, this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
- gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
- depthTexture._framebuffer = framebuffer;
- depthTexture.baseWidth = width;
- depthTexture.baseHeight = height;
- depthTexture.width = width;
- depthTexture.height = height;
- depthTexture.isReady = true;
- depthTexture.samples = 1;
- depthTexture.generateMipMaps = generateMipMaps;
- depthTexture.samplingMode = gl.NEAREST;
- depthTexture._generateDepthBuffer = generateDepthBuffer;
- depthTexture._generateStencilBuffer = generateStencilBuffer;
- textures.push(depthTexture);
- this._internalTexturesCache.push(depthTexture);
- }
- gl.drawBuffers(attachments);
- gl.bindRenderbuffer(gl.RENDERBUFFER, null);
- this.bindUnboundFramebuffer(null);
- this.resetTextureCache();
- return textures;
- };
- Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
- if (samples === void 0) { samples = 1; }
- var depthStencilBuffer = null;
- var gl = this._gl;
- // Create the depth/stencil buffer
- if (generateStencilBuffer) {
- depthStencilBuffer = gl.createRenderbuffer();
- gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
- if (samples > 1) {
- gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
- }
- else {
- gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
- }
- gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
- }
- else if (generateDepthBuffer) {
- depthStencilBuffer = gl.createRenderbuffer();
- gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
- if (samples > 1) {
- gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
- }
- else {
- gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
- }
- gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
- }
- return depthStencilBuffer;
- };
- Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
- if (this.webGLVersion < 2 || !texture) {
- return 1;
- }
- if (texture.samples === samples) {
- return samples;
- }
- var gl = this._gl;
- samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
- // Dispose previous render buffers
- if (texture._depthStencilBuffer) {
- gl.deleteRenderbuffer(texture._depthStencilBuffer);
- texture._depthStencilBuffer = null;
- }
- if (texture._MSAAFramebuffer) {
- gl.deleteFramebuffer(texture._MSAAFramebuffer);
- texture._MSAAFramebuffer = null;
- }
- if (texture._MSAARenderBuffer) {
- gl.deleteRenderbuffer(texture._MSAARenderBuffer);
- texture._MSAARenderBuffer = null;
- }
- if (samples > 1) {
- var framebuffer = gl.createFramebuffer();
- if (!framebuffer) {
- throw new Error("Unable to create multi sampled framebuffer");
- }
- texture._MSAAFramebuffer = framebuffer;
- this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
- var colorRenderbuffer = gl.createRenderbuffer();
- if (!colorRenderbuffer) {
- throw new Error("Unable to create multi sampled framebuffer");
- }
- gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
- gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
- gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
- texture._MSAARenderBuffer = colorRenderbuffer;
- }
- else {
- this.bindUnboundFramebuffer(texture._framebuffer);
- }
- texture.samples = samples;
- texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
- gl.bindRenderbuffer(gl.RENDERBUFFER, null);
- this.bindUnboundFramebuffer(null);
- return samples;
- };
- Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
- if (this.webGLVersion < 2 || !textures || textures.length == 0) {
- return 1;
- }
- if (textures[0].samples === samples) {
- return samples;
- }
- var gl = this._gl;
- samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
- // Dispose previous render buffers
- if (textures[0]._depthStencilBuffer) {
- gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
- textures[0]._depthStencilBuffer = null;
- }
- if (textures[0]._MSAAFramebuffer) {
- gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
- textures[0]._MSAAFramebuffer = null;
- }
- for (var i = 0; i < textures.length; i++) {
- if (textures[i]._MSAARenderBuffer) {
- gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
- textures[i]._MSAARenderBuffer = null;
- }
- }
- if (samples > 1) {
- var framebuffer = gl.createFramebuffer();
- if (!framebuffer) {
- throw new Error("Unable to create multi sampled framebuffer");
- }
- this.bindUnboundFramebuffer(framebuffer);
- var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
- var attachments = [];
- for (var i = 0; i < textures.length; i++) {
- var texture = textures[i];
- var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
- var colorRenderbuffer = gl.createRenderbuffer();
- if (!colorRenderbuffer) {
- throw new Error("Unable to create multi sampled framebuffer");
- }
- gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
- gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
- gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
- texture._MSAAFramebuffer = framebuffer;
- texture._MSAARenderBuffer = colorRenderbuffer;
- texture.samples = samples;
- texture._depthStencilBuffer = depthStencilBuffer;
- gl.bindRenderbuffer(gl.RENDERBUFFER, null);
- attachments.push(attachment);
- }
- gl.drawBuffers(attachments);
- }
- else {
- this.bindUnboundFramebuffer(textures[0]._framebuffer);
- }
- this.bindUnboundFramebuffer(null);
- return samples;
- };
- Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
- this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
- };
- Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
- this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
- };
- Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
- var gl = this._gl;
- var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
- var generateMipMaps = true;
- var generateDepthBuffer = true;
- var generateStencilBuffer = false;
- var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
- if (options !== undefined) {
- generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
- generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
- generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
- if (options.samplingMode !== undefined) {
- samplingMode = options.samplingMode;
- }
- }
- texture.isCube = true;
- texture.generateMipMaps = generateMipMaps;
- texture.samples = 1;
- texture.samplingMode = samplingMode;
- var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
- this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
- 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 framebuffer
- var framebuffer = gl.createFramebuffer();
- this.bindUnboundFramebuffer(framebuffer);
- texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
- // Mipmaps
- if (texture.generateMipMaps) {
- gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
- }
- // Unbind
- this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
- gl.bindRenderbuffer(gl.RENDERBUFFER, null);
- this.bindUnboundFramebuffer(null);
- texture._framebuffer = framebuffer;
- texture.width = size;
- texture.height = size;
- texture.isReady = true;
- //this.resetTextureCache();
- this._internalTexturesCache.push(texture);
- return texture;
- };
- Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
- var _this = this;
- if (onLoad === void 0) { onLoad = null; }
- if (onError === void 0) { onError = null; }
- if (forcedExtension === void 0) { forcedExtension = null; }
- var callback = function (loadData) {
- if (!loadData) {
- if (onLoad) {
- onLoad(null);
- }
- return;
- }
- var texture = loadData.texture;
- texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
- texture._lodGenerationScale = scale;
- texture._lodGenerationOffset = offset;
- if (_this._caps.textureLOD) {
- // Do not add extra process if texture lod is supported.
- if (onLoad) {
- onLoad(texture);
- }
- return;
- }
- var mipSlices = 3;
- var gl = _this._gl;
- var width = loadData.width;
- if (!width) {
- return;
- }
- var textures = [];
- for (var i = 0; i < mipSlices; i++) {
- //compute LOD from even spacing in smoothness (matching shader calculation)
- var smoothness = i / (mipSlices - 1);
- var roughness = 1 - smoothness;
- var minLODIndex = offset; // roughness = 0
- var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
- var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
- var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
- var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
- glTextureFromLod.isCube = true;
- _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, 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);
- if (loadData.isDDS) {
- var info = loadData.info;
- var data = loadData.data;
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
- BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
- }
- else {
- BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
- }
- _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
- // Wrap in a base texture for easy binding.
- var lodTexture = new BABYLON.BaseTexture(scene);
- lodTexture.isCube = true;
- lodTexture._texture = glTextureFromLod;
- glTextureFromLod.isReady = true;
- textures.push(lodTexture);
- }
- texture._lodTextureHigh = textures[2];
- texture._lodTextureMid = textures[1];
- texture._lodTextureLow = textures[0];
- if (onLoad) {
- onLoad(texture);
- }
- };
- return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
- };
- Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
- var _this = this;
- if (onLoad === void 0) { onLoad = null; }
- if (onError === void 0) { onError = null; }
- if (forcedExtension === void 0) { forcedExtension = null; }
- var gl = this._gl;
- var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
- texture.isCube = true;
- texture.url = rootUrl;
- texture.generateMipMaps = !noMipmap;
- if (!this._doNotHandleContextLost) {
- texture._extension = forcedExtension;
- texture._files = files;
- }
- var isKTX = false;
- var isDDS = false;
- var lastDot = rootUrl.lastIndexOf('.');
- var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
- if (this._textureFormatInUse) {
- extension = this._textureFormatInUse;
- rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
- isKTX = true;
- }
- else {
- isDDS = (extension === ".dds");
- }
- var onerror = function (request, exception) {
- if (onError && request) {
- onError(request.status + " " + request.statusText, exception);
- }
- };
- if (isKTX) {
- this._loadFile(rootUrl, function (data) {
- var ktx = new BABYLON.KhronosTextureContainer(data, 6);
- var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
- _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
- ktx.uploadLevels(_this._gl, !noMipmap);
- _this.setCubeMapTextureParams(gl, loadMipmap);
- texture.width = ktx.pixelWidth;
- texture.height = ktx.pixelHeight;
- texture.isReady = true;
- }, undefined, undefined, true, onerror);
- }
- else if (isDDS) {
- if (files && files.length === 6) {
- this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
- var info;
- var loadMipmap = false;
- var width = 0;
- for (var index = 0; index < imgs.length; index++) {
- var data = imgs[index];
- info = BABYLON.DDSTools.GetDDSInfo(data);
- loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
- _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
- BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
- if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
- gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
- }
- texture.width = info.width;
- texture.height = info.height;
- texture.type = info.textureType;
- width = info.width;
- }
- _this.setCubeMapTextureParams(gl, loadMipmap);
- texture.isReady = true;
- if (onLoad) {
- onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
- }
- }, files, onError);
- }
- else {
- this._loadFile(rootUrl, function (data) {
- var info = BABYLON.DDSTools.GetDDSInfo(data);
- var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
- _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
- BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
- if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
- gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
- }
- _this.setCubeMapTextureParams(gl, loadMipmap);
- texture.width = info.width;
- texture.height = info.height;
- texture.isReady = true;
- texture.type = info.textureType;
- if (onLoad) {
- onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
- }
- }, undefined, undefined, true, onerror);
- }
- }
- else {
- if (!files) {
- throw new Error("Cannot load cubemap because files were not defined");
- }
- cascadeLoadImgs(rootUrl, scene, function (imgs) {
- var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
- var height = width;
- _this._prepareWorkingCanvas();
- if (!_this._workingCanvas || !_this._workingContext) {
- return;
- }
- _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
- ];
- _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
- var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
- 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, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
- }
- if (!noMipmap) {
- gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
- }
- _this.setCubeMapTextureParams(gl, !noMipmap);
- texture.width = width;
- texture.height = height;
- texture.isReady = true;
- if (format) {
- texture.format = format;
- }
- texture.onLoadedObservable.notifyObservers(texture);
- texture.onLoadedObservable.clear();
- if (onLoad) {
- onLoad();
- }
- }, files, onError);
- }
- this._internalTexturesCache.push(texture);
- return texture;
- };
- Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
- 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);
- this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
- // this.resetTextureCache();
- };
- Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
- if (compression === void 0) { compression = null; }
- if (level === void 0) { level = 0; }
- texture._bufferViewArray = data;
- texture.format = format;
- texture.type = type;
- texture.invertY = invertY;
- texture._compression = compression;
- var gl = this._gl;
- var textureType = this._getWebGLTextureType(type);
- var internalFormat = this._getInternalFormat(format);
- var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
- var needConversion = false;
- if (internalFormat === gl.RGB) {
- internalFormat = gl.RGBA;
- needConversion = true;
- }
- this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
- if (texture.width % 4 !== 0) {
- gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
- }
- // Data are known to be in +X +Y +Z -X -Y -Z
- for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
- var faceData = data[faceIndex];
- if (compression) {
- gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
- }
- else {
- if (needConversion) {
- faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
- }
- gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
- }
- }
- var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
- if (isPot && texture.generateMipMaps && level === 0) {
- this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
- }
- this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
- // this.resetTextureCache();
- texture.isReady = true;
- };
- Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
- if (compression === void 0) { compression = null; }
- var gl = this._gl;
- var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
- texture.isCube = true;
- texture.generateMipMaps = generateMipMaps;
- texture.format = format;
- texture.type = type;
- if (!this._doNotHandleContextLost) {
- texture._bufferViewArray = data;
- }
- var textureType = this._getWebGLTextureType(type);
- var internalFormat = this._getInternalFormat(format);
- if (internalFormat === gl.RGB) {
- internalFormat = gl.RGBA;
- }
- var width = size;
- var height = width;
- texture.width = width;
- texture.height = height;
- // Double check on POT to generate Mips.
- var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
- if (!isPot) {
- generateMipMaps = false;
- }
- // Upload data if needed. The texture won't be ready until then.
- if (data) {
- this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
- }
- this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
- // Filters
- if (data && generateMipMaps) {
- this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
- }
- 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 if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
- 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 {
- var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
- 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);
- this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
- return texture;
- };
- Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
- var _this = this;
- if (onLoad === void 0) { onLoad = null; }
- if (onError === void 0) { onError = null; }
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
- if (invertY === void 0) { invertY = false; }
- var gl = this._gl;
- var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
- scene._addPendingData(texture);
- texture.url = url;
- this._internalTexturesCache.push(texture);
- var onerror = function (request, exception) {
- scene._removePendingData(texture);
- if (onError && request) {
- onError(request.status + " " + request.statusText, exception);
- }
- };
- var internalCallback = function (data) {
- var width = texture.width;
- var faceDataArrays = callback(data);
- if (!faceDataArrays) {
- return;
- }
- if (mipmmapGenerator) {
- var textureType = _this._getWebGLTextureType(type);
- var internalFormat = _this._getInternalFormat(format);
- var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
- var needConversion = false;
- if (internalFormat === gl.RGB) {
- internalFormat = gl.RGBA;
- needConversion = true;
- }
- _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
- var mipData = mipmmapGenerator(faceDataArrays);
- for (var level = 0; level < mipData.length; level++) {
- var mipSize = width >> level;
- for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
- var mipFaceData = mipData[level][faceIndex];
- if (needConversion) {
- mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
- }
- gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
- }
- }
- _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
- }
- else {
- texture.generateMipMaps = !noMipmap;
- _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
- }
- texture.isReady = true;
- // this.resetTextureCache();
- scene._removePendingData(texture);
- if (onLoad) {
- onLoad();
- }
- };
- this._loadFile(url, function (data) {
- internalCallback(data);
- }, undefined, scene.database, true, onerror);
- return texture;
- };
- ;
- Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
- if (compression === void 0) { compression = null; }
- var internalFormat = this._getInternalFormat(format);
- this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
- this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
- if (!this._doNotHandleContextLost) {
- texture._bufferView = data;
- texture.format = format;
- texture.invertY = invertY;
- texture._compression = compression;
- }
- if (texture.width % 4 !== 0) {
- this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
- }
- if (compression && data) {
- this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
- }
- else {
- this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
- }
- if (texture.generateMipMaps) {
- this._gl.generateMipmap(this._gl.TEXTURE_3D);
- }
- this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
- // this.resetTextureCache();
- texture.isReady = true;
- };
- Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
- if (compression === void 0) { compression = null; }
- var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
- texture.baseWidth = width;
- texture.baseHeight = height;
- texture.baseDepth = depth;
- texture.width = width;
- texture.height = height;
- texture.depth = depth;
- texture.format = format;
- texture.generateMipMaps = generateMipMaps;
- texture.samplingMode = samplingMode;
- texture.is3D = true;
- if (!this._doNotHandleContextLost) {
- texture._bufferView = data;
- }
- this.updateRawTexture3D(texture, data, format, invertY, compression);
- this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
- // Filters
- var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
- this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
- this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
- if (generateMipMaps) {
- this._gl.generateMipmap(this._gl.TEXTURE_3D);
- }
- this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
- this._internalTexturesCache.push(texture);
- return texture;
- };
- Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
- var gl = this._gl;
- if (!gl) {
- return;
- }
- 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);
- }
- this._bindTextureDirectly(gl.TEXTURE_2D, null);
- // this.resetTextureCache();
- if (scene) {
- scene._removePendingData(texture);
- }
- texture.onLoadedObservable.notifyObservers(texture);
- texture.onLoadedObservable.clear();
- };
- Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
- var _this = this;
- if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
- var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
- var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
- var gl = this._gl;
- if (!gl) {
- return;
- }
- if (!texture._webGLTexture) {
- // this.resetTextureCache();
- if (scene) {
- scene._removePendingData(texture);
- }
- return;
- }
- this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
- 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;
- if (processFunction(potWidth, potHeight, function () {
- _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
- })) {
- // Returning as texture needs extra async steps
- return;
- }
- this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
- };
- Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
- // Create new RGBA data container.
- var rgbaData;
- if (textureType === Engine.TEXTURETYPE_FLOAT) {
- rgbaData = new Float32Array(width * height * 4);
- }
- else {
- rgbaData = new Uint32Array(width * height * 4);
- }
- // Convert each pixel.
- for (var x = 0; x < width; x++) {
- for (var y = 0; y < height; y++) {
- var index = (y * width + x) * 3;
- var newIndex = (y * width + x) * 4;
- // Map Old Value to new value.
- rgbaData[newIndex + 0] = rgbData[index + 0];
- rgbaData[newIndex + 1] = rgbData[index + 1];
- rgbaData[newIndex + 2] = rgbData[index + 2];
- // Add fully opaque alpha channel.
- rgbaData[newIndex + 3] = 1;
- }
- }
- return rgbaData;
- };
- Engine.prototype._releaseFramebufferObjects = function (texture) {
- var gl = this._gl;
- if (texture._framebuffer) {
- gl.deleteFramebuffer(texture._framebuffer);
- texture._framebuffer = null;
- }
- if (texture._depthStencilBuffer) {
- gl.deleteRenderbuffer(texture._depthStencilBuffer);
- texture._depthStencilBuffer = null;
- }
- if (texture._MSAAFramebuffer) {
- gl.deleteFramebuffer(texture._MSAAFramebuffer);
- texture._MSAAFramebuffer = null;
- }
- if (texture._MSAARenderBuffer) {
- gl.deleteRenderbuffer(texture._MSAARenderBuffer);
- texture._MSAARenderBuffer = null;
- }
- };
- Engine.prototype._releaseTexture = function (texture) {
- var gl = this._gl;
- this._releaseFramebufferObjects(texture);
- gl.deleteTexture(texture._webGLTexture);
- // Unbind channels
- this.unbindAllTextures();
- var index = this._internalTexturesCache.indexOf(texture);
- if (index !== -1) {
- this._internalTexturesCache.splice(index, 1);
- }
- // Integrated fixed lod samplers.
- if (texture._lodTextureHigh) {
- texture._lodTextureHigh.dispose();
- }
- if (texture._lodTextureMid) {
- texture._lodTextureMid.dispose();
- }
- if (texture._lodTextureLow) {
- texture._lodTextureLow.dispose();
- }
- };
- Engine.prototype.setProgram = function (program) {
- if (this._currentProgram !== program) {
- this._gl.useProgram(program);
- this._currentProgram = program;
- }
- };
- Engine.prototype.bindSamplers = function (effect) {
- this.setProgram(effect.getProgram());
- var samplers = effect.getSamplers();
- for (var index = 0; index < samplers.length; index++) {
- var uniform = effect.getUniform(samplers[index]);
- if (uniform) {
- this._boundUniforms[index] = uniform;
- }
- }
- this._currentEffect = null;
- };
- Engine.prototype._activateTextureChannel = function (channel) {
- if (this._activeChannel !== channel && channel > -1) {
- this._gl.activeTexture(this._gl.TEXTURE0 + channel);
- this._activeChannel = channel;
- }
- };
- Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
- var index = this._boundTexturesStack.indexOf(internalTexture);
- if (index > -1 && index !== this._boundTexturesStack.length - 1) {
- this._boundTexturesStack.splice(index, 1);
- this._boundTexturesStack.push(internalTexture);
- }
- };
- Engine.prototype._removeDesignatedSlot = function (internalTexture) {
- var currentSlot = internalTexture._designatedSlot;
- internalTexture._designatedSlot = -1;
- var index = this._boundTexturesStack.indexOf(internalTexture);
- if (index > -1) {
- this._boundTexturesStack.splice(index, 1);
- if (currentSlot > -1) {
- this._boundTexturesCache[currentSlot] = null;
- this._nextFreeTextureSlots.push(currentSlot);
- }
- }
- return currentSlot;
- };
- Engine.prototype._bindTextureDirectly = function (target, texture, doNotBindUniformToTextureChannel) {
- if (doNotBindUniformToTextureChannel === void 0) { doNotBindUniformToTextureChannel = false; }
- var currentTextureBound = this._boundTexturesCache[this._activeChannel];
- var isTextureForRendering = texture && texture._initialSlot > -1;
- if (currentTextureBound !== texture) {
- if (currentTextureBound) {
- this._removeDesignatedSlot(currentTextureBound);
- }
- this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
- if (this._activeChannel >= 0) {
- this._boundTexturesCache[this._activeChannel] = texture;
- if (isTextureForRendering) {
- var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
- if (slotIndex > -1) {
- this._nextFreeTextureSlots.splice(slotIndex, 1);
- }
- this._boundTexturesStack.push(texture);
- }
- }
- }
- if (isTextureForRendering && this._activeChannel > -1) {
- texture._designatedSlot = this._activeChannel;
- if (!doNotBindUniformToTextureChannel) {
- this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
- }
- }
- };
- Engine.prototype._bindTexture = function (channel, texture) {
- if (channel < 0) {
- return;
- }
- if (texture) {
- channel = this._getCorrectTextureChannel(channel, texture);
- }
- this._activateTextureChannel(channel);
- this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
- };
- Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
- this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
- };
- Engine.prototype.unbindAllTextures = function () {
- for (var channel = 0; channel < this._caps.maxCombinedTexturesImageUnits; channel++) {
- this._activateTextureChannel(channel);
- this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
- this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
- if (this.webGLVersion > 1) {
- this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
- }
- }
- };
- Engine.prototype.setTexture = function (channel, uniform, texture) {
- if (channel < 0) {
- return;
- }
- if (uniform) {
- this._boundUniforms[channel] = uniform;
- }
- this._setTexture(channel, texture);
- };
- Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
- if (!internalTexture) {
- return -1;
- }
- internalTexture._initialSlot = channel;
- if (channel !== internalTexture._designatedSlot) {
- if (internalTexture._designatedSlot > -1) {
- return internalTexture._designatedSlot;
- }
- else {
- // No slot for this texture, let's pick a new one (if we find a free slot)
- if (this._nextFreeTextureSlots.length) {
- return this._nextFreeTextureSlots[0];
- }
- // We need to recycle the oldest bound texture, sorry.
- this._textureCollisions.addCount(1, false);
- return this._removeDesignatedSlot(this._boundTexturesStack[0]);
- }
- }
- return channel;
- };
- Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
- var uniform = this._boundUniforms[sourceSlot];
- this._gl.uniform1i(uniform, destination);
- };
- Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
- if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
- // Not ready?
- if (!texture) {
- if (this._boundTexturesCache[channel] != null) {
- this._activateTextureChannel(channel);
- this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
- this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
- if (this.webGLVersion > 1) {
- this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
- }
- }
- return false;
- }
- // Video
- var alreadyActivated = false;
- if (texture.video) {
- this._activateTextureChannel(channel);
- alreadyActivated = true;
- texture.update();
- }
- else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
- texture.delayLoad();
- return false;
- }
- var internalTexture;
- if (texture.isReady()) {
- internalTexture = texture.getInternalTexture();
- }
- else if (texture.isCube) {
- internalTexture = this.emptyCubeTexture;
- }
- else if (texture.is3D) {
- internalTexture = this.emptyTexture3D;
- }
- else {
- internalTexture = this.emptyTexture;
- }
- if (!isPartOfTextureArray) {
- channel = this._getCorrectTextureChannel(channel, internalTexture);
- }
- if (this._boundTexturesCache[channel] === internalTexture) {
- this._moveBoundTextureOnTop(internalTexture);
- if (!isPartOfTextureArray) {
- this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
- }
- return false;
- }
- if (!alreadyActivated) {
- this._activateTextureChannel(channel);
- }
- if (internalTexture && internalTexture.is3D) {
- this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
- if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
- internalTexture._cachedWrapU = texture.wrapU;
- switch (texture.wrapU) {
- case BABYLON.Texture.WRAP_ADDRESSMODE:
- this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
- break;
- case BABYLON.Texture.CLAMP_ADDRESSMODE:
- this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
- break;
- case BABYLON.Texture.MIRROR_ADDRESSMODE:
- this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
- break;
- }
- }
- if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
- internalTexture._cachedWrapV = texture.wrapV;
- switch (texture.wrapV) {
- case BABYLON.Texture.WRAP_ADDRESSMODE:
- this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
- break;
- case BABYLON.Texture.CLAMP_ADDRESSMODE:
- this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
- break;
- case BABYLON.Texture.MIRROR_ADDRESSMODE:
- this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
- break;
- }
- }
- if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
- internalTexture._cachedWrapR = texture.wrapR;
- switch (texture.wrapV) {
- case BABYLON.Texture.WRAP_ADDRESSMODE:
- this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
- break;
- case BABYLON.Texture.CLAMP_ADDRESSMODE:
- this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
- break;
- case BABYLON.Texture.MIRROR_ADDRESSMODE:
- this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
- break;
- }
- }
- this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
- }
- else if (internalTexture && internalTexture.isCube) {
- this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
- 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._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
- if (internalTexture && 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 && 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);
- }
- return true;
- };
- Engine.prototype.setTextureArray = function (channel, uniform, textures) {
- if (channel < 0 || !uniform) {
- return;
- }
- if (!this._textureUnits || this._textureUnits.length !== textures.length) {
- this._textureUnits = new Int32Array(textures.length);
- }
- for (var i = 0; i < textures.length; i++) {
- this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
- }
- this._gl.uniform1iv(uniform, this._textureUnits);
- for (var index = 0; index < textures.length; index++) {
- this._setTexture(this._textureUnits[index], textures[index], true);
- }
- };
- Engine.prototype._setAnisotropicLevel = function (key, texture) {
- var internalTexture = texture.getInternalTexture();
- if (!internalTexture) {
- return;
- }
- var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
- var value = texture.anisotropicFilteringLevel;
- if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
- && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
- && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
- value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
- }
- if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
- this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
- internalTexture._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;
- };
- /**
- * Add an externaly attached data from its key.
- * This method call will fail and return false, if such key already exists.
- * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
- * @param key the unique key that identifies the data
- * @param data the data object to associate to the key for this Engine instance
- * @return true if no such key were already present and the data was added successfully, false otherwise
- */
- Engine.prototype.addExternalData = function (key, data) {
- if (!this._externalData) {
- this._externalData = new BABYLON.StringDictionary();
- }
- return this._externalData.add(key, data);
- };
- /**
- * Get an externaly attached data from its key
- * @param key the unique key that identifies the data
- * @return the associated data, if present (can be null), or undefined if not present
- */
- Engine.prototype.getExternalData = function (key) {
- if (!this._externalData) {
- this._externalData = new BABYLON.StringDictionary();
- }
- return this._externalData.get(key);
- };
- /**
- * Get an externaly attached data from its key, create it using a factory if it's not already present
- * @param key the unique key that identifies the data
- * @param factory the factory that will be called to create the instance if and only if it doesn't exists
- * @return the associated data, can be null if the factory returned null.
- */
- Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
- if (!this._externalData) {
- this._externalData = new BABYLON.StringDictionary();
- }
- return this._externalData.getOrAddWithFactory(key, factory);
- };
- /**
- * Remove an externaly attached data from the Engine instance
- * @param key the unique key that identifies the data
- * @return true if the data was successfully removed, false if it doesn't exist
- */
- Engine.prototype.removeExternalData = function (key) {
- if (!this._externalData) {
- this._externalData = new BABYLON.StringDictionary();
- }
- return this._externalData.remove(key);
- };
- Engine.prototype.unbindAllAttributes = function () {
- if (this._mustWipeVertexAttributes) {
- this._mustWipeVertexAttributes = false;
- for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
- this._gl.disableVertexAttribArray(i);
- this._vertexAttribArraysEnabled[i] = false;
- this._currentBufferPointers[i].active = false;
- }
- return;
- }
- for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
- if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
- continue;
- }
- this._gl.disableVertexAttribArray(i);
- this._vertexAttribArraysEnabled[i] = false;
- this._currentBufferPointers[i].active = false;
- }
- };
- Engine.prototype.releaseEffects = function () {
- for (var name in this._compiledEffects) {
- this._deleteProgram(this._compiledEffects[name]._program);
- }
- this._compiledEffects = {};
- };
- // Dispose
- Engine.prototype.dispose = function () {
- this.hideLoadingUI();
- this.stopRenderLoop();
- // Release postProcesses
- while (this.postProcesses.length) {
- this.postProcesses[0].dispose();
- }
- // Empty texture
- if (this._emptyTexture) {
- this._releaseTexture(this._emptyTexture);
- this._emptyTexture = null;
- }
- if (this._emptyCubeTexture) {
- this._releaseTexture(this._emptyCubeTexture);
- this._emptyCubeTexture = null;
- }
- // Rescale PP
- if (this._rescalePostProcess) {
- this._rescalePostProcess.dispose();
- }
- // Release scenes
- while (this.scenes.length) {
- this.scenes[0].dispose();
- }
- // Release audio engine
- if (Engine.audioEngine) {
- Engine.audioEngine.dispose();
- }
- // Release effects
- this.releaseEffects();
- // Unbind
- this.unbindAllAttributes();
- if (this._dummyFramebuffer) {
- this._gl.deleteFramebuffer(this._dummyFramebuffer);
- }
- //WebVR
- this.disableVR();
- // Events
- if (BABYLON.Tools.IsWindowObjectExist()) {
- window.removeEventListener("blur", this._onBlur);
- window.removeEventListener("focus", this._onFocus);
- window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
- window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
- if (this._renderingCanvas) {
- this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
- this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
- this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
- if (!this._doNotHandleContextLost) {
- this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
- this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
- }
- }
- 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);
- if (this._onVrDisplayConnect) {
- window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
- if (this._onVrDisplayDisconnect) {
- window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
- }
- if (this._onVrDisplayPresentChange) {
- window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
- }
- this._onVrDisplayConnect = null;
- this._onVrDisplayDisconnect = null;
- }
- }
- // Remove from Instances
- var index = Engine.Instances.indexOf(this);
- if (index >= 0) {
- Engine.Instances.splice(index, 1);
- }
- this._workingCanvas = null;
- this._workingContext = null;
- this._currentBufferPointers = [];
- this._renderingCanvas = null;
- this._currentProgram = null;
- this.onResizeObservable.clear();
- this.onCanvasBlurObservable.clear();
- this.onCanvasFocusObservable.clear();
- this.onCanvasPointerOutObservable.clear();
- this.onBeginFrameObservable.clear();
- this.onEndFrameObservable.clear();
- BABYLON.Effect.ResetCache();
- // Abort active requests
- for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
- var request = _a[_i];
- request.abort();
- }
- };
- // Loading screen
- Engine.prototype.displayLoadingUI = function () {
- if (!BABYLON.Tools.IsWindowObjectExist()) {
- return;
- }
- var loadingScreen = this.loadingScreen;
- if (loadingScreen) {
- loadingScreen.displayLoadingUI();
- }
- };
- Engine.prototype.hideLoadingUI = function () {
- if (!BABYLON.Tools.IsWindowObjectExist()) {
- return;
- }
- var loadingScreen = this.loadingScreen;
- if (loadingScreen) {
- loadingScreen.hideLoadingUI();
- }
- };
- Object.defineProperty(Engine.prototype, "loadingScreen", {
- get: function () {
- if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
- this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
- 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
- });
- Engine.prototype.attachContextLostEvent = function (callback) {
- if (this._renderingCanvas) {
- this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
- }
- };
- Engine.prototype.attachContextRestoredEvent = function (callback) {
- if (this._renderingCanvas) {
- this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
- }
- };
- Engine.prototype.getVertexShaderSource = function (program) {
- var shaders = this._gl.getAttachedShaders(program);
- if (!shaders) {
- return null;
- }
- return this._gl.getShaderSource(shaders[0]);
- };
- Engine.prototype.getFragmentShaderSource = function (program) {
- var shaders = this._gl.getAttachedShaders(program);
- if (!shaders) {
- return null;
- }
- return this._gl.getShaderSource(shaders[1]);
- };
- Engine.prototype.getError = function () {
- return this._gl.getError();
- };
- // FPS
- Engine.prototype.getFps = function () {
- return this._fps;
- };
- Engine.prototype.getDeltaTime = function () {
- return this._deltaTime;
- };
- Engine.prototype._measureFps = function () {
- this._performanceMonitor.sampleFrame();
- this._fps = this._performanceMonitor.averageFPS;
- this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
- };
- Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
- if (faceIndex === void 0) { faceIndex = -1; }
- var gl = this._gl;
- if (!this._dummyFramebuffer) {
- var dummy = gl.createFramebuffer();
- if (!dummy) {
- throw new Error("Unable to create dummy framebuffer");
- }
- this._dummyFramebuffer = dummy;
- }
- gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
- if (faceIndex > -1) {
- gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
- }
- else {
- gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
- }
- var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
- var buffer;
- switch (readType) {
- case gl.UNSIGNED_BYTE:
- buffer = new Uint8Array(4 * width * height);
- readType = gl.UNSIGNED_BYTE;
- break;
- default:
- buffer = new Float32Array(4 * width * height);
- readType = gl.FLOAT;
- break;
- }
- gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
- gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
- return buffer;
- };
- Engine.prototype._canRenderToFloatFramebuffer = function () {
- if (this._webGLVersion > 1) {
- return this._caps.colorBufferFloat;
- }
- return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
- };
- Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
- if (this._webGLVersion > 1) {
- return this._caps.colorBufferFloat;
- }
- return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
- };
- // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
- Engine.prototype._canRenderToFramebuffer = function (type) {
- var gl = this._gl;
- //clear existing errors
- while (gl.getError() !== gl.NO_ERROR) { }
- var successful = true;
- var texture = gl.createTexture();
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
- var fb = gl.createFramebuffer();
- gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
- gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
- var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
- successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
- successful = successful && (gl.getError() === gl.NO_ERROR);
- //try render by clearing frame buffer's color buffer
- if (successful) {
- gl.clear(gl.COLOR_BUFFER_BIT);
- successful = successful && (gl.getError() === gl.NO_ERROR);
- }
- //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
- if (successful) {
- //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
- gl.bindFramebuffer(gl.FRAMEBUFFER, null);
- var readFormat = gl.RGBA;
- var readType = gl.UNSIGNED_BYTE;
- var buffer = new Uint8Array(4);
- gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
- successful = successful && (gl.getError() === gl.NO_ERROR);
- }
- //clean up
- gl.deleteTexture(texture);
- gl.deleteFramebuffer(fb);
- gl.bindFramebuffer(gl.FRAMEBUFFER, null);
- //clear accumulated errors
- while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
- return successful;
- };
- Engine.prototype._getWebGLTextureType = function (type) {
- if (type === Engine.TEXTURETYPE_FLOAT) {
- return this._gl.FLOAT;
- }
- else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
- // Add Half Float Constant.
- return this._gl.HALF_FLOAT_OES;
- }
- return this._gl.UNSIGNED_BYTE;
- };
- ;
- Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
- if (this._webGLVersion === 1) {
- return this._gl.RGBA;
- }
- if (type === Engine.TEXTURETYPE_FLOAT) {
- return this._gl.RGBA32F;
- }
- else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
- return this._gl.RGBA16F;
- }
- return this._gl.RGBA;
- };
- ;
- Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
- if (type === Engine.TEXTURETYPE_FLOAT) {
- return this._gl.RGBA32F;
- }
- else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
- return this._gl.RGBA16F;
- }
- return this._gl.RGBA8;
- };
- ;
- Engine.prototype.createQuery = function () {
- return this._gl.createQuery();
- };
- Engine.prototype.deleteQuery = function (query) {
- this._gl.deleteQuery(query);
- return this;
- };
- Engine.prototype.isQueryResultAvailable = function (query) {
- return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
- };
- Engine.prototype.getQueryResult = function (query) {
- return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
- };
- Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
- var glAlgorithm = this.getGlAlgorithmType(algorithmType);
- this._gl.beginQuery(glAlgorithm, query);
- return this;
- };
- Engine.prototype.endOcclusionQuery = function (algorithmType) {
- var glAlgorithm = this.getGlAlgorithmType(algorithmType);
- this._gl.endQuery(glAlgorithm);
- return this;
- };
- /* Time queries */
- Engine.prototype._createTimeQuery = function () {
- var timerQuery = this._caps.timerQuery;
- if (timerQuery.createQueryEXT) {
- return timerQuery.createQueryEXT();
- }
- return this.createQuery();
- };
- Engine.prototype._deleteTimeQuery = function (query) {
- var timerQuery = this._caps.timerQuery;
- if (timerQuery.deleteQueryEXT) {
- timerQuery.deleteQueryEXT(query);
- return;
- }
- this.deleteQuery(query);
- };
- Engine.prototype._getTimeQueryResult = function (query) {
- var timerQuery = this._caps.timerQuery;
- if (timerQuery.getQueryObjectEXT) {
- return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
- }
- return this.getQueryResult(query);
- };
- Engine.prototype._getTimeQueryAvailability = function (query) {
- var timerQuery = this._caps.timerQuery;
- if (timerQuery.getQueryObjectEXT) {
- return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
- }
- return this.isQueryResultAvailable(query);
- };
- Engine.prototype.startTimeQuery = function () {
- var timerQuery = this._caps.timerQuery;
- if (!timerQuery) {
- return null;
- }
- var token = new BABYLON._TimeToken();
- this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
- if (this._caps.canUseTimestampForTimerQuery) {
- token._startTimeQuery = this._createTimeQuery();
- timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
- }
- else {
- if (this._currentNonTimestampToken) {
- return this._currentNonTimestampToken;
- }
- token._timeElapsedQuery = this._createTimeQuery();
- if (timerQuery.beginQueryEXT) {
- timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
- }
- else {
- this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
- }
- this._currentNonTimestampToken = token;
- }
- return token;
- };
- Engine.prototype.endTimeQuery = function (token) {
- var timerQuery = this._caps.timerQuery;
- if (!timerQuery || !token) {
- return -1;
- }
- if (this._caps.canUseTimestampForTimerQuery) {
- if (!token._startTimeQuery) {
- return -1;
- }
- if (!token._endTimeQuery) {
- token._endTimeQuery = this._createTimeQuery();
- timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
- }
- }
- else if (!token._timeElapsedQueryEnded) {
- if (!token._timeElapsedQuery) {
- return -1;
- }
- if (timerQuery.endQueryEXT) {
- timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
- }
- else {
- this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
- }
- token._timeElapsedQueryEnded = true;
- }
- var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
- var available = false;
- if (token._endTimeQuery) {
- available = this._getTimeQueryAvailability(token._endTimeQuery);
- }
- else if (token._timeElapsedQuery) {
- available = this._getTimeQueryAvailability(token._timeElapsedQuery);
- }
- if (available && !disjoint) {
- var result = 0;
- if (this._caps.canUseTimestampForTimerQuery) {
- if (!token._startTimeQuery || !token._endTimeQuery) {
- return -1;
- }
- var timeStart = this._getTimeQueryResult(token._startTimeQuery);
- var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
- result = timeEnd - timeStart;
- this._deleteTimeQuery(token._startTimeQuery);
- this._deleteTimeQuery(token._endTimeQuery);
- token._startTimeQuery = null;
- token._endTimeQuery = null;
- }
- else {
- if (!token._timeElapsedQuery) {
- return -1;
- }
- result = this._getTimeQueryResult(token._timeElapsedQuery);
- this._deleteTimeQuery(token._timeElapsedQuery);
- token._timeElapsedQuery = null;
- token._timeElapsedQueryEnded = false;
- this._currentNonTimestampToken = null;
- }
- return result;
- }
- return -1;
- };
- Engine.prototype.getGlAlgorithmType = function (algorithmType) {
- return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
- };
- // Transform feedback
- Engine.prototype.createTransformFeedback = function () {
- return this._gl.createTransformFeedback();
- };
- Engine.prototype.deleteTransformFeedback = function (value) {
- this._gl.deleteTransformFeedback(value);
- };
- Engine.prototype.bindTransformFeedback = function (value) {
- this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
- };
- Engine.prototype.beginTransformFeedback = function (usePoints) {
- if (usePoints === void 0) { usePoints = true; }
- this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
- };
- Engine.prototype.endTransformFeedback = function () {
- this._gl.endTransformFeedback();
- };
- Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
- this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
- };
- Engine.prototype.bindTransformFeedbackBuffer = function (value) {
- this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
- };
- Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
- var _this = this;
- var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
- this._activeRequests.push(request);
- request.onCompleteObservable.add(function (request) {
- _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
- });
- return request;
- };
- Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
- if (onErrorCallBack === void 0) { onErrorCallBack = null; }
- var onload = function (data) {
- loadedFiles[index] = data;
- loadedFiles._internalCount++;
- if (loadedFiles._internalCount === 6) {
- onfinish(loadedFiles);
- }
- };
- var onerror = function (request, exception) {
- if (onErrorCallBack && request) {
- onErrorCallBack(request.status + " " + request.statusText, exception);
- }
- };
- this._loadFile(url, onload, undefined, undefined, true, onerror);
- };
- Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
- if (onError === void 0) { onError = null; }
- var loadedFiles = [];
- loadedFiles._internalCount = 0;
- for (var index = 0; index < 6; index++) {
- this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
- }
- };
- // Statics
- Engine.isSupported = function () {
- try {
- var tempcanvas = document.createElement("canvas");
- var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
- return gl != null && !!window.WebGLRenderingContext;
- }
- catch (e) {
- return false;
- }
- };
- /** Use this array to turn off some WebGL2 features on known buggy browsers version */
- Engine.ExceptionList = [
- { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
- { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] }
- ];
- Engine.Instances = new Array();
- // 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._ALPHA_PREMULTIPLIED = 7;
- Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
- Engine._ALPHA_INTERPOLATE = 9;
- Engine._ALPHA_SCREENMODE = 10;
- 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;
- Engine._TEXTURETYPE_HALF_FLOAT = 2;
- // Depht or Stencil test Constants.
- Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
- Engine._ALWAYS = 0x0207; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
- Engine._LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
- Engine._EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
- Engine._LEQUAL = 0x0203; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
- Engine._GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
- Engine._GEQUAL = 0x0206; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
- Engine._NOTEQUAL = 0x0205; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
- // Stencil Actions Constants.
- Engine._KEEP = 0x1E00;
- Engine._REPLACE = 0x1E01;
- Engine._INCR = 0x1E02;
- Engine._DECR = 0x1E03;
- Engine._INVERT = 0x150A;
- Engine._INCR_WRAP = 0x8507;
- Engine._DECR_WRAP = 0x8508;
- // Texture rescaling mode
- Engine._SCALEMODE_FLOOR = 1;
- Engine._SCALEMODE_NEAREST = 2;
- Engine._SCALEMODE_CEILING = 3;
- // 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 = {}));
- //# sourceMappingURL=babylon.engine.js.map
- var BABYLON;
- (function (BABYLON) {
- /**
- * Node is the basic class for all scene objects (Mesh, Light Camera).
- */
- var Node = /** @class */ (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) {
- if (scene === void 0) { scene = null; }
- this.state = "";
- this.metadata = null;
- this.doNotSerialize = false;
- this.animations = new Array();
- this._ranges = {};
- this._isEnabled = true;
- this._isReady = true;
- this._currentRenderId = -1;
- this._parentRenderId = -1;
- /**
- * An event triggered when the mesh is disposed.
- * @type {BABYLON.Observable}
- */
- this.onDisposeObservable = new BABYLON.Observable();
- // Behaviors
- this._behaviors = new Array();
- this.name = name;
- this.id = name;
- this._scene = (scene || BABYLON.Engine.LastCreatedScene);
- this.uniqueId = this._scene.getUniqueId();
- this._initCache();
- }
- Object.defineProperty(Node.prototype, "parent", {
- get: function () {
- return this._parentNode;
- },
- set: function (parent) {
- if (this._parentNode === parent) {
- return;
- }
- // Remove self from list of children of parent
- if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
- var index = this._parentNode._children.indexOf(this);
- if (index !== -1) {
- this._parentNode._children.splice(index, 1);
- }
- }
- // Store new parent
- this._parentNode = parent;
- // Add as child to new parent
- if (this._parentNode) {
- if (this._parentNode._children === undefined || this._parentNode._children === null) {
- this._parentNode._children = new Array();
- }
- this._parentNode._children.push(this);
- }
- },
- enumerable: true,
- configurable: true
- });
- Node.prototype.getClassName = function () {
- return "Node";
- };
- Object.defineProperty(Node.prototype, "onDispose", {
- set: function (callback) {
- if (this._onDisposeObserver) {
- this.onDisposeObservable.remove(this._onDisposeObserver);
- }
- this._onDisposeObserver = this.onDisposeObservable.add(callback);
- },
- enumerable: true,
- configurable: true
- });
- Node.prototype.getScene = function () {
- return this._scene;
- };
- Node.prototype.getEngine = function () {
- return this._scene.getEngine();
- };
- Node.prototype.addBehavior = function (behavior) {
- var _this = this;
- var index = this._behaviors.indexOf(behavior);
- if (index !== -1) {
- return this;
- }
- behavior.init();
- if (this._scene.isLoading) {
- // We defer the attach when the scene will be loaded
- var observer = this._scene.onDataLoadedObservable.add(function () {
- behavior.attach(_this);
- setTimeout(function () {
- // Need to use a timeout to avoid removing an observer while iterating the list of observers
- _this._scene.onDataLoadedObservable.remove(observer);
- }, 0);
- });
- }
- else {
- behavior.attach(this);
- }
- this._behaviors.push(behavior);
- return this;
- };
- Node.prototype.removeBehavior = function (behavior) {
- var index = this._behaviors.indexOf(behavior);
- if (index === -1) {
- return this;
- }
- this._behaviors[index].detach();
- this._behaviors.splice(index, 1);
- return this;
- };
- Object.defineProperty(Node.prototype, "behaviors", {
- get: function () {
- return this._behaviors;
- },
- enumerable: true,
- configurable: true
- });
- Node.prototype.getBehaviorByName = function (name) {
- for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
- var behavior = _a[_i];
- if (behavior.name === name) {
- return behavior;
- }
- }
- return null;
- };
- // 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 () {
- if (this.parent) {
- 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, all ancestors will be checked and false will be returned if any are false (not enabled), otherwise will return true.
- * @param {boolean} [checkAncestors=true] - Indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors.
- * @return {boolean} whether this node (and its parent) is enabled.
- * @see setEnabled
- */
- Node.prototype.isEnabled = function (checkAncestors) {
- if (checkAncestors === void 0) { checkAncestors = true; }
- if (checkAncestors === false) {
- return this._isEnabled;
- }
- if (this._isEnabled === false) {
- return false;
- }
- if (this.parent !== undefined && this.parent !== null) {
- return this.parent.isEnabled(checkAncestors);
- }
- 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 = new Array();
- this._getDescendants(results, directDescendantsOnly, predicate);
- return results;
- };
- /**
- * Get all child-meshes of this node.
- */
- Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
- var results = [];
- this._getDescendants(results, directDescendantsOnly, function (node) {
- return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
- });
- return results;
- };
- /**
- * Get all child-transformNodes of this node.
- */
- Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
- var results = [];
- this._getDescendants(results, directDescendantsOnly, function (node) {
- return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
- });
- return results;
- };
- /**
- * Get all direct children of this node.
- */
- Node.prototype.getChildren = function (predicate) {
- return this.getDescendants(true, predicate);
- };
- 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] = null; // 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;
- }
- this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
- };
- Node.prototype.serializeAnimationRanges = function () {
- var serializationRanges = [];
- for (var name in this._ranges) {
- var localRange = this._ranges[name];
- if (!localRange) {
- continue;
- }
- var range = {};
- range.name = name;
- range.from = localRange.from;
- range.to = localRange.to;
- serializationRanges.push(range);
- }
- return serializationRanges;
- };
- // override it in derived class
- Node.prototype.computeWorldMatrix = function (force) {
- return BABYLON.Matrix.Identity();
- };
- Node.prototype.dispose = function () {
- this.parent = null;
- // Callback
- this.onDisposeObservable.notifyObservers(this);
- this.onDisposeObservable.clear();
- // Behaviors
- for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
- var behavior = _a[_i];
- behavior.detach();
- }
- this._behaviors = [];
- };
- 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);
- __decorate([
- BABYLON.serialize()
- ], Node.prototype, "metadata", void 0);
- return Node;
- }());
- BABYLON.Node = Node;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.node.js.map
- var BABYLON;
- (function (BABYLON) {
- var BoundingSphere = /** @class */ (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 = {}));
- //# sourceMappingURL=babylon.boundingSphere.js.map
- var BABYLON;
- (function (BABYLON) {
- var BoundingBox = /** @class */ (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.centerWorld = BABYLON.Vector3.Zero();
- this.extendSizeWorld = 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;
- }
- // Extend
- this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
- this.extendSizeWorld.scaleInPlace(0.5);
- // OBB
- this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
- this.centerWorld.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 = {}));
- //# sourceMappingURL=babylon.boundingBox.js.map
- var BABYLON;
- (function (BABYLON) {
- var computeBoxExtents = function (axis, box) {
- var p = BABYLON.Vector3.Dot(box.centerWorld, 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 = /** @class */ (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);
- };
- /**
- * Recreate the bounding info to be centered around a specific point given a specific extend.
- * @param center New center of the bounding info
- * @param extend New extend of the bounding info
- */
- BoundingInfo.prototype.centerOn = function (center, extend) {
- this.minimum = center.subtract(extend);
- this.maximum = center.add(extend);
- this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
- this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
- return this;
- };
- BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
- if (!this.boundingSphere.isInFrustum(frustumPlanes))
- return false;
- return this.boundingBox.isInFrustum(frustumPlanes);
- };
- Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
- /**
- * Gets the world distance between the min and max points of the bounding box
- */
- get: function () {
- var boundingBox = this.boundingBox;
- var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
- return size.length();
- },
- enumerable: true,
- configurable: true
- });
- 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 = {}));
- //# sourceMappingURL=babylon.boundingInfo.js.map
- var BABYLON;
- (function (BABYLON) {
- var TransformNode = /** @class */ (function (_super) {
- __extends(TransformNode, _super);
- function TransformNode(name, scene, isPure) {
- if (scene === void 0) { scene = null; }
- if (isPure === void 0) { isPure = true; }
- var _this = _super.call(this, name, scene) || this;
- // Properties
- _this._rotation = BABYLON.Vector3.Zero();
- _this._scaling = BABYLON.Vector3.One();
- _this._isDirty = false;
- _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
- _this.scalingDeterminant = 1;
- _this.infiniteDistance = false;
- _this.position = BABYLON.Vector3.Zero();
- _this._localWorld = BABYLON.Matrix.Zero();
- _this._worldMatrix = BABYLON.Matrix.Zero();
- _this._worldMatrixDeterminant = 0;
- _this._absolutePosition = BABYLON.Vector3.Zero();
- _this._pivotMatrix = BABYLON.Matrix.Identity();
- _this._postMultiplyPivotMatrix = false;
- _this._isWorldMatrixFrozen = false;
- /**
- * An event triggered after the world matrix is updated
- * @type {BABYLON.Observable}
- */
- _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
- _this._nonUniformScaling = false;
- if (isPure) {
- _this.getScene().addTransformNode(_this);
- }
- return _this;
- }
- Object.defineProperty(TransformNode.prototype, "rotation", {
- /**
- * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
- * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
- * Default : (0.0, 0.0, 0.0)
- */
- get: function () {
- return this._rotation;
- },
- set: function (newRotation) {
- this._rotation = newRotation;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(TransformNode.prototype, "scaling", {
- /**
- * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
- * Default : (1.0, 1.0, 1.0)
- */
- get: function () {
- return this._scaling;
- },
- /**
- * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
- * Default : (1.0, 1.0, 1.0)
- */
- set: function (newScaling) {
- this._scaling = newScaling;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
- /**
- * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
- * It's null by default.
- * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
- */
- 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.0, 0.0);
- }
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Returns the latest update of the World matrix
- * Returns a Matrix.
- */
- TransformNode.prototype.getWorldMatrix = function () {
- if (this._currentRenderId !== this.getScene().getRenderId()) {
- this.computeWorldMatrix();
- }
- return this._worldMatrix;
- };
- /**
- * Returns the latest update of the World matrix determinant.
- */
- TransformNode.prototype._getWorldMatrixDeterminant = function () {
- if (this._currentRenderId !== this.getScene().getRenderId()) {
- this.computeWorldMatrix();
- }
- return this._worldMatrixDeterminant;
- };
- Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
- /**
- * Returns directly the latest state of the mesh World matrix.
- * A Matrix is returned.
- */
- get: function () {
- return this._worldMatrix;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Copies the paramater passed Matrix into the mesh Pose matrix.
- * Returns the AbstractMesh.
- */
- TransformNode.prototype.updatePoseMatrix = function (matrix) {
- this._poseMatrix.copyFrom(matrix);
- return this;
- };
- /**
- * Returns the mesh Pose matrix.
- * Returned object : Matrix
- */
- TransformNode.prototype.getPoseMatrix = function () {
- return this._poseMatrix;
- };
- TransformNode.prototype._isSynchronized = function () {
- if (this._isDirty) {
- return false;
- }
- if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.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;
- }
- if (!this._cache.rotation.equals(this.rotation))
- return false;
- if (!this._cache.scaling.equals(this.scaling))
- return false;
- return true;
- };
- TransformNode.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;
- };
- TransformNode.prototype.markAsDirty = function (property) {
- if (property === "rotation") {
- this.rotationQuaternion = null;
- }
- this._currentRenderId = Number.MAX_VALUE;
- this._isDirty = true;
- return this;
- };
- Object.defineProperty(TransformNode.prototype, "absolutePosition", {
- /**
- * Returns the current mesh absolute position.
- * Retuns a Vector3.
- */
- get: function () {
- return this._absolutePosition;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Sets a new pivot matrix to the mesh.
- * Returns the AbstractMesh.
- */
- TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
- if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
- this._pivotMatrix = matrix.clone();
- this._cache.pivotMatrixUpdated = true;
- this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
- if (this._postMultiplyPivotMatrix) {
- this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
- }
- return this;
- };
- /**
- * Returns the mesh pivot matrix.
- * Default : Identity.
- * A Matrix is returned.
- */
- TransformNode.prototype.getPivotMatrix = function () {
- return this._pivotMatrix;
- };
- /**
- * Prevents the World matrix to be computed any longer.
- * Returns the AbstractMesh.
- */
- TransformNode.prototype.freezeWorldMatrix = function () {
- this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
- this.computeWorldMatrix(true);
- this._isWorldMatrixFrozen = true;
- return this;
- };
- /**
- * Allows back the World matrix computation.
- * Returns the AbstractMesh.
- */
- TransformNode.prototype.unfreezeWorldMatrix = function () {
- this._isWorldMatrixFrozen = false;
- this.computeWorldMatrix(true);
- return this;
- };
- Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
- /**
- * True if the World matrix has been frozen.
- * Returns a boolean.
- */
- get: function () {
- return this._isWorldMatrixFrozen;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Retuns the mesh absolute position in the World.
- * Returns a Vector3.
- */
- TransformNode.prototype.getAbsolutePosition = function () {
- this.computeWorldMatrix();
- return this._absolutePosition;
- };
- /**
- * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
- * Returns the AbstractMesh.
- */
- TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
- if (!absolutePosition) {
- return this;
- }
- var absolutePositionX;
- var absolutePositionY;
- var absolutePositionZ;
- if (absolutePosition.x === undefined) {
- if (arguments.length < 3) {
- return this;
- }
- 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;
- }
- return this;
- };
- /**
- * Sets the mesh position in its local space.
- * Returns the AbstractMesh.
- */
- TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
- this.computeWorldMatrix();
- this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
- return this;
- };
- /**
- * Returns the mesh position in the local space from the current World matrix values.
- * Returns a new Vector3.
- */
- TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
- this.computeWorldMatrix();
- var invLocalWorldMatrix = this._localWorld.clone();
- invLocalWorldMatrix.invert();
- return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
- };
- /**
- * Translates the mesh along the passed Vector3 in its local space.
- * Returns the AbstractMesh.
- */
- TransformNode.prototype.locallyTranslate = function (vector3) {
- this.computeWorldMatrix(true);
- this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
- return this;
- };
- /**
- * Orients a mesh towards a target point. Mesh must be drawn facing user.
- * @param targetPoint the position (must be in same space as current mesh) to look at
- * @param yawCor optional yaw (y-axis) correction in radians
- * @param pitchCor optional pitch (x-axis) correction in radians
- * @param rollCor optional roll (z-axis) correction in radians
- * @param space the choosen space of the target
- * @returns the TransformNode.
- */
- TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
- if (yawCor === void 0) { yawCor = 0; }
- if (pitchCor === void 0) { pitchCor = 0; }
- if (rollCor === void 0) { rollCor = 0; }
- if (space === void 0) { space = BABYLON.Space.LOCAL; }
- var dv = BABYLON.AbstractMesh._lookAtVectorCache;
- var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
- targetPoint.subtractToRef(pos, dv);
- 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);
- if (this.rotationQuaternion) {
- BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
- }
- else {
- this.rotation.x = pitch + pitchCor;
- this.rotation.y = yaw + yawCor;
- this.rotation.z = rollCor;
- }
- return this;
- };
- /**
- * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
- * This Vector3 is expressed in the World space.
- */
- TransformNode.prototype.getDirection = function (localAxis) {
- var result = BABYLON.Vector3.Zero();
- this.getDirectionToRef(localAxis, result);
- return result;
- };
- /**
- * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
- * localAxis is expressed in the mesh local space.
- * result is computed in the Wordl space from the mesh World matrix.
- * Returns the AbstractMesh.
- */
- TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
- BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
- return this;
- };
- TransformNode.prototype.setPivotPoint = function (point, space) {
- if (space === void 0) { space = BABYLON.Space.LOCAL; }
- if (this.getScene().getRenderId() == 0) {
- this.computeWorldMatrix(true);
- }
- var wm = this.getWorldMatrix();
- if (space == BABYLON.Space.WORLD) {
- var tmat = BABYLON.Tmp.Matrix[0];
- wm.invertToRef(tmat);
- point = BABYLON.Vector3.TransformCoordinates(point, tmat);
- }
- BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
- this._pivotMatrix.m[12] = -point.x;
- this._pivotMatrix.m[13] = -point.y;
- this._pivotMatrix.m[14] = -point.z;
- this._cache.pivotMatrixUpdated = true;
- return this;
- };
- /**
- * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
- */
- TransformNode.prototype.getPivotPoint = function () {
- var point = BABYLON.Vector3.Zero();
- this.getPivotPointToRef(point);
- return point;
- };
- /**
- * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
- * Returns the AbstractMesh.
- */
- TransformNode.prototype.getPivotPointToRef = function (result) {
- result.x = -this._pivotMatrix.m[12];
- result.y = -this._pivotMatrix.m[13];
- result.z = -this._pivotMatrix.m[14];
- return this;
- };
- /**
- * Returns a new Vector3 set with the mesh pivot point World coordinates.
- */
- TransformNode.prototype.getAbsolutePivotPoint = function () {
- var point = BABYLON.Vector3.Zero();
- this.getAbsolutePivotPointToRef(point);
- return point;
- };
- /**
- * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
- * Returns the AbstractMesh.
- */
- TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
- result.x = this._pivotMatrix.m[12];
- result.y = this._pivotMatrix.m[13];
- result.z = this._pivotMatrix.m[14];
- this.getPivotPointToRef(result);
- BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
- return this;
- };
- /**
- * Defines the passed node as the parent of the current node.
- * The node will remain exactly where it is and its position / rotation will be updated accordingly
- * Returns the TransformNode.
- */
- TransformNode.prototype.setParent = function (node) {
- if (node === null) {
- var rotation = BABYLON.Tmp.Quaternion[0];
- var position = BABYLON.Tmp.Vector3[0];
- var scale = BABYLON.Tmp.Vector3[1];
- if (this.parent && this.parent.computeWorldMatrix) {
- this.parent.computeWorldMatrix(true);
- }
- this.computeWorldMatrix(true);
- this.getWorldMatrix().decompose(scale, rotation, position);
- if (this.rotationQuaternion) {
- this.rotationQuaternion.copyFrom(rotation);
- }
- else {
- rotation.toEulerAnglesToRef(this.rotation);
- }
- this.scaling.x = scale.x;
- this.scaling.y = scale.y;
- this.scaling.z = scale.z;
- this.position.x = position.x;
- this.position.y = position.y;
- this.position.z = position.z;
- }
- else {
- var rotation = BABYLON.Tmp.Quaternion[0];
- var position = BABYLON.Tmp.Vector3[0];
- var scale = BABYLON.Tmp.Vector3[1];
- var diffMatrix = BABYLON.Tmp.Matrix[0];
- var invParentMatrix = BABYLON.Tmp.Matrix[1];
- this.computeWorldMatrix(true);
- node.computeWorldMatrix(true);
- node.getWorldMatrix().invertToRef(invParentMatrix);
- this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
- diffMatrix.decompose(scale, rotation, position);
- if (this.rotationQuaternion) {
- this.rotationQuaternion.copyFrom(rotation);
- }
- else {
- rotation.toEulerAnglesToRef(this.rotation);
- }
- this.position.x = position.x;
- this.position.y = position.y;
- this.position.z = position.z;
- this.scaling.x = scale.x;
- this.scaling.y = scale.y;
- this.scaling.z = scale.z;
- }
- this.parent = node;
- return this;
- };
- Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
- get: function () {
- return this._nonUniformScaling;
- },
- enumerable: true,
- configurable: true
- });
- TransformNode.prototype._updateNonUniformScalingState = function (value) {
- if (this._nonUniformScaling === value) {
- return false;
- }
- this._nonUniformScaling = true;
- return true;
- };
- /**
- * Attach the current TransformNode to another TransformNode associated with a bone
- * @param bone Bone affecting the TransformNode
- * @param affectedTransformNode TransformNode associated with the bone
- */
- TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
- this._transformToBoneReferal = affectedTransformNode;
- this.parent = bone;
- if (bone.getWorldMatrix().determinant() < 0) {
- this.scalingDeterminant *= -1;
- }
- return this;
- };
- TransformNode.prototype.detachFromBone = function () {
- if (!this.parent) {
- return this;
- }
- if (this.parent.getWorldMatrix().determinant() < 0) {
- this.scalingDeterminant *= -1;
- }
- this._transformToBoneReferal = null;
- this.parent = null;
- return this;
- };
- /**
- * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
- * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
- * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
- * The passed axis is also normalized.
- * Returns the AbstractMesh.
- */
- TransformNode.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.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
- this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
- }
- else {
- if (this.parent) {
- var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
- invertParentWorldMatrix.invert();
- axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
- }
- rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
- rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
- }
- return this;
- };
- /**
- * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
- * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
- * The passed axis is also normalized.
- * Returns the AbstractMesh.
- * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
- */
- TransformNode.prototype.rotateAround = function (point, axis, amount) {
- axis.normalize();
- if (!this.rotationQuaternion) {
- this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
- this.rotation.copyFromFloats(0, 0, 0);
- }
- point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
- BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
- BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
- BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
- BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
- BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
- BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
- this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
- BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
- return this;
- };
- /**
- * Translates the mesh along the axis vector for the passed distance in the given space.
- * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
- * Returns the AbstractMesh.
- */
- TransformNode.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));
- }
- return this;
- };
- /**
- * Adds a rotation step to the mesh current rotation.
- * x, y, z are Euler angles expressed in radians.
- * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
- * This means this rotation is made in the mesh local space only.
- * It's useful to set a custom rotation order different from the BJS standard one YXZ.
- * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
- * ```javascript
- * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
- * ```
- * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
- * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles.
- * Returns the AbstractMesh.
- */
- TransformNode.prototype.addRotation = function (x, y, z) {
- var rotationQuaternion;
- if (this.rotationQuaternion) {
- rotationQuaternion = this.rotationQuaternion;
- }
- else {
- rotationQuaternion = BABYLON.Tmp.Quaternion[1];
- BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
- }
- var accumulation = BABYLON.Tmp.Quaternion[0];
- BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
- rotationQuaternion.multiplyInPlace(accumulation);
- if (!this.rotationQuaternion) {
- rotationQuaternion.toEulerAnglesToRef(this.rotation);
- }
- return this;
- };
- /**
- * Computes the mesh World matrix and returns it.
- * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
- * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
- * If the parameter `force`is set to `true`, the actual computation is done.
- * Returns the mesh World Matrix.
- */
- TransformNode.prototype.computeWorldMatrix = function (force) {
- if (this._isWorldMatrixFrozen) {
- return this._worldMatrix;
- }
- if (!force && this.isSynchronized(true)) {
- 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
- var camera = this.getScene().activeCamera;
- if (this.infiniteDistance && !this.parent && 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 (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
- if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
- if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
- // Need to decompose each rotation here
- var currentPosition = BABYLON.Tmp.Vector3[3];
- if (this.parent && this.parent.getWorldMatrix) {
- if (this._transformToBoneReferal) {
- this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
- BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
- }
- else {
- BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
- }
- }
- else {
- currentPosition.copyFrom(this.position);
- }
- currentPosition.subtractInPlace(camera.globalPosition);
- var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
- if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
- finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
- }
- if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
- finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
- }
- if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
- finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
- }
- BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
- }
- else {
- BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
- BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
- BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
- }
- BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
- BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
- }
- // Local world
- BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
- // Parent
- if (this.parent && this.parent.getWorldMatrix) {
- if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
- if (this._transformToBoneReferal) {
- this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
- BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
- }
- else {
- BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
- }
- this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
- BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
- this._worldMatrix.copyFrom(this._localWorld);
- this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
- }
- else {
- if (this._transformToBoneReferal) {
- this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
- BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
- }
- else {
- this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
- }
- }
- this._markSyncedWithParent();
- }
- else {
- this._worldMatrix.copyFrom(this._localWorld);
- }
- // Post multiply inverse of pivotMatrix
- if (this._postMultiplyPivotMatrix) {
- this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
- }
- // Normal matrix
- if (this.scaling.isNonUniform) {
- this._updateNonUniformScalingState(true);
- }
- else if (this.parent && this.parent._nonUniformScaling) {
- this._updateNonUniformScalingState(this.parent._nonUniformScaling);
- }
- else {
- this._updateNonUniformScalingState(false);
- }
- this._afterComputeWorldMatrix();
- // 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);
- }
- // Cache the determinant
- this._worldMatrixDeterminant = this._worldMatrix.determinant();
- return this._worldMatrix;
- };
- TransformNode.prototype._afterComputeWorldMatrix = function () {
- };
- /**
- * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
- * @param func: callback function to add
- *
- * Returns the TransformNode.
- */
- TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
- this.onAfterWorldMatrixUpdateObservable.add(func);
- return this;
- };
- /**
- * Removes a registered callback function.
- * Returns the TransformNode.
- */
- TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
- this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
- return this;
- };
- /**
- * Clone the current transform node
- * Returns the new transform node
- * @param name Name of the new clone
- * @param newParent New parent for the clone
- * @param doNotCloneChildren Do not clone children hierarchy
- */
- TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
- var _this = this;
- var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
- result.name = name;
- result.id = name;
- if (newParent) {
- result.parent = newParent;
- }
- if (!doNotCloneChildren) {
- // Children
- var directDescendants = this.getDescendants(true);
- for (var index = 0; index < directDescendants.length; index++) {
- var child = directDescendants[index];
- if (child.clone) {
- child.clone(name + "." + child.name, result);
- }
- }
- }
- return result;
- };
- TransformNode.prototype.serialize = function (currentSerializationObject) {
- var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
- serializationObject.type = this.getClassName();
- // Parent
- if (this.parent) {
- serializationObject.parentId = this.parent.id;
- }
- if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
- serializationObject.tags = BABYLON.Tags.GetTags(this);
- }
- serializationObject.localMatrix = this.getPivotMatrix().asArray();
- serializationObject.isEnabled = this.isEnabled();
- // Parent
- if (this.parent) {
- serializationObject.parentId = this.parent.id;
- }
- return serializationObject;
- };
- // Statics
- /**
- * Returns a new TransformNode object parsed from the source provided.
- * The parameter `parsedMesh` is the source.
- * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
- */
- TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
- var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
- if (BABYLON.Tags) {
- BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
- }
- if (parsedTransformNode.localMatrix) {
- transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
- }
- else if (parsedTransformNode.pivotMatrix) {
- transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
- }
- transformNode.setEnabled(parsedTransformNode.isEnabled);
- // Parent
- if (parsedTransformNode.parentId) {
- transformNode._waitingParentId = parsedTransformNode.parentId;
- }
- return transformNode;
- };
- /**
- * Disposes the TransformNode.
- * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
- * Returns nothing.
- */
- TransformNode.prototype.dispose = function (doNotRecurse) {
- // Animations
- this.getScene().stopAnimation(this);
- // Remove from scene
- this.getScene().removeTransformNode(this);
- if (!doNotRecurse) {
- // Children
- var objects = this.getDescendants(true);
- for (var 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);
- }
- }
- this.onAfterWorldMatrixUpdateObservable.clear();
- _super.prototype.dispose.call(this);
- };
- // Statics
- TransformNode.BILLBOARDMODE_NONE = 0;
- TransformNode.BILLBOARDMODE_X = 1;
- TransformNode.BILLBOARDMODE_Y = 2;
- TransformNode.BILLBOARDMODE_Z = 4;
- TransformNode.BILLBOARDMODE_ALL = 7;
- TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
- TransformNode._rotationAxisCache = new BABYLON.Quaternion();
- __decorate([
- BABYLON.serializeAsVector3()
- ], TransformNode.prototype, "_rotation", void 0);
- __decorate([
- BABYLON.serializeAsQuaternion()
- ], TransformNode.prototype, "_rotationQuaternion", void 0);
- __decorate([
- BABYLON.serializeAsVector3()
- ], TransformNode.prototype, "_scaling", void 0);
- __decorate([
- BABYLON.serialize()
- ], TransformNode.prototype, "billboardMode", void 0);
- __decorate([
- BABYLON.serialize()
- ], TransformNode.prototype, "scalingDeterminant", void 0);
- __decorate([
- BABYLON.serialize()
- ], TransformNode.prototype, "infiniteDistance", void 0);
- __decorate([
- BABYLON.serializeAsVector3()
- ], TransformNode.prototype, "position", void 0);
- return TransformNode;
- }(BABYLON.Node));
- BABYLON.TransformNode = TransformNode;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.transformNode.js.map
- var BABYLON;
- (function (BABYLON) {
- var AbstractMesh = /** @class */ (function (_super) {
- __extends(AbstractMesh, _super);
- // Constructor
- function AbstractMesh(name, scene) {
- if (scene === void 0) { scene = null; }
- var _this = _super.call(this, name, scene, false) || this;
- _this._facetNb = 0; // facet number
- _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
- _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
- _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
- _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
- _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
- _this._subDiv = {
- max: 1,
- X: 1,
- Y: 1,
- Z: 1
- };
- _this._facetDepthSort = false; // is the facet depth sort to be computed
- _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
- // 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 when material is changed
- * @type {BABYLON.Observable}
- */
- _this.onMaterialChangedObservable = new BABYLON.Observable();
- // Properties
- _this.definedFacingForward = true; // orientation for POV movement & rotation
- /**
- * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
-
- * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
-
- * or
-
- * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE (Default Value) which is mapped to GL_ANY_SAMPLES_PASSED_CONSERVATIVE which is a false positive algorithm that is faster than GL_ANY_SAMPLES_PASSED but less accurate.
-
- * for more info check WebGl documentations
- */
- _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
- /**
- * This property is responsible for starting the occlusion query within the Mesh or not, this property is also used to determine what should happen when the occlusionRetryCount is reached. It has supports 3 values:
-
- * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
-
- * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
-
- * OCCLUSION_TYPE_STRICT: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken restore the last state of the mesh occlusion if the mesh was visible then show the mesh if was hidden then hide don't show.
- */
- _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
- /**
- * This number indicates the number of allowed retries before stop the occlusion query, this is useful if the occlusion query is taking long time before to the query result is retireved, the query result indicates if the object is visible within the scene or not and based on that Babylon.Js engine decideds to show or hide the object.
-
- * The default value is -1 which means don't break the query and wait till the result.
- */
- _this.occlusionRetryCount = -1;
- _this._occlusionInternalRetryCounter = 0;
- _this._isOccluded = false;
- _this._isOcclusionQueryInProgress = false;
- _this.visibility = 1.0;
- _this.alphaIndex = Number.MAX_VALUE;
- _this.isVisible = true;
- _this.isPickable = true;
- _this.showBoundingBox = false;
- _this.showSubMeshesBoundingBox = false;
- _this.isBlocker = false;
- _this.enablePointerMoveEvents = 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._computeBonesUsingShaders = true;
- _this._numBoneInfluencers = 4;
- _this._applyFog = true;
- _this.useOctreeForRenderingSelection = true;
- _this.useOctreeForPicking = true;
- _this.useOctreeForCollisions = true;
- _this._layerMask = 0x0FFFFFFF;
- /**
- * True if the mesh must be rendered in any case.
- */
- _this.alwaysSelectAsActiveMesh = false;
- /**
- * This scene's action manager
- * @type {BABYLON.ActionManager}
- */
- _this.actionManager = null;
- // Physics
- _this.physicsImpostor = null;
- // Collisions
- _this._checkCollisions = false;
- _this._collisionMask = -1;
- _this._collisionGroup = -1;
- _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
- _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
- _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
- _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
- // Edges
- _this.edgesWidth = 1;
- _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
- // Cache
- _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
- _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
- _this._isDisposed = false;
- _this._renderId = 0;
- _this._intersectionsInProgress = new Array();
- _this._unIndexed = false;
- _this._lightSources = new Array();
- _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);
- };
- _this.getScene().addMesh(_this);
- _this._resyncLightSources();
- return _this;
- }
- Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
- get: function () {
- return BABYLON.TransformNode.BILLBOARDMODE_NONE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
- get: function () {
- return BABYLON.TransformNode.BILLBOARDMODE_X;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
- get: function () {
- return BABYLON.TransformNode.BILLBOARDMODE_Y;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
- get: function () {
- return BABYLON.TransformNode.BILLBOARDMODE_Z;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
- get: function () {
- return BABYLON.TransformNode.BILLBOARDMODE_ALL;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh.prototype, "facetNb", {
- /**
- * Read-only : the number of facets in the mesh
- */
- get: function () {
- return this._facetNb;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
- /**
- * The number (integer) of subdivisions per axis in the partioning space
- */
- get: function () {
- return this._partitioningSubdivisions;
- },
- set: function (nb) {
- this._partitioningSubdivisions = nb;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
- /**
- * The ratio (float) to apply to the bouding box size to set to the partioning space.
- * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
- */
- get: function () {
- return this._partitioningBBoxRatio;
- },
- set: function (ratio) {
- this._partitioningBBoxRatio = ratio;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
- /**
- * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
- * Works only for updatable meshes.
- * Doesn't work with multi-materials.
- */
- get: function () {
- return this._facetDepthSort;
- },
- set: function (sort) {
- this._facetDepthSort = sort;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
- /**
- * The location (Vector3) where the facet depth sort must be computed from.
- * By default, the active camera position.
- * Used only when facet depth sort is enabled.
- */
- get: function () {
- return this._facetDepthSortFrom;
- },
- set: function (location) {
- this._facetDepthSortFrom = location;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
- /**
- * Read-only boolean : is the feature facetData enabled ?
- */
- get: function () {
- return this._facetDataEnabled;
- },
- enumerable: true,
- configurable: true
- });
- AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
- if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
- return false;
- }
- this._markSubMeshesAsMiscDirty();
- return 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, "isOccluded", {
- /**
- * Property isOccluded : Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not.
- */
- get: function () {
- return this._isOccluded;
- },
- set: function (value) {
- this._isOccluded = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
- /**
- * Flag to check the progress status of the query
- */
- get: function () {
- return this._isOcclusionQueryInProgress;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh.prototype, "material", {
- get: function () {
- return this._material;
- },
- set: function (value) {
- if (this._material === value) {
- return;
- }
- this._material = value;
- if (this.onMaterialChangedObservable.hasObservers) {
- this.onMaterialChangedObservable.notifyObservers(this);
- }
- if (!this.subMeshes) {
- return;
- }
- for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
- var subMesh = _a[_i];
- subMesh.setEffect(null);
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
- get: function () {
- return this._receiveShadows;
- },
- set: function (value) {
- if (this._receiveShadows === value) {
- return;
- }
- this._receiveShadows = value;
- this._markSubMeshesAsLightDirty();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
- get: function () {
- return this._hasVertexAlpha;
- },
- set: function (value) {
- if (this._hasVertexAlpha === value) {
- return;
- }
- this._hasVertexAlpha = value;
- this._markSubMeshesAsAttributesDirty();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
- get: function () {
- return this._useVertexColors;
- },
- set: function (value) {
- if (this._useVertexColors === value) {
- return;
- }
- this._useVertexColors = value;
- this._markSubMeshesAsAttributesDirty();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
- get: function () {
- return this._computeBonesUsingShaders;
- },
- set: function (value) {
- if (this._computeBonesUsingShaders === value) {
- return;
- }
- this._computeBonesUsingShaders = value;
- this._markSubMeshesAsAttributesDirty();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
- get: function () {
- return this._numBoneInfluencers;
- },
- set: function (value) {
- if (this._numBoneInfluencers === value) {
- return;
- }
- this._numBoneInfluencers = value;
- this._markSubMeshesAsAttributesDirty();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh.prototype, "applyFog", {
- get: function () {
- return this._applyFog;
- },
- set: function (value) {
- if (this._applyFog === value) {
- return;
- }
- this._applyFog = value;
- this._markSubMeshesAsMiscDirty();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh.prototype, "layerMask", {
- get: function () {
- return this._layerMask;
- },
- set: function (value) {
- if (value === this._layerMask) {
- return;
- }
- this._layerMask = value;
- this._resyncLightSources();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
- get: function () {
- return this._collisionMask;
- },
- set: function (mask) {
- this._collisionMask = !isNaN(mask) ? mask : -1;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
- get: function () {
- return this._collisionGroup;
- },
- set: function (mask) {
- this._collisionGroup = !isNaN(mask) ? mask : -1;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh.prototype, "_positions", {
- get: function () {
- return null;
- },
- 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;
- }
- this._markSubMeshesAsAttributesDirty();
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Boolean : true if the mesh has been disposed.
- */
- AbstractMesh.prototype.isDisposed = function () {
- return this._isDisposed;
- };
- /**
- * Returns the string "AbstractMesh"
- */
- AbstractMesh.prototype.getClassName = function () {
- return "AbstractMesh";
- };
- /**
- * @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;
- };
- AbstractMesh.prototype._rebuild = function () {
- if (this._occlusionQuery) {
- this._occlusionQuery = null;
- }
- if (this._edgesRenderer) {
- this._edgesRenderer._rebuild();
- }
- if (!this.subMeshes) {
- return;
- }
- for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
- var subMesh = _a[_i];
- subMesh._rebuild();
- }
- };
- AbstractMesh.prototype._resyncLightSources = function () {
- this._lightSources.length = 0;
- for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
- var light = _a[_i];
- if (!light.isEnabled()) {
- continue;
- }
- if (light.canAffectMesh(this)) {
- this._lightSources.push(light);
- }
- }
- this._markSubMeshesAsLightDirty();
- };
- AbstractMesh.prototype._resyncLighSource = function (light) {
- var isIn = light.isEnabled() && light.canAffectMesh(this);
- var index = this._lightSources.indexOf(light);
- if (index === -1) {
- if (!isIn) {
- return;
- }
- this._lightSources.push(light);
- }
- else {
- if (isIn) {
- return;
- }
- this._lightSources.splice(index, 1);
- }
- this._markSubMeshesAsLightDirty();
- };
- AbstractMesh.prototype._removeLightSource = function (light) {
- var index = this._lightSources.indexOf(light);
- if (index === -1) {
- return;
- }
- this._lightSources.splice(index, 1);
- };
- AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
- if (!this.subMeshes) {
- return;
- }
- for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
- var subMesh = _a[_i];
- if (subMesh._materialDefines) {
- func(subMesh._materialDefines);
- }
- }
- };
- AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
- this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
- };
- AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
- this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
- };
- AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
- if (!this.subMeshes) {
- return;
- }
- for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
- var subMesh = _a[_i];
- var material = subMesh.getMaterial();
- if (material) {
- material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
- }
- }
- };
- Object.defineProperty(AbstractMesh.prototype, "scaling", {
- /**
- * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
- * Default : (1.0, 1.0, 1.0)
- */
- get: function () {
- return this._scaling;
- },
- /**
- * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
- * Default : (1.0, 1.0, 1.0)
- */
- set: function (newScaling) {
- this._scaling = newScaling;
- if (this.physicsImpostor) {
- this.physicsImpostor.forceUpdate();
- }
- },
- enumerable: true,
- configurable: true
- });
- // Methods
- /**
- * Disables the mesh edger rendering mode.
- * Returns the AbstractMesh.
- */
- AbstractMesh.prototype.disableEdgesRendering = function () {
- if (this._edgesRenderer) {
- this._edgesRenderer.dispose();
- this._edgesRenderer = null;
- }
- return this;
- };
- /**
- * Enables the edge rendering mode on the mesh.
- * This mode makes the mesh edges visible.
- * Returns the AbstractMesh.
- */
- 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);
- return this;
- };
- Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
- /**
- * Returns true if the mesh is blocked. Used by the class Mesh.
- * Returns the boolean `false` by default.
- */
- get: function () {
- return false;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Returns the mesh itself by default, used by the class Mesh.
- * Returned type : AbstractMesh
- */
- AbstractMesh.prototype.getLOD = function (camera) {
- return this;
- };
- /**
- * Returns 0 by default, used by the class Mesh.
- * Returns an integer.
- */
- AbstractMesh.prototype.getTotalVertices = function () {
- return 0;
- };
- /**
- * Returns null by default, used by the class Mesh.
- * Returned type : integer array
- */
- AbstractMesh.prototype.getIndices = function () {
- return null;
- };
- /**
- * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
- * Returned type : float array or Float32Array
- */
- AbstractMesh.prototype.getVerticesData = function (kind) {
- return null;
- };
- /**
- * 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
- *
- * Returns the Mesh.
- */
- AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
- return this;
- };
- /**
- * 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
- *
- * Returns the Mesh.
- */
- AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
- return this;
- };
- /**
- * Sets the mesh indices.
- * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
- * 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.
- * Returns the Mesh.
- */
- AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
- return this;
- };
- /** Returns false by default, used by the class Mesh.
- * Returns a boolean
- */
- AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
- return false;
- };
- /**
- * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
- * Returns a BoundingInfo
- */
- AbstractMesh.prototype.getBoundingInfo = function () {
- if (this._masterMesh) {
- return this._masterMesh.getBoundingInfo();
- }
- if (!this._boundingInfo) {
- // this._boundingInfo is being created here
- this._updateBoundingInfo();
- }
- // cannot be null.
- return this._boundingInfo;
- };
- /**
- * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
- * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
- */
- AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
- if (includeDescendants === void 0) { includeDescendants = true; }
- var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
- var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
- var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
- if (maxDimension === 0) {
- return this;
- }
- var scale = 1 / maxDimension;
- this.scaling.scaleInPlace(scale);
- return this;
- };
- /**
- * Sets a mesh new object BoundingInfo.
- * Returns the AbstractMesh.
- */
- AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
- this._boundingInfo = boundingInfo;
- return this;
- };
- 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;
- };
- /**
- * Returns the latest update of the World matrix
- * Returns a Matrix.
- */
- AbstractMesh.prototype.getWorldMatrix = function () {
- if (this._masterMesh) {
- return this._masterMesh.getWorldMatrix();
- }
- return _super.prototype.getWorldMatrix.call(this);
- };
- /**
- * Returns the latest update of the World matrix determinant.
- */
- AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
- if (this._masterMesh) {
- return this._masterMesh._getWorldMatrixDeterminant();
- }
- return _super.prototype._getWorldMatrixDeterminant.call(this);
- };
- // ================================== 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
- *
- * Returns the AbstractMesh.
- */
- AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
- this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
- return this;
- };
- /**
- * 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
- *
- * Returns a new Vector3.
- */
- 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
- *
- * Returns the AbstractMesh.
- */
- AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
- this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
- return this;
- };
- /**
- * 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
- *
- * Returns a new Vector3.
- */
- AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
- var defForwardMult = this.definedFacingForward ? 1 : -1;
- return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
- };
- /**
- * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
- * @param includeDescendants Include bounding info from descendants as well (true by default).
- */
- AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
- if (includeDescendants === void 0) { includeDescendants = true; }
- this.computeWorldMatrix(true);
- var min;
- var max;
- var boundingInfo = this.getBoundingInfo();
- if (!this.subMeshes) {
- min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
- max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
- }
- else {
- min = boundingInfo.boundingBox.minimumWorld;
- max = boundingInfo.boundingBox.maximumWorld;
- }
- if (includeDescendants) {
- var descendants = this.getDescendants(false);
- for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
- var descendant = descendants_1[_i];
- var childMesh = descendant;
- childMesh.computeWorldMatrix(true);
- //make sure we have the needed params to get mix and max
- if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
- continue;
- }
- var childBoundingInfo = childMesh.getBoundingInfo();
- var boundingBox = childBoundingInfo.boundingBox;
- var minBox = boundingBox.minimumWorld;
- var maxBox = boundingBox.maximumWorld;
- BABYLON.Tools.CheckExtends(minBox, min, max);
- BABYLON.Tools.CheckExtends(maxBox, min, max);
- }
- }
- return {
- min: min,
- max: max
- };
- };
- /**
- * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
- * Returns the AbstractMesh.
- */
- AbstractMesh.prototype._updateBoundingInfo = function () {
- this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
- this._boundingInfo.update(this.worldMatrixFromCache);
- this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
- return this;
- };
- /**
- * Update a mesh's children BoundingInfo objects only.
- * Returns the AbstractMesh.
- */
- AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
- if (!this.subMeshes) {
- return this;
- }
- for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
- var subMesh = this.subMeshes[subIndex];
- if (!subMesh.IsGlobal) {
- subMesh.updateBoundingInfo(matrix);
- }
- }
- return this;
- };
- AbstractMesh.prototype._afterComputeWorldMatrix = function () {
- // Bounding info
- this._updateBoundingInfo();
- };
- /**
- * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
- * A mesh is in the frustum if its bounding box intersects the frustum.
- * Boolean returned.
- */
- AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
- return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
- };
- /**
- * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
- * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
- * Boolean returned.
- */
- AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
- return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
- ;
- };
- /**
- * True if the mesh intersects another mesh or a SolidParticle object.
- * Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
- * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
- * Returns a boolean.
- */
- AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
- if (precise === void 0) { precise = false; }
- if (!this._boundingInfo || !mesh._boundingInfo) {
- return false;
- }
- if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
- return true;
- }
- if (includeDescendants) {
- for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
- var child = _a[_i];
- if (child.intersectsMesh(mesh, precise, true)) {
- return true;
- }
- }
- }
- return false;
- };
- /**
- * Returns true if the passed point (Vector3) is inside the mesh bounding box.
- * Returns a boolean.
- */
- AbstractMesh.prototype.intersectsPoint = function (point) {
- if (!this._boundingInfo) {
- return false;
- }
- return this._boundingInfo.intersectsPoint(point);
- };
- AbstractMesh.prototype.getPhysicsImpostor = function () {
- return this.physicsImpostor;
- };
- AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
- if (camera === void 0) { camera = null; }
- if (!camera) {
- camera = this.getScene().activeCamera;
- }
- return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
- };
- /**
- * Returns the distance from the mesh to the active camera.
- * Returns a float.
- */
- AbstractMesh.prototype.getDistanceToCamera = function (camera) {
- if (camera === void 0) { camera = null; }
- if (!camera) {
- camera = this.getScene().activeCamera;
- }
- return this.absolutePosition.subtract(camera.position).length();
- };
- AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
- if (!this.physicsImpostor) {
- return this;
- }
- this.physicsImpostor.applyImpulse(force, contactPoint);
- return this;
- };
- AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
- if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
- return this;
- }
- this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
- mainPivot: pivot1,
- connectedPivot: pivot2,
- nativeParams: options
- });
- return this;
- };
- Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
- // Collisions
- /**
- * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
- * Default `false`.
- */
- get: function () {
- return this._checkCollisions;
- },
- set: function (collisionEnabled) {
- this._checkCollisions = collisionEnabled;
- if (this.getScene().workerCollisions) {
- this.getScene().collisionCoordinator.onMeshUpdated(this);
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractMesh.prototype, "collider", {
- /**
- * Gets Collider object used to compute collisions (not physics)
- */
- get: function () {
- return this._collider;
- },
- enumerable: true,
- configurable: true
- });
- AbstractMesh.prototype.moveWithCollisions = function (displacement) {
- var globalPosition = this.getAbsolutePosition();
- globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
- if (!this._collider) {
- this._collider = new BABYLON.Collider();
- }
- this._collider._radius = this.ellipsoid;
- this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
- return this;
- };
- // Submeshes octree
- /**
- * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
- * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
- * Returns an Octree of submeshes.
- */
- 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);
- var boundingInfo = this.getBoundingInfo();
- // Update octree
- var bbox = boundingInfo.boundingBox;
- this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
- return this._submeshesOctree;
- };
- // Collisions
- AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
- this._generatePointsArray();
- if (!this._positions) {
- return this;
- }
- // 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;
- }
- return 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);
- }
- return this;
- };
- AbstractMesh.prototype._checkCollision = function (collider) {
- // Bounding box test
- if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
- return this;
- // 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);
- return this;
- };
- // Picking
- AbstractMesh.prototype._generatePointsArray = function () {
- return false;
- };
- /**
- * Checks if the passed Ray intersects with the mesh.
- * Returns an object PickingInfo.
- */
- 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 || 0;
- pickingInfo.bv = intersectInfo.bv || 0;
- pickingInfo.faceId = intersectInfo.faceId;
- pickingInfo.subMeshId = intersectInfo.subMeshId;
- return pickingInfo;
- }
- return pickingInfo;
- };
- /**
- * Clones the mesh, used by the class Mesh.
- * Just returns `null` for an AbstractMesh.
- */
- AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
- return null;
- };
- /**
- * Disposes all the mesh submeshes.
- * Returns the AbstractMesh.
- */
- AbstractMesh.prototype.releaseSubMeshes = function () {
- if (this.subMeshes) {
- while (this.subMeshes.length) {
- this.subMeshes[0].dispose();
- }
- }
- else {
- this.subMeshes = new Array();
- }
- return this;
- };
- /**
- * Disposes the AbstractMesh.
- * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
- * Returns nothing.
- */
- AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
- var _this = this;
- if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
- var index;
- // Action manager
- if (this.actionManager !== undefined && this.actionManager !== null) {
- this.actionManager.dispose();
- this.actionManager = null;
- }
- // Skeleton
- this.skeleton = null;
- // 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);
- }
- // Shadow generators
- var generator = light.getShadowGenerator();
- if (generator) {
- var shadowMap = generator.getShadowMap();
- if (shadowMap && shadowMap.renderList) {
- meshIndex = shadowMap.renderList.indexOf(_this);
- if (meshIndex !== -1) {
- shadowMap.renderList.splice(meshIndex, 1);
- }
- }
- }
- });
- // Edges
- if (this._edgesRenderer) {
- this._edgesRenderer.dispose();
- this._edgesRenderer = null;
- }
- // SubMeshes
- if (this.getClassName() !== "InstancedMesh") {
- this.releaseSubMeshes();
- }
- // Octree
- var sceneOctree = this.getScene().selectionOctree;
- if (sceneOctree !== undefined && sceneOctree !== null) {
- var index = sceneOctree.dynamicContent.indexOf(this);
- if (index !== -1) {
- sceneOctree.dynamicContent.splice(index, 1);
- }
- }
- // Query
- var engine = this.getScene().getEngine();
- if (this._occlusionQuery) {
- this._isOcclusionQueryInProgress = false;
- engine.deleteQuery(this._occlusionQuery);
- this._occlusionQuery = null;
- }
- // Engine
- engine.wipeCaches();
- // Remove from scene
- this.getScene().removeMesh(this);
- if (disposeMaterialAndTextures) {
- if (this.material) {
- this.material.dispose(false, true);
- }
- }
- 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--;
- }
- }
- }
- // facet data
- if (this._facetDataEnabled) {
- this.disableFacetData();
- }
- this.onAfterWorldMatrixUpdateObservable.clear();
- this.onCollideObservable.clear();
- this.onCollisionPositionChangeObservable.clear();
- this._isDisposed = true;
- _super.prototype.dispose.call(this, doNotRecurse);
- };
- /**
- * Adds the passed mesh as a child to the current mesh.
- * Returns the AbstractMesh.
- */
- AbstractMesh.prototype.addChild = function (mesh) {
- mesh.setParent(this);
- return this;
- };
- /**
- * Removes the passed mesh from the current mesh children list.
- * Returns the AbstractMesh.
- */
- AbstractMesh.prototype.removeChild = function (mesh) {
- mesh.setParent(null);
- return this;
- };
- // Facet data
- /**
- * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
- * Returns the AbstractMesh.
- */
- AbstractMesh.prototype._initFacetData = function () {
- if (!this._facetNormals) {
- this._facetNormals = new Array();
- }
- if (!this._facetPositions) {
- this._facetPositions = new Array();
- }
- if (!this._facetPartitioning) {
- this._facetPartitioning = new Array();
- }
- this._facetNb = (this.getIndices().length / 3) | 0;
- this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
- this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
- for (var f = 0; f < this._facetNb; f++) {
- this._facetNormals[f] = BABYLON.Vector3.Zero();
- this._facetPositions[f] = BABYLON.Vector3.Zero();
- }
- this._facetDataEnabled = true;
- return this;
- };
- /**
- * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
- * This method can be called within the render loop.
- * You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation.
- * Returns the AbstractMesh.
- */
- AbstractMesh.prototype.updateFacetData = function () {
- if (!this._facetDataEnabled) {
- this._initFacetData();
- }
- var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- var indices = this.getIndices();
- var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
- var bInfo = this.getBoundingInfo();
- if (this._facetDepthSort && !this._facetDepthSortEnabled) {
- // init arrays, matrix and sort function on first call
- this._facetDepthSortEnabled = true;
- if (indices instanceof Uint16Array) {
- this._depthSortedIndices = new Uint16Array(indices);
- }
- else if (indices instanceof Uint32Array) {
- this._depthSortedIndices = new Uint32Array(indices);
- }
- else {
- var needs32bits = false;
- for (var i = 0; i < indices.length; i++) {
- if (indices[i] > 65535) {
- needs32bits = true;
- break;
- }
- }
- if (needs32bits) {
- this._depthSortedIndices = new Uint32Array(indices);
- }
- else {
- this._depthSortedIndices = new Uint16Array(indices);
- }
- }
- this._facetDepthSortFunction = function (f1, f2) {
- return (f2.sqDistance - f1.sqDistance);
- };
- if (!this._facetDepthSortFrom) {
- var camera = this.getScene().activeCamera;
- this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
- }
- this._depthSortedFacets = [];
- for (var f = 0; f < this._facetNb; f++) {
- var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
- this._depthSortedFacets.push(depthSortedFacet);
- }
- this._invertedMatrix = BABYLON.Matrix.Identity();
- this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
- }
- this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
- this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
- this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
- var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
- bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
- this._subDiv.max = this._partitioningSubdivisions;
- this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
- this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
- this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
- this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
- this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
- this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
- // set the parameters for ComputeNormals()
- this._facetParameters.facetNormals = this.getFacetLocalNormals();
- this._facetParameters.facetPositions = this.getFacetLocalPositions();
- this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
- this._facetParameters.bInfo = bInfo;
- this._facetParameters.bbSize = this._bbSize;
- this._facetParameters.subDiv = this._subDiv;
- this._facetParameters.ratio = this.partitioningBBoxRatio;
- this._facetParameters.depthSort = this._facetDepthSort;
- if (this._facetDepthSort && this._facetDepthSortEnabled) {
- this.computeWorldMatrix(true);
- this._worldMatrix.invertToRef(this._invertedMatrix);
- BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
- this._facetParameters.distanceTo = this._facetDepthSortOrigin;
- }
- this._facetParameters.depthSortedFacets = this._depthSortedFacets;
- BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
- if (this._facetDepthSort && this._facetDepthSortEnabled) {
- this._depthSortedFacets.sort(this._facetDepthSortFunction);
- var l = (this._depthSortedIndices.length / 3) | 0;
- for (var f = 0; f < l; f++) {
- var sind = this._depthSortedFacets[f].ind;
- this._depthSortedIndices[f * 3] = indices[sind];
- this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
- this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
- }
- this.updateIndices(this._depthSortedIndices);
- }
- return this;
- };
- /**
- * Returns the facetLocalNormals array.
- * The normals are expressed in the mesh local space.
- */
- AbstractMesh.prototype.getFacetLocalNormals = function () {
- if (!this._facetNormals) {
- this.updateFacetData();
- }
- return this._facetNormals;
- };
- /**
- * Returns the facetLocalPositions array.
- * The facet positions are expressed in the mesh local space.
- */
- AbstractMesh.prototype.getFacetLocalPositions = function () {
- if (!this._facetPositions) {
- this.updateFacetData();
- }
- return this._facetPositions;
- };
- /**
- * Returns the facetLocalPartioning array.
- */
- AbstractMesh.prototype.getFacetLocalPartitioning = function () {
- if (!this._facetPartitioning) {
- this.updateFacetData();
- }
- return this._facetPartitioning;
- };
- /**
- * Returns the i-th facet position in the world system.
- * This method allocates a new Vector3 per call.
- */
- AbstractMesh.prototype.getFacetPosition = function (i) {
- var pos = BABYLON.Vector3.Zero();
- this.getFacetPositionToRef(i, pos);
- return pos;
- };
- /**
- * Sets the reference Vector3 with the i-th facet position in the world system.
- * Returns the AbstractMesh.
- */
- AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
- var localPos = (this.getFacetLocalPositions())[i];
- var world = this.getWorldMatrix();
- BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
- return this;
- };
- /**
- * Returns the i-th facet normal in the world system.
- * This method allocates a new Vector3 per call.
- */
- AbstractMesh.prototype.getFacetNormal = function (i) {
- var norm = BABYLON.Vector3.Zero();
- this.getFacetNormalToRef(i, norm);
- return norm;
- };
- /**
- * Sets the reference Vector3 with the i-th facet normal in the world system.
- * Returns the AbstractMesh.
- */
- AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
- var localNorm = (this.getFacetLocalNormals())[i];
- BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
- return this;
- };
- /**
- * Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system).
- */
- AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
- var bInfo = this.getBoundingInfo();
- var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
- var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
- var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
- if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
- return null;
- }
- return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
- };
- /**
- * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
- * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
- * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
- * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
- * If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
- */
- AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
- if (checkFace === void 0) { checkFace = false; }
- if (facing === void 0) { facing = true; }
- var world = this.getWorldMatrix();
- var invMat = BABYLON.Tmp.Matrix[5];
- world.invertToRef(invMat);
- var invVect = BABYLON.Tmp.Vector3[8];
- BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
- var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
- if (projected) {
- // tranform the local computed projected vector to world coordinates
- BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
- }
- return closest;
- };
- /**
- * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
- * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
- * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
- * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
- * If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
- */
- AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
- if (checkFace === void 0) { checkFace = false; }
- if (facing === void 0) { facing = true; }
- var closest = null;
- var tmpx = 0.0;
- var tmpy = 0.0;
- var tmpz = 0.0;
- var d = 0.0; // tmp dot facet normal * facet position
- var t0 = 0.0;
- var projx = 0.0;
- var projy = 0.0;
- var projz = 0.0;
- // Get all the facets in the same partitioning block than (x, y, z)
- var facetPositions = this.getFacetLocalPositions();
- var facetNormals = this.getFacetLocalNormals();
- var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
- if (!facetsInBlock) {
- return null;
- }
- // Get the closest facet to (x, y, z)
- var shortest = Number.MAX_VALUE; // init distance vars
- var tmpDistance = shortest;
- var fib; // current facet in the block
- var norm; // current facet normal
- var p0; // current facet barycenter position
- // loop on all the facets in the current partitioning block
- for (var idx = 0; idx < facetsInBlock.length; idx++) {
- fib = facetsInBlock[idx];
- norm = facetNormals[fib];
- p0 = facetPositions[fib];
- d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
- if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
- // compute (x,y,z) projection on the facet = (projx, projy, projz)
- d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
- t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
- projx = x + norm.x * t0;
- projy = y + norm.y * t0;
- projz = z + norm.z * t0;
- tmpx = projx - x;
- tmpy = projy - y;
- tmpz = projz - z;
- tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
- if (tmpDistance < shortest) {
- shortest = tmpDistance;
- closest = fib;
- if (projected) {
- projected.x = projx;
- projected.y = projy;
- projected.z = projz;
- }
- }
- }
- }
- return closest;
- };
- /**
- * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
- */
- AbstractMesh.prototype.getFacetDataParameters = function () {
- return this._facetParameters;
- };
- /**
- * Disables the feature FacetData and frees the related memory.
- * Returns the AbstractMesh.
- */
- AbstractMesh.prototype.disableFacetData = function () {
- if (this._facetDataEnabled) {
- this._facetDataEnabled = false;
- this._facetPositions = new Array();
- this._facetNormals = new Array();
- this._facetPartitioning = new Array();
- this._facetParameters = null;
- this._depthSortedIndices = new Uint32Array(0);
- }
- return this;
- };
- /**
- * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
- * Returns the mesh.
- */
- AbstractMesh.prototype.updateIndices = function (indices) {
- return this;
- };
- /**
- * The mesh Geometry. Actually used by the Mesh object.
- * Returns a blank geometry object.
- */
- /**
- * Creates new normals data for the mesh.
- * @param updatable.
- */
- AbstractMesh.prototype.createNormals = function (updatable) {
- var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- var indices = this.getIndices();
- var normals;
- if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
- normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
- }
- else {
- normals = [];
- }
- BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
- this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
- };
- /**
- * Align the mesh with a normal.
- * Returns the mesh.
- */
- AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
- if (!upDirection) {
- upDirection = BABYLON.Axis.Y;
- }
- var axisX = BABYLON.Tmp.Vector3[0];
- var axisZ = BABYLON.Tmp.Vector3[1];
- BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
- BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
- if (this.rotationQuaternion) {
- BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
- }
- else {
- BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
- }
- return this;
- };
- AbstractMesh.prototype.checkOcclusionQuery = function () {
- var engine = this.getEngine();
- if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
- this._isOccluded = false;
- return;
- }
- if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
- var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
- if (isOcclusionQueryAvailable) {
- var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
- this._isOcclusionQueryInProgress = false;
- this._occlusionInternalRetryCounter = 0;
- this._isOccluded = occlusionQueryResult === 1 ? false : true;
- }
- else {
- this._occlusionInternalRetryCounter++;
- if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
- this._isOcclusionQueryInProgress = false;
- this._occlusionInternalRetryCounter = 0;
- // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
- // if strict continue the last state of the object.
- this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
- }
- else {
- return;
- }
- }
- }
- var scene = this.getScene();
- var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
- if (!this._occlusionQuery) {
- this._occlusionQuery = engine.createQuery();
- }
- engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
- occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
- engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
- this._isOcclusionQueryInProgress = true;
- };
- AbstractMesh.OCCLUSION_TYPE_NONE = 0;
- AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
- AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
- AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
- AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
- return AbstractMesh;
- }(BABYLON.TransformNode));
- BABYLON.AbstractMesh = AbstractMesh;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.abstractMesh.js.map
- var BABYLON;
- (function (BABYLON) {
- var Light = /** @class */ (function (_super) {
- __extends(Light, _super);
- /**
- * Creates a Light object in the scene.
- * Documentation : http://doc.babylonjs.com/tutorials/lights
- */
- function Light(name, scene) {
- var _this = _super.call(this, name, scene) || this;
- _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;
- /**
- * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
- * of light.
- */
- _this._photometricScale = 1.0;
- _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
- _this._radius = 0.00001;
- _this.renderPriority = 0;
- /**
- * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
- * the current shadow generator.
- */
- _this.shadowEnabled = true;
- _this._excludeWithLayerMask = 0;
- _this._includeOnlyWithLayerMask = 0;
- _this._lightmapMode = 0;
- _this._excludedMeshesIds = new Array();
- _this._includedOnlyMeshesIds = new Array();
- _this.getScene().addLight(_this);
- _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
- _this._buildUniformLayout();
- _this.includedOnlyMeshes = new Array();
- _this.excludedMeshes = new Array();
- _this._resyncMeshes();
- return _this;
- }
- Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
- /**
- * If every light affecting the material is in this lightmapMode,
- * material.lightmapTexture adds or multiplies
- * (depends on material.useLightmapAsShadowmap)
- * after every other light calculations.
- */
- get: function () {
- return Light._LIGHTMAP_DEFAULT;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
- /**
- * material.lightmapTexture as only diffuse lighting from this light
- * adds pnly specular lighting from this light
- * adds dynamic shadows
- */
- get: function () {
- return Light._LIGHTMAP_SPECULAR;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
- /**
- * material.lightmapTexture as only lighting
- * no light calculation from this light
- * only adds dynamic shadows from this light
- */
- get: function () {
- return Light._LIGHTMAP_SHADOWSONLY;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
- /**
- * Each light type uses the default quantity according to its type:
- * point/spot lights use luminous intensity
- * directional lights use illuminance
- */
- get: function () {
- return Light._INTENSITYMODE_AUTOMATIC;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
- /**
- * lumen (lm)
- */
- get: function () {
- return Light._INTENSITYMODE_LUMINOUSPOWER;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
- /**
- * candela (lm/sr)
- */
- get: function () {
- return Light._INTENSITYMODE_LUMINOUSINTENSITY;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
- /**
- * lux (lm/m^2)
- */
- get: function () {
- return Light._INTENSITYMODE_ILLUMINANCE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
- /**
- * nit (cd/m^2)
- */
- get: function () {
- return Light._INTENSITYMODE_LUMINANCE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
- /**
- * Light type const id of the point light.
- */
- get: function () {
- return Light._LIGHTTYPEID_POINTLIGHT;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
- /**
- * Light type const id of the directional light.
- */
- get: function () {
- return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
- /**
- * Light type const id of the spot light.
- */
- get: function () {
- return Light._LIGHTTYPEID_SPOTLIGHT;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
- /**
- * Light type const id of the hemispheric light.
- */
- get: function () {
- return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Light.prototype, "intensityMode", {
- /**
- * Gets the photometric scale used to interpret the intensity.
- * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
- */
- get: function () {
- return this._intensityMode;
- },
- /**
- * Sets the photometric scale used to interpret the intensity.
- * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
- */
- set: function (value) {
- this._intensityMode = value;
- this._computePhotometricScale();
- },
- enumerable: true,
- configurable: true
- });
- ;
- ;
- Object.defineProperty(Light.prototype, "radius", {
- /**
- * Gets the light radius used by PBR Materials to simulate soft area lights.
- */
- get: function () {
- return this._radius;
- },
- /**
- * sets the light radius used by PBR Materials to simulate soft area lights.
- */
- set: function (value) {
- this._radius = value;
- this._computePhotometricScale();
- },
- enumerable: true,
- configurable: true
- });
- ;
- ;
- Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
- get: function () {
- return this._includedOnlyMeshes;
- },
- set: function (value) {
- this._includedOnlyMeshes = value;
- this._hookArrayForIncludedOnly(value);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Light.prototype, "excludedMeshes", {
- get: function () {
- return this._excludedMeshes;
- },
- set: function (value) {
- this._excludedMeshes = value;
- this._hookArrayForExcluded(value);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
- get: function () {
- return this._excludeWithLayerMask;
- },
- set: function (value) {
- this._excludeWithLayerMask = value;
- this._resyncMeshes();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
- get: function () {
- return this._includeOnlyWithLayerMask;
- },
- set: function (value) {
- this._includeOnlyWithLayerMask = value;
- this._resyncMeshes();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Light.prototype, "lightmapMode", {
- get: function () {
- return this._lightmapMode;
- },
- set: function (value) {
- if (this._lightmapMode === value) {
- return;
- }
- this._lightmapMode = value;
- this._markMeshesAsLightDirty();
- },
- enumerable: true,
- configurable: true
- });
- Light.prototype._buildUniformLayout = function () {
- // Overridden
- };
- /**
- * Returns the string "Light".
- */
- Light.prototype.getClassName = function () {
- return "Light";
- };
- /**
- * @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;
- };
- /**
- * Set the enabled state of this node.
- * @param {boolean} value - the new enabled state
- * @see isEnabled
- */
- Light.prototype.setEnabled = function (value) {
- _super.prototype.setEnabled.call(this, value);
- this._resyncMeshes();
- };
- /**
- * Returns the Light associated shadow generator.
- */
- Light.prototype.getShadowGenerator = function () {
- return this._shadowGenerator;
- };
- /**
- * Returns a Vector3, the absolute light position in the World.
- */
- Light.prototype.getAbsolutePosition = function () {
- return BABYLON.Vector3.Zero();
- };
- Light.prototype.transferToEffect = function (effect, lightIndex) {
- };
- Light.prototype._getWorldMatrix = function () {
- return BABYLON.Matrix.Identity();
- };
- /**
- * Boolean : True if the light will affect the passed mesh.
- */
- Light.prototype.canAffectMesh = function (mesh) {
- if (!mesh) {
- return true;
- }
- if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
- return false;
- }
- if (this.excludedMeshes && 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;
- };
- /**
- * Returns the light World matrix.
- */
- 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;
- };
- /**
- * Sort function to order lights for rendering.
- * @param a First Light object to compare to second.
- * @param b Second Light object to compare first.
- * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
- */
- Light.compareLightsPriority = function (a, b) {
- //shadow-casting lights have priority over non-shadow-casting lights
- //the renderPrioirty is a secondary sort criterion
- if (a.shadowEnabled !== b.shadowEnabled) {
- return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
- }
- return b.renderPriority - a.renderPriority;
- };
- /**
- * Disposes the light.
- */
- Light.prototype.dispose = function () {
- if (this._shadowGenerator) {
- this._shadowGenerator.dispose();
- this._shadowGenerator = null;
- }
- // Animations
- this.getScene().stopAnimation(this);
- this._uniformBuffer.dispose();
- // Remove from scene
- this.getScene().removeLight(this);
- _super.prototype.dispose.call(this);
- };
- /**
- * Returns the light type ID (integer).
- */
- Light.prototype.getTypeID = function () {
- return 0;
- };
- /**
- * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
- */
- Light.prototype.getScaledIntensity = function () {
- return this._photometricScale * this.intensity;
- };
- /**
- * Returns a new Light object, named "name", from the current one.
- */
- Light.prototype.clone = function (name) {
- var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
- if (!constructor) {
- return null;
- }
- return BABYLON.SerializationHelper.Clone(constructor, this);
- };
- /**
- * Serializes the current light into a Serialization object.
- * Returns the serialized object.
- */
- 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;
- };
- /**
- * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
- * This new light is named "name" and added to the passed scene.
- */
- 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); };
- }
- return null;
- };
- /**
- * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
- */
- Light.Parse = function (parsedLight, scene) {
- var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
- if (!constructor) {
- return null;
- }
- var light = BABYLON.SerializationHelper.Parse(constructor, 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;
- };
- Light.prototype._hookArrayForExcluded = function (array) {
- var _this = this;
- var oldPush = array.push;
- array.push = function () {
- var items = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- items[_i] = arguments[_i];
- }
- var result = oldPush.apply(array, items);
- for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
- var item = items_1[_a];
- item._resyncLighSource(_this);
- }
- return result;
- };
- var oldSplice = array.splice;
- array.splice = function (index, deleteCount) {
- var deleted = oldSplice.apply(array, [index, deleteCount]);
- for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
- var item = deleted_1[_i];
- item._resyncLighSource(_this);
- }
- return deleted;
- };
- for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
- var item = array_1[_i];
- item._resyncLighSource(this);
- }
- };
- Light.prototype._hookArrayForIncludedOnly = function (array) {
- var _this = this;
- var oldPush = array.push;
- array.push = function () {
- var items = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- items[_i] = arguments[_i];
- }
- var result = oldPush.apply(array, items);
- _this._resyncMeshes();
- return result;
- };
- var oldSplice = array.splice;
- array.splice = function (index, deleteCount) {
- var deleted = oldSplice.apply(array, [index, deleteCount]);
- _this._resyncMeshes();
- return deleted;
- };
- this._resyncMeshes();
- };
- Light.prototype._resyncMeshes = function () {
- for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
- var mesh = _a[_i];
- mesh._resyncLighSource(this);
- }
- };
- Light.prototype._markMeshesAsLightDirty = function () {
- for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
- var mesh = _a[_i];
- if (mesh._lightSources.indexOf(this) !== -1) {
- mesh._markSubMeshesAsLightDirty();
- }
- }
- };
- /**
- * Recomputes the cached photometric scale if needed.
- */
- Light.prototype._computePhotometricScale = function () {
- this._photometricScale = this._getPhotometricScale();
- this.getScene().resetCachedMaterial();
- };
- /**
- * Returns the Photometric Scale according to the light type and intensity mode.
- */
- Light.prototype._getPhotometricScale = function () {
- var photometricScale = 0.0;
- var lightTypeID = this.getTypeID();
- //get photometric mode
- var photometricMode = this.intensityMode;
- if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
- if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
- photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
- }
- else {
- photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
- }
- }
- //compute photometric scale
- switch (lightTypeID) {
- case Light.LIGHTTYPEID_POINTLIGHT:
- case Light.LIGHTTYPEID_SPOTLIGHT:
- switch (photometricMode) {
- case Light.INTENSITYMODE_LUMINOUSPOWER:
- photometricScale = 1.0 / (4.0 * Math.PI);
- break;
- case Light.INTENSITYMODE_LUMINOUSINTENSITY:
- photometricScale = 1.0;
- break;
- case Light.INTENSITYMODE_LUMINANCE:
- photometricScale = this.radius * this.radius;
- break;
- }
- break;
- case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
- switch (photometricMode) {
- case Light.INTENSITYMODE_ILLUMINANCE:
- photometricScale = 1.0;
- break;
- case Light.INTENSITYMODE_LUMINANCE:
- // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
- // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
- var apexAngleRadians = this.radius;
- // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
- apexAngleRadians = Math.max(apexAngleRadians, 0.001);
- var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
- photometricScale = solidAngle;
- break;
- }
- break;
- case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
- // No fall off in hemisperic light.
- photometricScale = 1.0;
- break;
- }
- return photometricScale;
- };
- Light.prototype._reorderLightsInScene = function () {
- var scene = this.getScene();
- if (this._renderPriority != 0) {
- scene.requireLightSorting = true;
- }
- this.getScene().sortLightsByPriority();
- };
- //lightmapMode Consts
- Light._LIGHTMAP_DEFAULT = 0;
- Light._LIGHTMAP_SPECULAR = 1;
- Light._LIGHTMAP_SHADOWSONLY = 2;
- // Intensity Mode Consts
- Light._INTENSITYMODE_AUTOMATIC = 0;
- Light._INTENSITYMODE_LUMINOUSPOWER = 1;
- Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
- Light._INTENSITYMODE_ILLUMINANCE = 3;
- Light._INTENSITYMODE_LUMINANCE = 4;
- // Light types ids const.
- Light._LIGHTTYPEID_POINTLIGHT = 0;
- Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
- Light._LIGHTTYPEID_SPOTLIGHT = 2;
- Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
- __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, "intensityMode", null);
- __decorate([
- BABYLON.serialize()
- ], Light.prototype, "radius", null);
- __decorate([
- BABYLON.serialize()
- ], Light.prototype, "_renderPriority", void 0);
- __decorate([
- BABYLON.expandToProperty("_reorderLightsInScene")
- ], Light.prototype, "renderPriority", void 0);
- __decorate([
- BABYLON.serialize()
- ], Light.prototype, "shadowEnabled", void 0);
- __decorate([
- BABYLON.serialize("excludeWithLayerMask")
- ], Light.prototype, "_excludeWithLayerMask", void 0);
- __decorate([
- BABYLON.serialize("includeOnlyWithLayerMask")
- ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
- __decorate([
- BABYLON.serialize("lightmapMode")
- ], Light.prototype, "_lightmapMode", void 0);
- return Light;
- }(BABYLON.Node));
- BABYLON.Light = Light;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.light.js.map
- var BABYLON;
- (function (BABYLON) {
- var Camera = /** @class */ (function (_super) {
- __extends(Camera, _super);
- function Camera(name, position, scene) {
- var _this = _super.call(this, name, scene) || this;
- _this.upVector = BABYLON.Vector3.Up();
- _this.orthoLeft = null;
- _this.orthoRight = null;
- _this.orthoBottom = null;
- _this.orthoTop = null;
- /**
- * default : 0.8
- * FOV is set in Radians.
- */
- _this.fov = 0.8;
- _this.minZ = 1;
- _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);
- /**
- * Restricts the camera to viewing objects with the same layerMask.
- * A camera with a layerMask of 1 will render meshes with no layerMask and meshes with a layerMask of 1.
- */
- _this.layerMask = 0x0FFFFFFF;
- /**
- * default : FOVMODE_VERTICAL_FIXED
- * fovMode sets the camera frustum bounds to the viewport bounds.
- */
- _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
- // Camera rig members
- _this.cameraRigMode = Camera.RIG_MODE_NONE;
- _this._rigCameras = new Array();
- _this._webvrViewMatrix = BABYLON.Matrix.Identity();
- _this._skipRendering = false;
- _this.customRenderTargets = new Array();
- // Observables
- _this.onViewMatrixChangedObservable = new BABYLON.Observable();
- _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
- _this.onAfterCheckInputsObservable = new BABYLON.Observable();
- _this.onRestoreStateObservable = new BABYLON.Observable();
- // Cache
- _this._computedViewMatrix = BABYLON.Matrix.Identity();
- _this._projectionMatrix = new BABYLON.Matrix();
- _this._doNotComputeProjectionMatrix = false;
- _this._postProcesses = new Array();
- _this._transformMatrix = BABYLON.Matrix.Zero();
- _this._activeMeshes = new BABYLON.SmartArray(256);
- _this._globalPosition = BABYLON.Vector3.Zero();
- _this._refreshFrustumPlanes = true;
- _this.getScene().addCamera(_this);
- if (!_this.getScene().activeCamera) {
- _this.getScene().activeCamera = _this;
- }
- _this.position = position;
- return _this;
- }
- 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", {
- /**
- * This is the default FOV mode for perspective cameras.
- * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
- *
- */
- get: function () {
- return Camera._FOVMODE_VERTICAL_FIXED;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
- /**
- * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
- *
- */
- 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
- });
- Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
- get: function () {
- return Camera._RIG_MODE_WEBVR;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Store current camera state (fov, position, etc..)
- */
- Camera.prototype.storeState = function () {
- this._stateStored = true;
- this._storedFov = this.fov;
- return this;
- };
- /**
- * Restores the camera state values if it has been stored. You must call storeState() first
- */
- Camera.prototype._restoreStateValues = function () {
- if (!this._stateStored) {
- return false;
- }
- this.fov = this._storedFov;
- return true;
- };
- /**
- * Restored camera state. You must call storeState() first
- */
- Camera.prototype.restoreState = function () {
- if (this._restoreStateValues()) {
- this.onRestoreStateObservable.notifyObservers(this);
- return true;
- }
- return false;
- };
- Camera.prototype.getClassName = function () {
- return "Camera";
- };
- /**
- * @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.getClassName();
- 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.fovMode = 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);
- }
- this._cache.position.copyFrom(this.position);
- this._cache.upVector.copyFrom(this.upVector);
- };
- // 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.fovMode === this.fovMode
- && 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 () {
- this._checkInputs();
- if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
- this._updateRigCameras();
- }
- };
- Camera.prototype._checkInputs = function () {
- this.onAfterCheckInputsObservable.notifyObservers(this);
- };
- Object.defineProperty(Camera.prototype, "rigCameras", {
- get: function () {
- return this._rigCameras;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Camera.prototype, "rigPostProcess", {
- get: function () {
- return this._rigPostProcess;
- },
- enumerable: true,
- configurable: true
- });
- Camera.prototype._cascadePostProcessesToRigCams = function () {
- // invalidate framebuffer
- if (this._postProcesses.length > 0) {
- this._postProcesses[0].markTextureDirty();
- }
- // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
- for (var i = 0, len = this._rigCameras.length; i < len; i++) {
- var cam = this._rigCameras[i];
- var rigPostProcess = cam._rigPostProcess;
- // for VR rig, there does not have to be a post process
- if (rigPostProcess) {
- var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
- if (isPass) {
- // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
- cam.isIntermediate = this._postProcesses.length === 0;
- }
- cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
- rigPostProcess.markTextureDirty();
- }
- else {
- cam._postProcesses = this._postProcesses.slice(0);
- }
- }
- };
- 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);
- }
- else {
- this._postProcesses.splice(insertAt, 0, postProcess);
- }
- this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
- return this._postProcesses.indexOf(postProcess);
- };
- Camera.prototype.detachPostProcess = function (postProcess) {
- var idx = this._postProcesses.indexOf(postProcess);
- if (idx !== -1) {
- this._postProcesses.splice(idx, 1);
- }
- this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
- };
- 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) {
- if (!force && this._isSynchronizedViewMatrix()) {
- return this._computedViewMatrix;
- }
- this.updateCache();
- this._computedViewMatrix = this._getViewMatrix();
- this._currentRenderId = this.getScene().getRenderId();
- this._refreshFrustumPlanes = true;
- 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();
- }
- if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
- this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
- }
- this.onViewMatrixChangedObservable.notifyObservers(this);
- return this._computedViewMatrix;
- };
- Camera.prototype.freezeProjectionMatrix = function (projection) {
- this._doNotComputeProjectionMatrix = true;
- if (projection !== undefined) {
- this._projectionMatrix = projection;
- }
- };
- ;
- Camera.prototype.unfreezeProjectionMatrix = function () {
- this._doNotComputeProjectionMatrix = false;
- };
- ;
- Camera.prototype.getProjectionMatrix = function (force) {
- if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
- return this._projectionMatrix;
- }
- // Cache
- this._cache.mode = this.mode;
- this._cache.minZ = this.minZ;
- this._cache.maxZ = this.maxZ;
- // Matrix
- this._refreshFrustumPlanes = true;
- var engine = this.getEngine();
- var scene = this.getScene();
- if (this.mode === Camera.PERSPECTIVE_CAMERA) {
- this._cache.fov = this.fov;
- this._cache.fovMode = this.fovMode;
- this._cache.aspectRatio = engine.getAspectRatio(this);
- if (this.minZ <= 0) {
- this.minZ = 0.1;
- }
- if (scene.useRightHandedSystem) {
- BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
- }
- else {
- BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
- }
- }
- else {
- var halfWidth = engine.getRenderWidth() / 2.0;
- var halfHeight = engine.getRenderHeight() / 2.0;
- if (scene.useRightHandedSystem) {
- BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
- }
- else {
- BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
- }
- 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();
- }
- this.onProjectionMatrixChangedObservable.notifyObservers(this);
- return this._projectionMatrix;
- };
- Camera.prototype.getTranformationMatrix = function () {
- this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
- return this._transformMatrix;
- };
- Camera.prototype.updateFrustumPlanes = function () {
- if (!this._refreshFrustumPlanes) {
- return;
- }
- this.getTranformationMatrix();
- if (!this._frustumPlanes) {
- this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
- }
- else {
- BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
- }
- this._refreshFrustumPlanes = false;
- };
- Camera.prototype.isInFrustum = function (target) {
- this.updateFrustumPlanes();
- return target.isInFrustum(this._frustumPlanes);
- };
- Camera.prototype.isCompletelyInFrustum = function (target) {
- this.updateFrustumPlanes();
- return target.isCompletelyInFrustum(this._frustumPlanes);
- };
- Camera.prototype.getForwardRay = function (length, transform, origin) {
- if (length === void 0) { length = 100; }
- if (!transform) {
- transform = this.getWorldMatrix();
- }
- if (!origin) {
- origin = this.position;
- }
- var forward = new BABYLON.Vector3(0, 0, 1);
- var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
- var direction = BABYLON.Vector3.Normalize(forwardWorld);
- return new BABYLON.Ray(origin, direction, length);
- };
- Camera.prototype.dispose = function () {
- // Observables
- this.onViewMatrixChangedObservable.clear();
- this.onProjectionMatrixChangedObservable.clear();
- this.onAfterCheckInputsObservable.clear();
- this.onRestoreStateObservable.clear();
- // Inputs
- if (this.inputs) {
- this.inputs.clear();
- }
- // Animations
- this.getScene().stopAnimation(this);
- // Remove from scene
- this.getScene().removeCamera(this);
- while (this._rigCameras.length > 0) {
- var camera = this._rigCameras.pop();
- if (camera) {
- camera.dispose();
- }
- }
- // Postprocesses
- if (this._rigPostProcess) {
- this._rigPostProcess.dispose(this);
- this._rigPostProcess = null;
- this._postProcesses = [];
- }
- else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
- this._rigPostProcess = null;
- this._postProcesses = [];
- }
- else {
- var i = this._postProcesses.length;
- while (--i >= 0) {
- this._postProcesses[i].dispose(this);
- }
- }
- // Render targets
- var i = this.customRenderTargets.length;
- while (--i >= 0) {
- this.customRenderTargets[i].dispose();
- }
- this.customRenderTargets = [];
- // Active Meshes
- this._activeMeshes.dispose();
- _super.prototype.dispose.call(this);
- };
- Object.defineProperty(Camera.prototype, "leftCamera", {
- // ---- Camera rigs section ----
- get: function () {
- if (this._rigCameras.length < 1) {
- return null;
- }
- return this._rigCameras[0];
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Camera.prototype, "rightCamera", {
- get: function () {
- if (this._rigCameras.length < 2) {
- return null;
- }
- return this._rigCameras[1];
- },
- enumerable: true,
- configurable: true
- });
- Camera.prototype.getLeftTarget = function () {
- if (this._rigCameras.length < 1) {
- return null;
- }
- return this._rigCameras[0].getTarget();
- };
- Camera.prototype.getRightTarget = function () {
- if (this._rigCameras.length < 2) {
- return null;
- }
- return this._rigCameras[1].getTarget();
- };
- Camera.prototype.setCameraRigMode = function (mode, rigParams) {
- if (this.cameraRigMode === mode) {
- return;
- }
- while (this._rigCameras.length > 0) {
- var camera = this._rigCameras.pop();
- if (camera) {
- camera.dispose();
- }
- }
- this.cameraRigMode = mode;
- this._cameraRigParams = {};
- //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.interaxialDistance = rigParams.interaxialDistance || 0.0637;
- this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
- // create the rig cameras, unless none
- if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
- var leftCamera = this.createRigCamera(this.name + "_L", 0);
- var rightCamera = this.createRigCamera(this.name + "_R", 1);
- if (leftCamera && rightCamera) {
- this._rigCameras.push(leftCamera);
- this._rigCameras.push(rightCamera);
- }
- }
- switch (this.cameraRigMode) {
- case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
- this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
- this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
- 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;
- this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
- this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
- break;
- case Camera.RIG_MODE_VR:
- 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;
- this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
- 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) {
- this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
- this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
- }
- break;
- case Camera.RIG_MODE_WEBVR:
- if (rigParams.vrDisplay) {
- var leftEye = rigParams.vrDisplay.getEyeParameters('left');
- var rightEye = rigParams.vrDisplay.getEyeParameters('right');
- //Left eye
- this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
- this._rigCameras[0].setCameraRigParameter("left", true);
- //leaving this for future reference
- this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
- this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
- this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
- this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
- this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
- this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
- this._rigCameras[0].parent = this;
- this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
- //Right eye
- this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
- this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
- this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
- this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
- this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
- this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
- this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
- this._rigCameras[1].parent = this;
- this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
- if (Camera.UseAlternateWebVRRendering) {
- this._rigCameras[1]._skipRendering = true;
- this._rigCameras[0]._alternateCamera = this._rigCameras[1];
- }
- }
- break;
- }
- this._cascadePostProcessesToRigCams();
- 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._updateCameraRotationMatrix = function () {
- //Here for WebVR
- };
- Camera.prototype._updateWebVRCameraRotationMatrix = function () {
- //Here for WebVR
- };
- /**
- * This function MUST be overwritten by the different WebVR cameras available.
- * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
- */
- Camera.prototype._getWebVRProjectionMatrix = function () {
- return BABYLON.Matrix.Identity();
- };
- /**
- * This function MUST be overwritten by the different WebVR cameras available.
- * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
- */
- Camera.prototype._getWebVRViewMatrix = function () {
- return BABYLON.Matrix.Identity();
- };
- Camera.prototype.setCameraRigParameter = function (name, value) {
- if (!this._cameraRigParams) {
- this._cameraRigParams = {};
- }
- this._cameraRigParams[name] = value;
- //provisionnally:
- if (name === "interaxialDistance") {
- this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
- }
- };
- /**
- * needs to be overridden by children so sub has required properties to be copied
- */
- Camera.prototype.createRigCamera = function (name, cameraIndex) {
- return null;
- };
- /**
- * May need 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.getClassName();
- // 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.clone = function (name) {
- return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
- };
- Camera.prototype.getDirection = function (localAxis) {
- var result = BABYLON.Vector3.Zero();
- this.getDirectionToRef(localAxis, result);
- return result;
- };
- Camera.prototype.getDirectionToRef = function (localAxis, result) {
- BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
- };
- 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 "WebVRGamepadCamera":
- 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 "VRDeviceOrientationGamepadCamera":
- return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(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":// Forcing Universal here
- return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
- default:// Universal Camera is the default value
- return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
- }
- };
- Camera.prototype.computeWorldMatrix = function () {
- return this.getWorldMatrix();
- };
- 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();
- }
- if (camera.setPosition) {
- camera.position.copyFromFloats(0, 0, 0);
- camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
- }
- // 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._RIG_MODE_WEBVR = 21;
- Camera.ForceAttachControlToAlwaysPreventDefault = false;
- Camera.UseAlternateWebVRRendering = 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 = {}));
- //# sourceMappingURL=babylon.camera.js.map
- var BABYLON;
- (function (BABYLON) {
- var RenderingManager = /** @class */ (function () {
- function RenderingManager(scene) {
- this._renderingGroups = new Array();
- this._autoClearDepthStencil = {};
- this._customOpaqueSortCompareFn = {};
- this._customAlphaTestSortCompareFn = {};
- this._customTransparentSortCompareFn = {};
- this._renderinGroupInfo = null;
- this._scene = scene;
- for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
- this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
- }
- }
- RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
- if (depth === void 0) { depth = true; }
- if (stencil === void 0) { stencil = true; }
- if (this._depthStencilBufferAlreadyCleaned) {
- return;
- }
- this._scene.getEngine().clear(null, false, depth, stencil);
- this._depthStencilBufferAlreadyCleaned = true;
- };
- RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
- // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
- var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
- var info = null;
- if (observable) {
- if (!this._renderinGroupInfo) {
- this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
- }
- info = this._renderinGroupInfo;
- info.scene = this._scene;
- info.camera = this._scene.activeCamera;
- }
- // Dispatch sprites
- if (renderSprites) {
- for (var index = 0; index < this._scene.spriteManagers.length; index++) {
- var manager = this._scene.spriteManagers[index];
- this.dispatchSprites(manager);
- }
- }
- // Render
- for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
- this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
- var renderingGroup = this._renderingGroups[index];
- if (!renderingGroup && !observable)
- continue;
- var renderingGroupMask = 0;
- // Fire PRECLEAR stage
- if (observable && info) {
- renderingGroupMask = Math.pow(2, index);
- info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
- info.renderingGroupId = index;
- observable.notifyObservers(info, renderingGroupMask);
- }
- // Clear depth/stencil if needed
- if (RenderingManager.AUTOCLEAR) {
- var autoClear = this._autoClearDepthStencil[index];
- if (autoClear && autoClear.autoClear) {
- this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
- }
- }
- if (observable && info) {
- // Fire PREOPAQUE stage
- info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
- observable.notifyObservers(info, renderingGroupMask);
- // Fire PRETRANSPARENT stage
- info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
- observable.notifyObservers(info, renderingGroupMask);
- }
- if (renderingGroup)
- renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
- // Fire POSTTRANSPARENT stage
- if (observable && info) {
- info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
- observable.notifyObservers(info, renderingGroupMask);
- }
- }
- };
- RenderingManager.prototype.reset = function () {
- for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
- var renderingGroup = this._renderingGroups[index];
- if (renderingGroup) {
- renderingGroup.prepare();
- }
- }
- };
- RenderingManager.prototype.dispose = function () {
- for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
- var renderingGroup = this._renderingGroups[index];
- if (renderingGroup) {
- renderingGroup.dispose();
- }
- }
- this._renderingGroups.length = 0;
- };
- RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
- if (this._renderingGroups[renderingGroupId] === undefined) {
- this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
- }
- };
- RenderingManager.prototype.dispatchSprites = function (spriteManager) {
- var renderingGroupId = spriteManager.renderingGroupId || 0;
- this._prepareRenderingGroup(renderingGroupId);
- this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
- };
- RenderingManager.prototype.dispatchParticles = function (particleSystem) {
- var renderingGroupId = particleSystem.renderingGroupId || 0;
- this._prepareRenderingGroup(renderingGroupId);
- this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
- };
- /**
- * @param subMesh The submesh to dispatch
- * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
- * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
- */
- RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
- if (mesh === undefined) {
- mesh = subMesh.getMesh();
- }
- var renderingGroupId = mesh.renderingGroupId || 0;
- this._prepareRenderingGroup(renderingGroupId);
- this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
- };
- /**
- * Overrides the default sort function applied in the renderging group to prepare the meshes.
- * This allowed control for front to back rendering or reversly depending of the special needs.
- *
- * @param renderingGroupId The rendering group id corresponding to its index
- * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
- * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
- * @param transparentSortCompareFn The transparent queue comparison function use to sort.
- */
- RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
- if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
- if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
- if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
- this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
- this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
- this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
- if (this._renderingGroups[renderingGroupId]) {
- var group = this._renderingGroups[renderingGroupId];
- group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
- group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
- group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
- }
- };
- /**
- * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
- *
- * @param renderingGroupId The rendering group id corresponding to its index
- * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
- * @param depth Automatically clears depth between groups if true and autoClear is true.
- * @param stencil Automatically clears stencil between groups if true and autoClear is true.
- */
- RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
- if (depth === void 0) { depth = true; }
- if (stencil === void 0) { stencil = true; }
- this._autoClearDepthStencil[renderingGroupId] = {
- autoClear: autoClearDepthStencil,
- depth: depth,
- stencil: stencil
- };
- };
- /**
- * The max id used for rendering groups (not included)
- */
- RenderingManager.MAX_RENDERINGGROUPS = 4;
- /**
- * The min id used for rendering groups (included)
- */
- RenderingManager.MIN_RENDERINGGROUPS = 0;
- /**
- * Used to globally prevent autoclearing scenes.
- */
- RenderingManager.AUTOCLEAR = true;
- return RenderingManager;
- }());
- BABYLON.RenderingManager = RenderingManager;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.renderingManager.js.map
- var BABYLON;
- (function (BABYLON) {
- var RenderingGroup = /** @class */ (function () {
- /**
- * Creates a new rendering group.
- * @param index The rendering group index
- * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
- * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
- * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
- */
- function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
- if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
- if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
- if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
- this.index = index;
- this._opaqueSubMeshes = new BABYLON.SmartArray(256);
- this._transparentSubMeshes = new BABYLON.SmartArray(256);
- this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
- this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
- this._particleSystems = new BABYLON.SmartArray(256);
- this._spriteManagers = new BABYLON.SmartArray(256);
- this._edgesRenderers = new BABYLON.SmartArray(16);
- this._scene = scene;
- this.opaqueSortCompareFn = opaqueSortCompareFn;
- this.alphaTestSortCompareFn = alphaTestSortCompareFn;
- this.transparentSortCompareFn = transparentSortCompareFn;
- }
- Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
- /**
- * Set the opaque sort comparison function.
- * If null the sub meshes will be render in the order they were created
- */
- set: function (value) {
- this._opaqueSortCompareFn = value;
- if (value) {
- this._renderOpaque = this.renderOpaqueSorted;
- }
- else {
- this._renderOpaque = RenderingGroup.renderUnsorted;
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
- /**
- * Set the alpha test sort comparison function.
- * If null the sub meshes will be render in the order they were created
- */
- set: function (value) {
- this._alphaTestSortCompareFn = value;
- if (value) {
- this._renderAlphaTest = this.renderAlphaTestSorted;
- }
- else {
- this._renderAlphaTest = RenderingGroup.renderUnsorted;
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
- /**
- * Set the transparent sort comparison function.
- * If null the sub meshes will be render in the order they were created
- */
- set: function (value) {
- if (value) {
- this._transparentSortCompareFn = value;
- }
- else {
- this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
- }
- this._renderTransparent = this.renderTransparentSorted;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Render all the sub meshes contained in the group.
- * @param customRenderFunction Used to override the default render behaviour of the group.
- * @returns true if rendered some submeshes.
- */
- RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
- if (customRenderFunction) {
- customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
- return;
- }
- var engine = this._scene.getEngine();
- // Depth only
- if (this._depthOnlySubMeshes.length !== 0) {
- engine.setAlphaTesting(true);
- engine.setColorWrite(false);
- this._renderAlphaTest(this._depthOnlySubMeshes);
- engine.setAlphaTesting(false);
- engine.setColorWrite(true);
- }
- // Opaque
- if (this._opaqueSubMeshes.length !== 0) {
- this._renderOpaque(this._opaqueSubMeshes);
- }
- // Alpha test
- if (this._alphaTestSubMeshes.length !== 0) {
- engine.setAlphaTesting(true);
- this._renderAlphaTest(this._alphaTestSubMeshes);
- engine.setAlphaTesting(false);
- }
- var stencilState = engine.getStencilBuffer();
- engine.setStencilBuffer(false);
- // Sprites
- if (renderSprites) {
- this._renderSprites();
- }
- // Particles
- if (renderParticles) {
- this._renderParticles(activeMeshes);
- }
- if (this.onBeforeTransparentRendering) {
- this.onBeforeTransparentRendering();
- }
- // Transparent
- if (this._transparentSubMeshes.length !== 0) {
- this._renderTransparent(this._transparentSubMeshes);
- engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
- }
- // Set back stencil to false in case it changes before the edge renderer.
- engine.setStencilBuffer(false);
- // Edges
- for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
- this._edgesRenderers.data[edgesRendererIndex].render();
- }
- // Restore Stencil state.
- engine.setStencilBuffer(stencilState);
- };
- /**
- * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
- * @param subMeshes The submeshes to render
- */
- RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
- return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
- };
- /**
- * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
- * @param subMeshes The submeshes to render
- */
- RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
- return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
- };
- /**
- * Renders the opaque submeshes in the order from the transparentSortCompareFn.
- * @param subMeshes The submeshes to render
- */
- RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
- return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
- };
- /**
- * Renders the submeshes in a specified order.
- * @param subMeshes The submeshes to sort before render
- * @param sortCompareFn The comparison function use to sort
- * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
- * @param transparent Specifies to activate blending if true
- */
- RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
- var subIndex = 0;
- var subMesh;
- var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
- for (; subIndex < subMeshes.length; subIndex++) {
- subMesh = subMeshes.data[subIndex];
- subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
- subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
- }
- var sortedArray = subMeshes.data.slice(0, subMeshes.length);
- if (sortCompareFn) {
- sortedArray.sort(sortCompareFn);
- }
- for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
- subMesh = sortedArray[subIndex];
- if (transparent) {
- var material = subMesh.getMaterial();
- if (material && material.needDepthPrePass) {
- var engine = material.getScene().getEngine();
- engine.setColorWrite(false);
- engine.setAlphaTesting(true);
- engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
- subMesh.render(false);
- engine.setAlphaTesting(false);
- engine.setColorWrite(true);
- }
- }
- subMesh.render(transparent);
- }
- };
- /**
- * Renders the submeshes in the order they were dispatched (no sort applied).
- * @param subMeshes The submeshes to render
- */
- RenderingGroup.renderUnsorted = function (subMeshes) {
- for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
- var submesh = subMeshes.data[subIndex];
- submesh.render(false);
- }
- };
- /**
- * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
- * are rendered back to front if in the same alpha index.
- *
- * @param a The first submesh
- * @param b The second submesh
- * @returns The result of the comparison
- */
- RenderingGroup.defaultTransparentSortCompare = function (a, b) {
- // Alpha index first
- if (a._alphaIndex > b._alphaIndex) {
- return 1;
- }
- if (a._alphaIndex < b._alphaIndex) {
- return -1;
- }
- // Then distance to camera
- return RenderingGroup.backToFrontSortCompare(a, b);
- };
- /**
- * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
- * are rendered back to front.
- *
- * @param a The first submesh
- * @param b The second submesh
- * @returns The result of the comparison
- */
- RenderingGroup.backToFrontSortCompare = function (a, b) {
- // Then distance to camera
- if (a._distanceToCamera < b._distanceToCamera) {
- return 1;
- }
- if (a._distanceToCamera > b._distanceToCamera) {
- return -1;
- }
- return 0;
- };
- /**
- * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
- * are rendered front to back (prevent overdraw).
- *
- * @param a The first submesh
- * @param b The second submesh
- * @returns The result of the comparison
- */
- RenderingGroup.frontToBackSortCompare = function (a, b) {
- // Then distance to camera
- if (a._distanceToCamera < b._distanceToCamera) {
- return -1;
- }
- if (a._distanceToCamera > b._distanceToCamera) {
- return 1;
- }
- return 0;
- };
- /**
- * Resets the different lists of submeshes to prepare a new frame.
- */
- RenderingGroup.prototype.prepare = function () {
- this._opaqueSubMeshes.reset();
- this._transparentSubMeshes.reset();
- this._alphaTestSubMeshes.reset();
- this._depthOnlySubMeshes.reset();
- this._particleSystems.reset();
- this._spriteManagers.reset();
- this._edgesRenderers.reset();
- };
- RenderingGroup.prototype.dispose = function () {
- this._opaqueSubMeshes.dispose();
- this._transparentSubMeshes.dispose();
- this._alphaTestSubMeshes.dispose();
- this._depthOnlySubMeshes.dispose();
- this._particleSystems.dispose();
- this._spriteManagers.dispose();
- this._edgesRenderers.dispose();
- };
- /**
- * Inserts the submesh in its correct queue depending on its material.
- * @param subMesh The submesh to dispatch
- * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
- * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
- */
- RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
- // Get mesh and materials if not provided
- if (mesh === undefined) {
- mesh = subMesh.getMesh();
- }
- if (material === undefined) {
- material = subMesh.getMaterial();
- }
- if (material === null || material === undefined) {
- return;
- }
- if (material.needAlphaBlendingForMesh(mesh)) {
- this._transparentSubMeshes.push(subMesh);
- }
- else if (material.needAlphaTesting()) {
- if (material.needDepthPrePass) {
- this._depthOnlySubMeshes.push(subMesh);
- }
- this._alphaTestSubMeshes.push(subMesh);
- }
- else {
- if (material.needDepthPrePass) {
- this._depthOnlySubMeshes.push(subMesh);
- }
- this._opaqueSubMeshes.push(subMesh); // Opaque
- }
- if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
- this._edgesRenderers.push(mesh._edgesRenderer);
- }
- };
- RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
- this._spriteManagers.push(spriteManager);
- };
- RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
- this._particleSystems.push(particleSystem);
- };
- RenderingGroup.prototype._renderParticles = function (activeMeshes) {
- if (this._particleSystems.length === 0) {
- return;
- }
- // Particles
- var activeCamera = this._scene.activeCamera;
- this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
- for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
- var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
- if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
- continue;
- }
- var emitter = particleSystem.emitter;
- if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
- this._scene._activeParticles.addCount(particleSystem.render(), false);
- }
- }
- this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
- };
- RenderingGroup.prototype._renderSprites = function () {
- if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
- return;
- }
- // Sprites
- var activeCamera = this._scene.activeCamera;
- this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
- for (var id = 0; id < this._spriteManagers.length; id++) {
- var spriteManager = this._spriteManagers.data[id];
- if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
- spriteManager.render();
- }
- }
- this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
- };
- return RenderingGroup;
- }());
- BABYLON.RenderingGroup = RenderingGroup;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.renderingGroup.js.map
- var BABYLON;
- (function (BABYLON) {
- var ClickInfo = /** @class */ (function () {
- function ClickInfo() {
- this._singleClick = false;
- this._doubleClick = false;
- this._hasSwiped = false;
- this._ignore = false;
- }
- Object.defineProperty(ClickInfo.prototype, "singleClick", {
- get: function () {
- return this._singleClick;
- },
- set: function (b) {
- this._singleClick = b;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ClickInfo.prototype, "doubleClick", {
- get: function () {
- return this._doubleClick;
- },
- set: function (b) {
- this._doubleClick = b;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
- get: function () {
- return this._hasSwiped;
- },
- set: function (b) {
- this._hasSwiped = b;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ClickInfo.prototype, "ignore", {
- get: function () {
- return this._ignore;
- },
- set: function (b) {
- this._ignore = b;
- },
- enumerable: true,
- configurable: true
- });
- return ClickInfo;
- }());
- /**
- * This class is used by the onRenderingGroupObservable
- */
- var RenderingGroupInfo = /** @class */ (function () {
- function RenderingGroupInfo() {
- }
- /**
- * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
- * This stage will be fired no matter what
- */
- RenderingGroupInfo.STAGE_PRECLEAR = 1;
- /**
- * Called before opaque object are rendered.
- * This stage will be fired only if there's 3D Opaque content to render
- */
- RenderingGroupInfo.STAGE_PREOPAQUE = 2;
- /**
- * Called after the opaque objects are rendered and before the transparent ones
- * This stage will be fired only if there's 3D transparent content to render
- */
- RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
- /**
- * Called after the transparent object are rendered, last hook of the renderingGroup phase
- * This stage will be fired no matter what
- */
- RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
- return RenderingGroupInfo;
- }());
- BABYLON.RenderingGroupInfo = RenderingGroupInfo;
- /**
- * Represents a scene to be rendered by the engine.
- * @see http://doc.babylonjs.com/page.php?p=21911
- */
- var Scene = /** @class */ (function () {
- /**
- * @constructor
- * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
- */
- function Scene(engine) {
- // Members
- this.autoClear = true;
- this.autoClearDepthAndStencil = true;
- this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
- this.ambientColor = new BABYLON.Color3(0, 0, 0);
- this.forceWireframe = false;
- this._forcePointsCloud = false;
- this.forceShowBoundingBoxes = false;
- this.animationsEnabled = true;
- this.useConstantAnimationDeltaTime = false;
- this.constantlyUpdateMeshUnderPointer = false;
- this.hoverCursor = "pointer";
- this.defaultCursor = "";
- /**
- * This is used to call preventDefault() on pointer down
- * in order to block unwanted artifacts like system double clicks
- */
- this.preventDefaultOnPointerDown = true;
- // Metadata
- this.metadata = null;
- /**
- * An event triggered when the scene is disposed.
- * @type {BABYLON.Observable}
- */
- this.onDisposeObservable = new BABYLON.Observable();
- /**
- * An event triggered before rendering the scene (right after animations and physics)
- * @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 before animating the scene
- * @type {BABYLON.Observable}
- */
- this.onBeforeAnimationsObservable = new BABYLON.Observable();
- /**
- * An event triggered after animations processing
- * @type {BABYLON.Observable}
- */
- this.onAfterAnimationsObservable = new BABYLON.Observable();
- /**
- * An event triggered before draw calls are ready to be sent
- * @type {BABYLON.Observable}
- */
- this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
- /**
- * An event triggered after draw calls have been sent
- * @type {BABYLON.Observable}
- */
- this.onAfterDrawPhaseObservable = new BABYLON.Observable();
- /**
- * An event triggered when physic simulation is about to be run
- * @type {BABYLON.Observable}
- */
- this.onBeforePhysicsObservable = new BABYLON.Observable();
- /**
- * An event triggered when physic simulation has been done
- * @type {BABYLON.Observable}
- */
- this.onAfterPhysicsObservable = 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 active meshes evaluation is about to start
- * @type {BABYLON.Observable}
- */
- this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
- /**
- * An event triggered when active meshes evaluation is done
- * @type {BABYLON.Observable}
- */
- this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
- /**
- * An event triggered when particles rendering is about to start
- * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
- * @type {BABYLON.Observable}
- */
- this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
- /**
- * An event triggered when particles rendering is done
- * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
- * @type {BABYLON.Observable}
- */
- this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
- /**
- * An event triggered when sprites rendering is about to start
- * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
- * @type {BABYLON.Observable}
- */
- this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
- /**
- * An event triggered when sprites rendering is done
- * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
- * @type {BABYLON.Observable}
- */
- this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
- /**
- * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
- * @type {BABYLON.Observable}
- */
- this.onDataLoadedObservable = 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 transform node is created
- * @type {BABYLON.Observable}
- */
- this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
- /**
- * An event triggered when a transform node is removed
- * @type {BABYLON.Observable}
- */
- this.onTransformNodeRemovedObservable = 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();
- /**
- * An event triggered when render targets are about to be rendered
- * Can happen multiple times per frame.
- * @type {BABYLON.Observable}
- */
- this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
- /**
- * An event triggered when render targets were rendered.
- * Can happen multiple times per frame.
- * @type {BABYLON.Observable}
- */
- this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
- /**
- * An event triggered before calculating deterministic simulation step
- * @type {BABYLON.Observable}
- */
- this.onBeforeStepObservable = new BABYLON.Observable();
- /**
- * An event triggered after calculating deterministic simulation step
- * @type {BABYLON.Observable}
- */
- this.onAfterStepObservable = new BABYLON.Observable();
- /**
- * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
- * The RenderinGroupInfo class contains all the information about the context in which the observable is called
- * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3)
- */
- this.onRenderingGroupObservable = new BABYLON.Observable();
- // Animations
- this.animations = [];
- /**
- * This observable event is triggered when any ponter event is triggered. It is registered during Scene.attachControl() and it is called BEFORE the 3D engine process anything (mesh/sprite picking for instance).
- * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
- */
- this.onPrePointerObservable = new BABYLON.Observable();
- /**
- * Observable event triggered each time an input event is received from the rendering canvas
- */
- this.onPointerObservable = new BABYLON.Observable();
- this._meshPickProceed = false;
- this._currentPickResult = null;
- this._previousPickResult = null;
- this._totalPointersPressed = 0;
- this._doubleClickOccured = false;
- /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
- this.cameraToUseForPointers = null;
- this._startingPointerPosition = new BABYLON.Vector2(0, 0);
- this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
- this._startingPointerTime = 0;
- this._previousStartingPointerTime = 0;
- // Deterministic lockstep
- this._timeAccumulator = 0;
- this._currentStepId = 0;
- this._currentInternalStep = 0;
- // Keyboard
- /**
- * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
- * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
- */
- this.onPreKeyboardObservable = new BABYLON.Observable();
- /**
- * Observable event triggered each time an keyboard event is received from the hosting window
- */
- this.onKeyboardObservable = new BABYLON.Observable();
- // Coordinate system
- /**
- * use right-handed coordinate system on this scene.
- * @type {boolean}
- */
- this._useRightHandedSystem = false;
- // Fog
- 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. */
- this.cameras = new Array();
- /** All of the active cameras added to this scene. */
- this.activeCameras = new Array();
- // Meshes
- /**
- * All of the tranform nodes added to this scene.
- * @see BABYLON.TransformNode
- * @type {BABYLON.TransformNode[]}
- */
- this.transformNodes = new Array();
- /**
- * All of the (abstract) meshes added to this scene.
- * @see BABYLON.AbstractMesh
- * @type {BABYLON.AbstractMesh[]}
- */
- this.meshes = new Array();
- /**
- * All of the animation groups added to this scene.
- * @see BABYLON.AnimationGroup
- * @type {BABYLON.AnimationGroup[]}
- */
- this.animationGroups = new Array();
- // Geometries
- this._geometries = new Array();
- this.materials = new Array();
- this.multiMaterials = new Array();
- // 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();
- this.highlightLayers = new Array();
- // Skeletons
- this._skeletonsEnabled = true;
- this.skeletons = new Array();
- // Morph targets
- this.morphTargetManagers = new Array();
- // Lens flares
- this.lensFlaresEnabled = true;
- this.lensFlareSystems = new Array();
- // Collisions
- this.collisionsEnabled = true;
- /** Defines the gravity applied to this scene */
- this.gravity = new BABYLON.Vector3(0, -9.807, 0);
- // Postprocesses
- this.postProcesses = new Array();
- 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.SmartArrayNoDuplicate(256);
- // Procedural textures
- this.proceduralTexturesEnabled = true;
- this._proceduralTextures = new Array();
- this.soundTracks = new Array();
- this._audioEnabled = true;
- this._headphone = false;
- // Performance counters
- this._totalVertices = new BABYLON.PerfCounter();
- this._activeIndices = new BABYLON.PerfCounter();
- this._activeParticles = new BABYLON.PerfCounter();
- this._activeBones = new BABYLON.PerfCounter();
- this._animationTime = 0;
- this.animationTimeScale = 1;
- this._renderId = 0;
- this._executeWhenReadyTimeoutId = -1;
- this._intermediateRendering = false;
- this._viewUpdateFlag = -1;
- this._projectionUpdateFlag = -1;
- this._alternateViewUpdateFlag = -1;
- this._alternateProjectionUpdateFlag = -1;
- this._toBeDisposed = new BABYLON.SmartArray(256);
- this._activeRequests = new Array();
- this._pendingData = new Array();
- this._isDisposed = false;
- this.dispatchAllSubMeshesOfActiveMeshes = false;
- this._activeMeshes = new BABYLON.SmartArray(256);
- this._processedMaterials = new BABYLON.SmartArray(256);
- this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
- this._activeParticleSystems = new BABYLON.SmartArray(256);
- this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
- this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
- this._activeAnimatables = new Array();
- this._transformMatrix = BABYLON.Matrix.Zero();
- this._useAlternateCameraConfiguration = false;
- this._alternateRendering = false;
- this.requireLightSorting = false;
- this._activeMeshesFrozen = false;
- this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
- this._engine = engine || BABYLON.Engine.LastCreatedEngine;
- this._engine.scenes.push(this);
- this._uid = null;
- this._renderingManager = new BABYLON.RenderingManager(this);
- this.postProcessManager = new BABYLON.PostProcessManager(this);
- if (BABYLON.OutlineRenderer) {
- this._outlineRenderer = new BABYLON.OutlineRenderer(this);
- }
- if (BABYLON.Tools.IsWindowObjectExist()) {
- this.attachControl();
- }
- //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));
- // Uniform Buffer
- this._createUbo();
- // Default Image processing definition.
- this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
- }
- Object.defineProperty(Scene, "FOGMODE_NONE", {
- /** The fog is deactivated */
- get: function () {
- return Scene._FOGMODE_NONE;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene, "FOGMODE_EXP", {
- /** The fog density is following an exponential function */
- get: function () {
- return Scene._FOGMODE_EXP;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene, "FOGMODE_EXP2", {
- /** The fog density is following an exponential function faster than FOGMODE_EXP */
- get: function () {
- return Scene._FOGMODE_EXP2;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene, "FOGMODE_LINEAR", {
- /** The fog density is following a linear function. */
- get: function () {
- return Scene._FOGMODE_LINEAR;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene.prototype, "environmentTexture", {
- /**
- * Texture used in all pbr material as the reflection texture.
- * As in the majority of the scene they are the same (exception for multi room and so on),
- * this is easier to reference from here than from all the materials.
- */
- get: function () {
- return this._environmentTexture;
- },
- /**
- * Texture used in all pbr material as the reflection texture.
- * As in the majority of the scene they are the same (exception for multi room and so on),
- * this is easier to set here than in all the materials.
- */
- set: function (value) {
- if (this._environmentTexture === value) {
- return;
- }
- this._environmentTexture = value;
- this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
- /**
- * Default image processing configuration used either in the rendering
- * Forward main pass or through the imageProcessingPostProcess if present.
- * As in the majority of the scene they are the same (exception for multi camera),
- * this is easier to reference from here than from all the materials and post process.
- *
- * No setter as we it is a shared configuration, you can set the values instead.
- */
- get: function () {
- return this._imageProcessingConfiguration;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene.prototype, "forcePointsCloud", {
- get: function () {
- return this._forcePointsCloud;
- },
- set: function (value) {
- if (this._forcePointsCloud === value) {
- return;
- }
- this._forcePointsCloud = value;
- this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene.prototype, "onDispose", {
- /** A function to be executed when this scene is disposed. */
- 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", {
- /** A function to be executed before rendering this scene */
- set: function (callback) {
- if (this._onBeforeRenderObserver) {
- this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
- }
- if (callback) {
- this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene.prototype, "afterRender", {
- /** A function to be executed after rendering this scene */
- set: function (callback) {
- if (this._onAfterRenderObserver) {
- this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
- }
- if (callback) {
- 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, "gamepadManager", {
- get: function () {
- if (!this._gamepadManager) {
- this._gamepadManager = new BABYLON.GamepadManager(this);
- }
- return this._gamepadManager;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
- get: function () {
- return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
- get: function () {
- return this._useRightHandedSystem;
- },
- set: function (value) {
- if (this._useRightHandedSystem === value) {
- return;
- }
- this._useRightHandedSystem = value;
- this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
- },
- enumerable: true,
- configurable: true
- });
- Scene.prototype.setStepId = function (newStepId) {
- this._currentStepId = newStepId;
- };
- ;
- Scene.prototype.getStepId = function () {
- return this._currentStepId;
- };
- ;
- Scene.prototype.getInternalStep = function () {
- return this._currentInternalStep;
- };
- ;
- Object.defineProperty(Scene.prototype, "fogEnabled", {
- get: function () {
- return this._fogEnabled;
- },
- /**
- * is fog enabled on this scene.
- */
- set: function (value) {
- if (this._fogEnabled === value) {
- return;
- }
- this._fogEnabled = value;
- this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene.prototype, "fogMode", {
- get: function () {
- return this._fogMode;
- },
- set: function (value) {
- if (this._fogMode === value) {
- return;
- }
- this._fogMode = value;
- this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene.prototype, "shadowsEnabled", {
- get: function () {
- return this._shadowsEnabled;
- },
- set: function (value) {
- if (this._shadowsEnabled === value) {
- return;
- }
- this._shadowsEnabled = value;
- this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene.prototype, "lightsEnabled", {
- get: function () {
- return this._lightsEnabled;
- },
- set: function (value) {
- if (this._lightsEnabled === value) {
- return;
- }
- this._lightsEnabled = value;
- this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene.prototype, "defaultMaterial", {
- /** The default material used on meshes when no material is affected */
- get: function () {
- if (!this._defaultMaterial) {
- this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
- }
- return this._defaultMaterial;
- },
- /** The default material used on meshes when no material is affected */
- set: function (value) {
- this._defaultMaterial = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene.prototype, "texturesEnabled", {
- get: function () {
- return this._texturesEnabled;
- },
- set: function (value) {
- if (this._texturesEnabled === value) {
- return;
- }
- this._texturesEnabled = value;
- this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
- get: function () {
- return this._skeletonsEnabled;
- },
- set: function (value) {
- if (this._skeletonsEnabled === value) {
- return;
- }
- this._skeletonsEnabled = value;
- this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
- get: function () {
- if (!this._postProcessRenderPipelineManager) {
- this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
- }
- return this._postProcessRenderPipelineManager;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene.prototype, "mainSoundTrack", {
- get: function () {
- if (!this._mainSoundTrack) {
- this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
- }
- return this._mainSoundTrack;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
- get: function () {
- return this._alternateRendering;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene.prototype, "frustumPlanes", {
- get: function () {
- return this._frustumPlanes;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene.prototype, "debugLayer", {
- // Properties
- get: function () {
- if (!this._debugLayer) {
- this._debugLayer = new BABYLON.DebugLayer(this);
- }
- return this._debugLayer;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Scene.prototype, "workerCollisions", {
- get: function () {
- return this._workerCollisions;
- },
- set: function (enabled) {
- if (!BABYLON.CollisionCoordinatorLegacy) {
- return;
- }
- 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.getCachedEffect = function () {
- return this._cachedEffect;
- };
- Scene.prototype.getCachedVisibility = function () {
- return this._cachedVisibility;
- };
- Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
- if (visibility === void 0) { visibility = 1; }
- return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
- };
- Scene.prototype.getBoundingBoxRenderer = function () {
- if (!this._boundingBoxRenderer) {
- this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
- }
- return this._boundingBoxRenderer;
- };
- Scene.prototype.getOutlineRenderer = function () {
- return this._outlineRenderer;
- };
- Scene.prototype.getEngine = function () {
- return this._engine;
- };
- Scene.prototype.getTotalVertices = function () {
- return this._totalVertices.current;
- };
- Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
- get: function () {
- return this._totalVertices;
- },
- enumerable: true,
- configurable: true
- });
- Scene.prototype.getActiveIndices = function () {
- return this._activeIndices.current;
- };
- Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
- get: function () {
- return this._activeIndices;
- },
- enumerable: true,
- configurable: true
- });
- Scene.prototype.getActiveParticles = function () {
- return this._activeParticles.current;
- };
- Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
- get: function () {
- return this._activeParticles;
- },
- enumerable: true,
- configurable: true
- });
- Scene.prototype.getActiveBones = function () {
- return this._activeBones.current;
- };
- Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
- get: function () {
- return this._activeBones;
- },
- enumerable: true,
- configurable: true
- });
- // Stats
- Scene.prototype.getInterFramePerfCounter = function () {
- BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
- return 0;
- };
- Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
- get: function () {
- BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
- return null;
- },
- enumerable: true,
- configurable: true
- });
- Scene.prototype.getLastFrameDuration = function () {
- BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
- return 0;
- };
- Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
- get: function () {
- BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
- return null;
- },
- enumerable: true,
- configurable: true
- });
- Scene.prototype.getEvaluateActiveMeshesDuration = function () {
- BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
- return 0;
- };
- Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
- get: function () {
- BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
- return null;
- },
- enumerable: true,
- configurable: true
- });
- Scene.prototype.getActiveMeshes = function () {
- return this._activeMeshes;
- };
- Scene.prototype.getRenderTargetsDuration = function () {
- BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
- return 0;
- };
- Scene.prototype.getRenderDuration = function () {
- BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
- return 0;
- };
- Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
- get: function () {
- BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
- return null;
- },
- enumerable: true,
- configurable: true
- });
- Scene.prototype.getParticlesDuration = function () {
- BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
- return 0;
- };
- Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
- get: function () {
- BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
- return null;
- },
- enumerable: true,
- configurable: true
- });
- Scene.prototype.getSpritesDuration = function () {
- BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
- return 0;
- };
- Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
- get: function () {
- BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
- return null;
- },
- enumerable: true,
- configurable: true
- });
- 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();
- if (!canvasRect) {
- return;
- }
- this._pointerX = evt.clientX - canvasRect.left;
- this._pointerY = evt.clientY - canvasRect.top;
- this._unTranslatedPointerX = this._pointerX;
- this._unTranslatedPointerY = this._pointerY;
- };
- Scene.prototype._createUbo = function () {
- this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
- this._sceneUbo.addUniform("viewProjection", 16);
- this._sceneUbo.addUniform("view", 16);
- };
- Scene.prototype._createAlternateUbo = function () {
- this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
- this._alternateSceneUbo.addUniform("viewProjection", 16);
- this._alternateSceneUbo.addUniform("view", 16);
- };
- // Pointers handling
- /**
- * Use this method to simulate a pointer move on a mesh
- * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
- */
- Scene.prototype.simulatePointerMove = function (pickResult) {
- var evt = new PointerEvent("pointermove");
- return this._processPointerMove(pickResult, evt);
- };
- Scene.prototype._processPointerMove = function (pickResult, evt) {
- var canvas = this._engine.getRenderingCanvas();
- if (!canvas) {
- return this;
- }
- if (pickResult && pickResult.hit && pickResult.pickedMesh) {
- this.setPointerOverSprite(null);
- this.setPointerOverMesh(pickResult.pickedMesh);
- if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
- if (this._pointerOverMesh.actionManager.hoverCursor) {
- canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
- }
- else {
- canvas.style.cursor = this.hoverCursor;
- }
- }
- else {
- canvas.style.cursor = this.defaultCursor;
- }
- }
- else {
- this.setPointerOverMesh(null);
- // Sprites
- pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
- if (pickResult && pickResult.hit && pickResult.pickedSprite) {
- this.setPointerOverSprite(pickResult.pickedSprite);
- if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
- canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
- }
- else {
- canvas.style.cursor = this.hoverCursor;
- }
- }
- else {
- this.setPointerOverSprite(null);
- // Restore pointer
- canvas.style.cursor = this.defaultCursor;
- }
- }
- if (pickResult) {
- if (this.onPointerMove) {
- this.onPointerMove(evt, pickResult);
- }
- if (this.onPointerObservable.hasObservers()) {
- var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
- var pi = new BABYLON.PointerInfo(type, evt, pickResult);
- this.onPointerObservable.notifyObservers(pi, type);
- }
- }
- return this;
- };
- /**
- * Use this method to simulate a pointer down on a mesh
- * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
- */
- Scene.prototype.simulatePointerDown = function (pickResult) {
- var evt = new PointerEvent("pointerdown");
- return this._processPointerDown(pickResult, evt);
- };
- Scene.prototype._processPointerDown = function (pickResult, evt) {
- var _this = this;
- if (pickResult && pickResult.hit && pickResult.pickedMesh) {
- this._pickedDownMesh = pickResult.pickedMesh;
- var actionManager = pickResult.pickedMesh.actionManager;
- if (actionManager) {
- if (actionManager.hasPickTriggers) {
- actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
- switch (evt.button) {
- case 0:
- actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
- break;
- case 1:
- actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
- break;
- case 2:
- actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
- break;
- }
- }
- if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
- window.setTimeout(function () {
- var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, function (mesh) { return (mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger) && mesh == _this._pickedDownMesh); }, false, _this.cameraToUseForPointers);
- if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
- if (_this._totalPointersPressed !== 0 &&
- ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
- (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
- Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
- _this._startingPointerTime = 0;
- actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
- }
- }
- }, Scene.LongPressDelay);
- }
- }
- }
- if (pickResult) {
- if (this.onPointerDown) {
- this.onPointerDown(evt, pickResult);
- }
- if (this.onPointerObservable.hasObservers()) {
- var type = BABYLON.PointerEventTypes.POINTERDOWN;
- var pi = new BABYLON.PointerInfo(type, evt, pickResult);
- this.onPointerObservable.notifyObservers(pi, type);
- }
- }
- return this;
- };
- /**
- * Use this method to simulate a pointer up on a mesh
- * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
- */
- Scene.prototype.simulatePointerUp = function (pickResult) {
- var evt = new PointerEvent("pointerup");
- var clickInfo = new ClickInfo();
- clickInfo.singleClick = true;
- clickInfo.ignore = true;
- return this._processPointerUp(pickResult, evt, clickInfo);
- };
- Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
- if (pickResult && pickResult && pickResult.pickedMesh) {
- this._pickedUpMesh = pickResult.pickedMesh;
- if (this._pickedDownMesh === this._pickedUpMesh) {
- if (this.onPointerPick) {
- this.onPointerPick(evt, pickResult);
- }
- if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
- var type = BABYLON.PointerEventTypes.POINTERPICK;
- var pi = new BABYLON.PointerInfo(type, evt, pickResult);
- this.onPointerObservable.notifyObservers(pi, type);
- }
- }
- if (pickResult.pickedMesh.actionManager) {
- if (clickInfo.ignore) {
- pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
- }
- if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
- pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
- }
- if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
- pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
- }
- }
- }
- if (this._pickedDownMesh &&
- this._pickedDownMesh.actionManager &&
- this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
- this._pickedDownMesh !== this._pickedUpMesh) {
- this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
- }
- if (this.onPointerUp) {
- this.onPointerUp(evt, pickResult);
- }
- if (this.onPointerObservable.hasObservers()) {
- if (!clickInfo.ignore) {
- if (!clickInfo.hasSwiped) {
- if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
- var type = BABYLON.PointerEventTypes.POINTERTAP;
- var pi = new BABYLON.PointerInfo(type, evt, pickResult);
- this.onPointerObservable.notifyObservers(pi, type);
- }
- if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
- var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
- var pi = new BABYLON.PointerInfo(type, evt, pickResult);
- this.onPointerObservable.notifyObservers(pi, type);
- }
- }
- }
- else {
- var type = BABYLON.PointerEventTypes.POINTERUP;
- var pi = new BABYLON.PointerInfo(type, evt, pickResult);
- this.onPointerObservable.notifyObservers(pi, type);
- }
- }
- return this;
- };
- /**
- * 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; }
- this._initActionManager = function (act, clickInfo) {
- if (!_this._meshPickProceed) {
- var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
- _this._currentPickResult = pickResult;
- if (pickResult) {
- act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
- }
- _this._meshPickProceed = true;
- }
- return act;
- };
- this._delayedSimpleClick = function (btn, clickInfo, cb) {
- // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
- if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
- btn !== _this._previousButtonPressed) {
- _this._doubleClickOccured = false;
- clickInfo.singleClick = true;
- clickInfo.ignore = false;
- cb(clickInfo, _this._currentPickResult);
- }
- };
- this._initClickEvent = function (obs1, obs2, evt, cb) {
- var clickInfo = new ClickInfo();
- _this._currentPickResult = null;
- var act = null;
- var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
- || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
- || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
- if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
- act = _this._initActionManager(act, clickInfo);
- if (act)
- checkPicking = act.hasPickTriggers;
- }
- if (checkPicking) {
- var btn = evt.button;
- clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
- Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
- if (!clickInfo.hasSwiped) {
- var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
- if (!checkSingleClickImmediately) {
- checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
- !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
- if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
- act = _this._initActionManager(act, clickInfo);
- if (act)
- checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
- }
- }
- if (checkSingleClickImmediately) {
- // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
- if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
- btn !== _this._previousButtonPressed) {
- clickInfo.singleClick = true;
- cb(clickInfo, _this._currentPickResult);
- }
- }
- else {
- // wait that no double click has been raised during the double click delay
- _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
- _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
- }
- var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
- obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
- if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
- act = _this._initActionManager(act, clickInfo);
- if (act)
- checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
- }
- if (checkDoubleClick) {
- // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
- if (btn === _this._previousButtonPressed &&
- new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
- !_this._doubleClickOccured) {
- // pointer has not moved for 2 clicks, it's a double click
- if (!clickInfo.hasSwiped &&
- Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
- Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
- _this._previousStartingPointerTime = 0;
- _this._doubleClickOccured = true;
- clickInfo.doubleClick = true;
- clickInfo.ignore = false;
- if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
- clearTimeout(_this._previousDelayedSimpleClickTimeout);
- }
- _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
- cb(clickInfo, _this._currentPickResult);
- }
- else {
- _this._doubleClickOccured = false;
- _this._previousStartingPointerTime = _this._startingPointerTime;
- _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
- _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
- _this._previousButtonPressed = btn;
- if (Scene.ExclusiveDoubleClickMode) {
- if (_this._previousDelayedSimpleClickTimeout) {
- clearTimeout(_this._previousDelayedSimpleClickTimeout);
- }
- _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
- cb(clickInfo, _this._previousPickResult);
- }
- else {
- cb(clickInfo, _this._currentPickResult);
- }
- }
- }
- else {
- _this._doubleClickOccured = false;
- _this._previousStartingPointerTime = _this._startingPointerTime;
- _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
- _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
- _this._previousButtonPressed = btn;
- }
- }
- }
- }
- clickInfo.ignore = true;
- cb(clickInfo, _this._currentPickResult);
- };
- this._spritePredicate = function (sprite) {
- return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
- };
- this._onPointerMove = function (evt) {
- _this._updatePointerPosition(evt);
- // PreObservable support
- if (_this.onPrePointerObservable.hasObservers()) {
- var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
- var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
- _this.onPrePointerObservable.notifyObservers(pi, type);
- if (pi.skipOnPointerObservable) {
- return;
- }
- }
- if (!_this.cameraToUseForPointers && !_this.activeCamera) {
- return;
- }
- if (!_this.pointerMovePredicate) {
- _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
- }
- // Meshes
- var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
- _this._processPointerMove(pickResult, evt);
- };
- this._onPointerDown = function (evt) {
- _this._totalPointersPressed++;
- _this._pickedDownMesh = null;
- _this._meshPickProceed = false;
- _this._updatePointerPosition(evt);
- if (_this.preventDefaultOnPointerDown && canvas) {
- evt.preventDefault();
- canvas.focus();
- }
- // PreObservable support
- if (_this.onPrePointerObservable.hasObservers()) {
- var type = BABYLON.PointerEventTypes.POINTERDOWN;
- var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
- _this.onPrePointerObservable.notifyObservers(pi, type);
- if (pi.skipOnPointerObservable) {
- return;
- }
- }
- if (!_this.cameraToUseForPointers && !_this.activeCamera) {
- return;
- }
- _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.isEnabled();
- };
- }
- // Meshes
- _this._pickedDownMesh = null;
- var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
- _this._processPointerDown(pickResult, evt);
- // Sprites
- _this._pickedDownSprite = null;
- if (_this.spriteManagers.length > 0) {
- pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
- if (pickResult && 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;
- }
- if (pickResult.pickedSprite.actionManager) {
- pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
- }
- }
- }
- }
- };
- this._onPointerUp = function (evt) {
- if (_this._totalPointersPressed === 0) {
- return; // So we need to test it the pointer down was pressed before.
- }
- _this._totalPointersPressed--;
- _this._pickedUpMesh = null;
- _this._meshPickProceed = false;
- _this._updatePointerPosition(evt);
- _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
- // PreObservable support
- if (_this.onPrePointerObservable.hasObservers()) {
- if (!clickInfo.ignore) {
- if (!clickInfo.hasSwiped) {
- if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
- var type = BABYLON.PointerEventTypes.POINTERTAP;
- var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
- _this.onPrePointerObservable.notifyObservers(pi, type);
- if (pi.skipOnPointerObservable) {
- return;
- }
- }
- if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
- var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
- var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
- _this.onPrePointerObservable.notifyObservers(pi, type);
- if (pi.skipOnPointerObservable) {
- return;
- }
- }
- }
- }
- else {
- var type = BABYLON.PointerEventTypes.POINTERUP;
- var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
- _this.onPrePointerObservable.notifyObservers(pi, type);
- if (pi.skipOnPointerObservable) {
- return;
- }
- }
- }
- if (!_this.cameraToUseForPointers && !_this.activeCamera) {
- return;
- }
- if (!_this.pointerUpPredicate) {
- _this.pointerUpPredicate = function (mesh) {
- return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
- };
- }
- // Meshes
- if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
- _this._initActionManager(null, clickInfo);
- }
- if (!pickResult) {
- pickResult = _this._currentPickResult;
- }
- _this._processPointerUp(pickResult, evt, clickInfo);
- // Sprites
- if (_this.spriteManagers.length > 0) {
- var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
- if (spritePickResult) {
- if (spritePickResult.hit && spritePickResult.pickedSprite) {
- if (spritePickResult.pickedSprite.actionManager) {
- spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
- if (spritePickResult.pickedSprite.actionManager) {
- if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
- spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
- }
- }
- }
- }
- if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
- _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
- }
- }
- }
- _this._previousPickResult = _this._currentPickResult;
- });
- };
- this._onKeyDown = function (evt) {
- var type = BABYLON.KeyboardEventTypes.KEYDOWN;
- if (_this.onPreKeyboardObservable.hasObservers()) {
- var pi = new BABYLON.KeyboardInfoPre(type, evt);
- _this.onPreKeyboardObservable.notifyObservers(pi, type);
- if (pi.skipOnPointerObservable) {
- return;
- }
- }
- if (_this.onKeyboardObservable.hasObservers()) {
- var pi = new BABYLON.KeyboardInfo(type, evt);
- _this.onKeyboardObservable.notifyObservers(pi, type);
- }
- if (_this.actionManager) {
- _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
- }
- };
- this._onKeyUp = function (evt) {
- var type = BABYLON.KeyboardEventTypes.KEYUP;
- if (_this.onPreKeyboardObservable.hasObservers()) {
- var pi = new BABYLON.KeyboardInfoPre(type, evt);
- _this.onPreKeyboardObservable.notifyObservers(pi, type);
- if (pi.skipOnPointerObservable) {
- return;
- }
- }
- if (_this.onKeyboardObservable.hasObservers()) {
- var pi = new BABYLON.KeyboardInfo(type, evt);
- _this.onKeyboardObservable.notifyObservers(pi, type);
- }
- if (_this.actionManager) {
- _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
- }
- };
- var engine = this.getEngine();
- this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
- if (!canvas) {
- return;
- }
- canvas.addEventListener("keydown", _this._onKeyDown, false);
- canvas.addEventListener("keyup", _this._onKeyUp, false);
- });
- this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
- if (!canvas) {
- return;
- }
- canvas.removeEventListener("keydown", _this._onKeyDown);
- canvas.removeEventListener("keyup", _this._onKeyUp);
- });
- var eventPrefix = BABYLON.Tools.GetPointerPrefix();
- var canvas = this._engine.getRenderingCanvas();
- if (!canvas) {
- return;
- }
- if (attachMove) {
- canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
- // Wheel
- canvas.addEventListener('mousewheel', this._onPointerMove, false);
- canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
- }
- if (attachDown) {
- canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
- }
- if (attachUp) {
- window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
- }
- canvas.tabIndex = 1;
- };
- Scene.prototype.detachControl = function () {
- var engine = this.getEngine();
- var eventPrefix = BABYLON.Tools.GetPointerPrefix();
- var canvas = engine.getRenderingCanvas();
- if (!canvas) {
- return;
- }
- canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
- canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
- window.removeEventListener(eventPrefix + "up", this._onPointerUp);
- if (this._onCanvasBlurObserver) {
- engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
- }
- if (this._onCanvasFocusObserver) {
- engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
- }
- // Wheel
- canvas.removeEventListener('mousewheel', this._onPointerMove);
- canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
- // Keyboard
- canvas.removeEventListener("keydown", this._onKeyDown);
- canvas.removeEventListener("keyup", this._onKeyUp);
- // Observables
- this.onKeyboardObservable.clear();
- this.onPreKeyboardObservable.clear();
- this.onPointerObservable.clear();
- this.onPrePointerObservable.clear();
- };
- // Ready
- Scene.prototype.isReady = function () {
- if (this._isDisposed) {
- return false;
- }
- if (this._pendingData.length > 0) {
- return false;
- }
- var index;
- // Geometries
- for (index = 0; index < this._geometries.length; index++) {
- var geometry = this._geometries[index];
- if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
- return false;
- }
- }
- // Meshes
- for (index = 0; index < this.meshes.length; index++) {
- var mesh = this.meshes[index];
- if (!mesh.isEnabled()) {
- continue;
- }
- if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
- continue;
- }
- 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;
- this._cachedEffect = null;
- this._cachedVisibility = 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._executeOnceBeforeRender = function (func) {
- var _this = this;
- var execFunc = function () {
- func();
- setTimeout(function () {
- _this.unregisterBeforeRender(execFunc);
- });
- };
- this.registerBeforeRender(execFunc);
- };
- /**
- * The provided function will run before render once and will be disposed afterwards.
- * A timeout delay can be provided so that the function will be executed in N ms.
- * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
- * @param func The function to be executed.
- * @param timeout optional delay in ms
- */
- Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
- var _this = this;
- if (timeout !== undefined) {
- setTimeout(function () {
- _this._executeOnceBeforeRender(func);
- }, timeout);
- }
- else {
- this._executeOnceBeforeRender(func);
- }
- };
- Scene.prototype._addPendingData = function (data) {
- this._pendingData.push(data);
- };
- Scene.prototype._removePendingData = function (data) {
- var wasLoading = this.isLoading;
- var index = this._pendingData.indexOf(data);
- if (index !== -1) {
- this._pendingData.splice(index, 1);
- }
- if (wasLoading && !this.isLoading) {
- this.onDataLoadedObservable.notifyObservers(this);
- }
- };
- Scene.prototype.getWaitingItemsCount = function () {
- return this._pendingData.length;
- };
- Object.defineProperty(Scene.prototype, "isLoading", {
- get: function () {
- return this._pendingData.length > 0;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * 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.
- * Returns {BABYLON.Animatable} the animatable object created for this animation
- * See BABYLON.Animatable
- */
- Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
- if (speedRatio === void 0) { speedRatio = 1.0; }
- if (from > to && speedRatio > 0) {
- speedRatio *= -1;
- }
- 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;
- };
- /**
- * Begin a new animation on a given node
- * @param {BABYLON.Node} node defines the root node where the animation will take place
- * @param {BABYLON.Animation[]} defines the list of animations to start
- * @param {number} from defines the initial value
- * @param {number} to defines the final value
- * @param {boolean} loop defines if you want animation to loop (off by default)
- * @param {number} speedRatio defines the speed ratio to apply to all animations
- * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
- * @returns the list of created animatables
- */
- 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;
- };
- /**
- * Begin a new animation on a given node and its hierarchy
- * @param {BABYLON.Node} node defines the root node where the animation will take place
- * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
- * @param {BABYLON.Animation[]} defines the list of animations to start
- * @param {number} from defines the initial value
- * @param {number} to defines the final value
- * @param {boolean} loop defines if you want animation to loop (off by default)
- * @param {number} speedRatio defines the speed ratio to apply to all animations
- * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
- * @returns the list of animatables created for all nodes
- */
- Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
- var children = target.getDescendants(directDescendantsOnly);
- var result = [];
- for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
- var child = children_1[_i];
- result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
- }
- return result;
- };
- 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
- * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
- * @see beginAnimation
- */
- Scene.prototype.stopAnimation = function (target, animationName) {
- var animatable = this.getAnimatableByTarget(target);
- if (animatable) {
- animatable.stop(animationName);
- }
- };
- /**
- * Stops and removes all animations that have been applied to the scene
- */
- Scene.prototype.stopAllAnimations = function () {
- if (this._activeAnimatables) {
- for (var i = 0; i < this._activeAnimatables.length; i++) {
- this._activeAnimatables[i].stop();
- }
- this._activeAnimatables = [];
- }
- };
- Scene.prototype._animate = function () {
- if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
- return;
- }
- // Getting time
- var now = BABYLON.Tools.Now;
- if (!this._animationTimeLast) {
- if (this._pendingData.length > 0) {
- return;
- }
- this._animationTimeLast = now;
- }
- var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
- this._animationTime += deltaTime;
- this._animationTimeLast = now;
- for (var index = 0; index < this._activeAnimatables.length; index++) {
- this._activeAnimatables[index]._animate(this._animationTime);
- }
- };
- // Matrix
- Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
- this._useAlternateCameraConfiguration = active;
- };
- Scene.prototype.getViewMatrix = function () {
- return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
- };
- Scene.prototype.getProjectionMatrix = function () {
- return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
- };
- Scene.prototype.getTransformMatrix = function () {
- return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
- };
- Scene.prototype.setTransformMatrix = function (view, projection) {
- if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
- return;
- }
- this._viewUpdateFlag = view.updateFlag;
- this._projectionUpdateFlag = projection.updateFlag;
- this._viewMatrix = view;
- this._projectionMatrix = projection;
- this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
- // Update frustum
- if (!this._frustumPlanes) {
- this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
- }
- else {
- BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
- }
- if (this.activeCamera && this.activeCamera._alternateCamera) {
- var otherCamera = this.activeCamera._alternateCamera;
- otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
- BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
- }
- if (this._sceneUbo.useUbo) {
- this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
- this._sceneUbo.updateMatrix("view", this._viewMatrix);
- this._sceneUbo.update();
- }
- };
- Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
- if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
- return;
- }
- this._alternateViewUpdateFlag = view.updateFlag;
- this._alternateProjectionUpdateFlag = projection.updateFlag;
- this._alternateViewMatrix = view;
- this._alternateProjectionMatrix = projection;
- if (!this._alternateTransformMatrix) {
- this._alternateTransformMatrix = BABYLON.Matrix.Zero();
- }
- this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
- if (!this._alternateSceneUbo) {
- this._createAlternateUbo();
- }
- if (this._alternateSceneUbo.useUbo) {
- this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
- this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
- this._alternateSceneUbo.update();
- }
- };
- Scene.prototype.getSceneUniformBuffer = function () {
- return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
- };
- // Methods
- Scene.prototype.getUniqueId = function () {
- var result = Scene._uniqueIdCounter;
- Scene._uniqueIdCounter++;
- return result;
- };
- Scene.prototype.addMesh = function (newMesh) {
- this.meshes.push(newMesh);
- //notify the collision coordinator
- if (this.collisionCoordinator) {
- 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);
- }
- this.onMeshRemovedObservable.notifyObservers(toRemove);
- return index;
- };
- Scene.prototype.addTransformNode = function (newTransformNode) {
- this.transformNodes.push(newTransformNode);
- this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
- };
- Scene.prototype.removeTransformNode = function (toRemove) {
- var index = this.transformNodes.indexOf(toRemove);
- if (index !== -1) {
- // Remove from the scene if found
- this.transformNodes.splice(index, 1);
- }
- this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
- return index;
- };
- Scene.prototype.removeSkeleton = function (toRemove) {
- var index = this.skeletons.indexOf(toRemove);
- if (index !== -1) {
- // Remove from the scene if found
- this.skeletons.splice(index, 1);
- }
- return index;
- };
- Scene.prototype.removeMorphTargetManager = function (toRemove) {
- var index = this.morphTargetManagers.indexOf(toRemove);
- if (index !== -1) {
- // Remove from the scene if found
- this.morphTargetManagers.splice(index, 1);
- }
- return index;
- };
- Scene.prototype.removeLight = function (toRemove) {
- var index = this.lights.indexOf(toRemove);
- if (index !== -1) {
- // Remove from meshes
- for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
- var mesh = _a[_i];
- mesh._removeLightSource(toRemove);
- }
- // Remove from the scene if mesh found
- this.lights.splice(index, 1);
- this.sortLightsByPriority();
- }
- 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) {
- this.lights.push(newLight);
- this.sortLightsByPriority();
- // Add light to all meshes (To support if the light is removed and then readded)
- for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
- var mesh = _a[_i];
- if (mesh._lightSources.indexOf(newLight) === -1) {
- mesh._lightSources.push(newLight);
- mesh._resyncLightSources();
- }
- }
- this.onNewLightAddedObservable.notifyObservers(newLight);
- };
- Scene.prototype.sortLightsByPriority = function () {
- if (this.requireLightSorting) {
- this.lights.sort(BABYLON.Light.compareLightsPriority);
- }
- };
- Scene.prototype.addCamera = function (newCamera) {
- 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.switchActiveCamera = function (newCamera, attachControl) {
- if (attachControl === void 0) { attachControl = true; }
- var canvas = this._engine.getRenderingCanvas();
- if (!canvas) {
- return;
- }
- if (this.activeCamera) {
- 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 an animation group using its name
- * @param {string} the material's name
- * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
- */
- Scene.prototype.getAnimationGroupByName = function (name) {
- for (var index = 0; index < this.animationGroups.length; index++) {
- if (this.animationGroups[index].name === name) {
- return this.animationGroups[index];
- }
- }
- 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.IParticleSystem|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
- if (this.collisionCoordinator) {
- 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
- if (this.collisionCoordinator) {
- 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 the first added transform node found of a given ID
- * @param {string} id - the id to search for
- * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
- */
- Scene.prototype.getTransformNodeByID = function (id) {
- for (var index = 0; index < this.transformNodes.length; index++) {
- if (this.transformNodes[index].id === id) {
- return this.transformNodes[index];
- }
- }
- return null;
- };
- Scene.prototype.getTransformNodesByID = function (id) {
- return this.transformNodes.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.transformNodes.length - 1; index >= 0; index--) {
- if (this.transformNodes[index].id === id) {
- return this.transformNodes[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.getTransformNodeByName = function (name) {
- for (var index = 0; index < this.transformNodes.length; index++) {
- if (this.transformNodes[index].name === name) {
- return this.transformNodes[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.getMorphTargetManagerById = function (id) {
- for (var index = 0; index < this.morphTargetManagers.length; index++) {
- if (this.morphTargetManagers[index].uniqueId === id) {
- return this.morphTargetManagers[index];
- }
- }
- return null;
- };
- Scene.prototype.isActiveMesh = function (mesh) {
- return (this._activeMeshes.indexOf(mesh) !== -1);
- };
- /**
- * Return a the first highlight layer of the scene with a given name.
- * @param name The name of the highlight layer to look for.
- * @return The highlight layer if found otherwise null.
- */
- Scene.prototype.getHighlightLayerByName = function (name) {
- for (var index = 0; index < this.highlightLayers.length; index++) {
- if (this.highlightLayers[index].name === name) {
- return this.highlightLayers[index];
- }
- }
- return null;
- };
- Object.defineProperty(Scene.prototype, "uid", {
- /**
- * Return a unique id as a string which can serve as an identifier for the scene
- */
- get: function () {
- if (!this._uid) {
- this._uid = BABYLON.Tools.RandomId();
- }
- return this._uid;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Add an externaly attached data from its key.
- * This method call will fail and return false, if such key already exists.
- * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
- * @param key the unique key that identifies the data
- * @param data the data object to associate to the key for this Engine instance
- * @return true if no such key were already present and the data was added successfully, false otherwise
- */
- Scene.prototype.addExternalData = function (key, data) {
- if (!this._externalData) {
- this._externalData = new BABYLON.StringDictionary();
- }
- return this._externalData.add(key, data);
- };
- /**
- * Get an externaly attached data from its key
- * @param key the unique key that identifies the data
- * @return the associated data, if present (can be null), or undefined if not present
- */
- Scene.prototype.getExternalData = function (key) {
- if (!this._externalData) {
- return null;
- }
- return this._externalData.get(key);
- };
- /**
- * Get an externaly attached data from its key, create it using a factory if it's not already present
- * @param key the unique key that identifies the data
- * @param factory the factory that will be called to create the instance if and only if it doesn't exists
- * @return the associated data, can be null if the factory returned null.
- */
- Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
- if (!this._externalData) {
- this._externalData = new BABYLON.StringDictionary();
- }
- return this._externalData.getOrAddWithFactory(key, factory);
- };
- /**
- * Remove an externaly attached data from the Engine instance
- * @param key the unique key that identifies the data
- * @return true if the data was successfully removed, false if it doesn't exist
- */
- Scene.prototype.removeExternalData = function (key) {
- return this._externalData.remove(key);
- };
- Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
- if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
- if (mesh.showSubMeshesBoundingBox) {
- var boundingInfo = subMesh.getBoundingInfo();
- if (boundingInfo !== null && boundingInfo !== undefined) {
- this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
- }
- }
- var material = subMesh.getMaterial();
- if (material !== null && material !== undefined) {
- // Render targets
- if (material.getRenderTargetTextures !== undefined) {
- if (this._processedMaterials.indexOf(material) === -1) {
- this._processedMaterials.push(material);
- this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
- }
- }
- // Dispatch
- this._activeIndices.addCount(subMesh.indexCount, false);
- this._renderingManager.dispatch(subMesh, mesh, material);
- }
- }
- };
- Scene.prototype._isInIntermediateRendering = function () {
- return this._intermediateRendering;
- };
- Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
- this._activeMeshCandidateProvider = provider;
- };
- Scene.prototype.getActiveMeshCandidateProvider = function () {
- return this._activeMeshCandidateProvider;
- };
- /**
- * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
- */
- Scene.prototype.freezeActiveMeshes = function () {
- this._evaluateActiveMeshes();
- this._activeMeshesFrozen = true;
- return this;
- };
- /**
- * Use this function to restart evaluating active meshes on every frame
- */
- Scene.prototype.unfreezeActiveMeshes = function () {
- this._activeMeshesFrozen = false;
- return this;
- };
- Scene.prototype._evaluateActiveMeshes = function () {
- if (this._activeMeshesFrozen && this._activeMeshes.length) {
- return;
- }
- if (!this.activeCamera) {
- return;
- }
- this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
- this.activeCamera._activeMeshes.reset();
- this._activeMeshes.reset();
- this._renderingManager.reset();
- this._processedMaterials.reset();
- this._activeParticleSystems.reset();
- this._activeSkeletons.reset();
- this._softwareSkinnedMeshes.reset();
- if (this._boundingBoxRenderer) {
- this._boundingBoxRenderer.reset();
- }
- // Meshes
- var meshes;
- var len;
- var checkIsEnabled = true;
- // Determine mesh candidates
- if (this._activeMeshCandidateProvider !== undefined) {
- // Use _activeMeshCandidateProvider
- meshes = this._activeMeshCandidateProvider.getMeshes(this);
- checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
- if (meshes !== undefined) {
- len = meshes.length;
- }
- else {
- len = 0;
- }
- }
- else if (this._selectionOctree !== undefined) {
- // Octree
- var selection = this._selectionOctree.select(this._frustumPlanes);
- meshes = selection.data;
- len = selection.length;
- }
- else {
- // Full scene traversal
- len = this.meshes.length;
- meshes = this.meshes;
- }
- // Check each mesh
- for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
- mesh = meshes[meshIndex];
- if (mesh.isBlocked) {
- continue;
- }
- this._totalVertices.addCount(mesh.getTotalVertices(), false);
- if (!mesh.isReady() || (checkIsEnabled && !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
- meshLOD = mesh.getLOD(this.activeCamera);
- if (meshLOD === undefined || meshLOD === null) {
- 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);
- if (meshLOD !== mesh) {
- meshLOD._activate(this._renderId);
- }
- this._activeMesh(mesh, meshLOD);
- }
- }
- this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
- // Particle systems
- if (this.particlesEnabled) {
- this.onBeforeParticlesRenderingObservable.notifyObservers(this);
- for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
- var particleSystem = this.particleSystems[particleIndex];
- if (!particleSystem.isStarted() || !particleSystem.emitter) {
- continue;
- }
- var emitter = particleSystem.emitter;
- if (!emitter.position || emitter.isEnabled()) {
- this._activeParticleSystems.push(particleSystem);
- particleSystem.animate();
- this._renderingManager.dispatchParticles(particleSystem);
- }
- }
- this.onAfterParticlesRenderingObservable.notifyObservers(this);
- }
- };
- Scene.prototype._activeMesh = function (sourceMesh, mesh) {
- if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
- if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
- mesh.skeleton.prepare();
- }
- if (!mesh.computeBonesUsingShaders) {
- this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
- }
- }
- if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
- var boundingInfo = sourceMesh.getBoundingInfo();
- this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
- }
- if (mesh !== undefined && mesh !== null
- && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
- // Submeshes Octrees
- var len;
- var subMeshes;
- if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
- var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
- len = intersections.length;
- subMeshes = intersections.data;
- }
- else {
- subMeshes = mesh.subMeshes;
- len = subMeshes.length;
- }
- for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
- subMesh = subMeshes[subIndex];
- this._evaluateSubMesh(subMesh, mesh);
- }
- }
- };
- Scene.prototype.updateTransformMatrix = function (force) {
- if (!this.activeCamera) {
- return;
- }
- this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
- };
- Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
- this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
- };
- Scene.prototype._renderForCamera = function (camera) {
- if (camera && camera._skipRendering) {
- return;
- }
- 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.activeCamera.update();
- this.updateTransformMatrix();
- if (camera._alternateCamera) {
- this.updateAlternateTransformMatrix(camera._alternateCamera);
- this._alternateRendering = true;
- }
- this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
- // Meshes
- this._evaluateActiveMeshes();
- // Software skinning
- for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
- var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
- mesh.applySkeleton(mesh.skeleton);
- }
- // Render targets
- this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
- var needsRestoreFrameBuffer = false;
- if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
- this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
- }
- 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++;
- needsRestoreFrameBuffer = true; // Restore back buffer
- }
- // Render HighlightLayer Texture
- var stencilState = this._engine.getStencilBuffer();
- var renderhighlights = false;
- if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
- this._intermediateRendering = true;
- for (var i = 0; i < this.highlightLayers.length; i++) {
- var highlightLayer = this.highlightLayers[i];
- if (highlightLayer.shouldRender() &&
- (!highlightLayer.camera ||
- (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
- (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
- renderhighlights = true;
- var renderTarget = highlightLayer._mainTexture;
- if (renderTarget._shouldRender()) {
- this._renderId++;
- renderTarget.render(false, false);
- needsRestoreFrameBuffer = true;
- }
- }
- }
- this._intermediateRendering = false;
- this._renderId++;
- }
- if (needsRestoreFrameBuffer) {
- engine.restoreDefaultFramebuffer(); // Restore back buffer
- }
- this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
- // Prepare Frame
- this.postProcessManager._prepareFrame();
- // 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.layerMask & this.activeCamera.layerMask) !== 0)) {
- layer.render();
- }
- }
- engine.setDepthBuffer(true);
- }
- // Activate HighlightLayer stencil
- if (renderhighlights) {
- this._engine.setStencilBuffer(true);
- }
- // Render
- this.onBeforeDrawPhaseObservable.notifyObservers(this);
- this._renderingManager.render(null, null, true, true);
- this.onAfterDrawPhaseObservable.notifyObservers(this);
- // Restore HighlightLayer stencil
- if (renderhighlights) {
- this._engine.setStencilBuffer(stencilState);
- }
- // Bounding boxes
- if (this._boundingBoxRenderer) {
- this._boundingBoxRenderer.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.layerMask & this.activeCamera.layerMask) !== 0)) {
- layer.render();
- }
- }
- engine.setDepthBuffer(true);
- }
- // Highlight Layer
- if (renderhighlights) {
- engine.setDepthBuffer(false);
- for (var i = 0; i < this.highlightLayers.length; i++) {
- if (this.highlightLayers[i].shouldRender()) {
- this.highlightLayers[i].render();
- }
- }
- engine.setDepthBuffer(true);
- }
- // Finalize frame
- this.postProcessManager._finalizeFrame(camera.isIntermediate);
- // Reset some special arrays
- this._renderTargets.reset();
- this._alternateRendering = false;
- 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;
- }
- // Update camera
- if (this.activeCamera) {
- this.activeCamera.update();
- }
- // 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());
- };
- Scene.prototype._checkIntersections = function () {
- for (var index = 0; index < this._meshesForIntersections.length; index++) {
- var sourceMesh = this._meshesForIntersections.data[index];
- if (!sourceMesh.actionManager) {
- continue;
- }
- 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, undefined, 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, undefined, 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 () {
- if (this.isDisposed) {
- return;
- }
- this._activeParticles.fetchNewFrame();
- this._totalVertices.fetchNewFrame();
- this._activeIndices.fetchNewFrame();
- this._activeBones.fetchNewFrame();
- this._meshesForIntersections.reset();
- this.resetCachedMaterial();
- this.onBeforeAnimationsObservable.notifyObservers(this);
- // Actions
- if (this.actionManager) {
- this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
- }
- //Simplification Queue
- if (this.simplificationQueue && !this.simplificationQueue.running) {
- this.simplificationQueue.executeNext();
- }
- if (this._engine.isDeterministicLockStep()) {
- var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
- var defaultFPS = (60.0 / 1000.0);
- var defaultFrameTime = 1000 / 60; // frame time in MS
- if (this._physicsEngine) {
- defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
- }
- var stepsTaken = 0;
- var maxSubSteps = this._engine.getLockstepMaxSteps();
- var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
- internalSteps = Math.min(internalSteps, maxSubSteps);
- do {
- this.onBeforeStepObservable.notifyObservers(this);
- // Animations
- this._animationRatio = defaultFrameTime * defaultFPS;
- this._animate();
- this.onAfterAnimationsObservable.notifyObservers(this);
- // Physics
- if (this._physicsEngine) {
- this.onBeforePhysicsObservable.notifyObservers(this);
- this._physicsEngine._step(defaultFrameTime / 1000);
- this.onAfterPhysicsObservable.notifyObservers(this);
- }
- this.onAfterStepObservable.notifyObservers(this);
- this._currentStepId++;
- stepsTaken++;
- deltaTime -= defaultFrameTime;
- } while (deltaTime > 0 && stepsTaken < internalSteps);
- this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
- }
- else {
- // Animations
- var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
- this._animationRatio = deltaTime * (60.0 / 1000.0);
- this._animate();
- this.onAfterAnimationsObservable.notifyObservers(this);
- // Physics
- if (this._physicsEngine) {
- this.onBeforePhysicsObservable.notifyObservers(this);
- this._physicsEngine._step(deltaTime / 1000.0);
- this.onAfterPhysicsObservable.notifyObservers(this);
- }
- }
- // update gamepad manager
- if (this._gamepadManager && this._gamepadManager._isMonitoring) {
- this._gamepadManager._checkGamepadsStatus();
- }
- // Before render
- this.onBeforeRenderObservable.notifyObservers(this);
- // Customs render targets
- this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
- var engine = this.getEngine();
- var currentActiveCamera = this.activeCamera;
- if (this.renderTargetsEnabled) {
- BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
- this._intermediateRendering = true;
- 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._intermediateRendering = false;
- this._renderId++;
- }
- // Restore back buffer
- if (this.customRenderTargets.length > 0) {
- engine.restoreDefaultFramebuffer();
- }
- this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
- 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
- if (this.autoClearDepthAndStencil || this.autoClear) {
- this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
- }
- // 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() && light.shadowEnabled && shadowGenerator) {
- var shadowMap = (shadowGenerator.getShadowMap());
- if (this.textures.indexOf(shadowMap) !== -1) {
- this._renderTargets.push(shadowMap);
- }
- }
- }
- }
- // Depth renderer
- if (this._depthRenderer) {
- this._renderTargets.push(this._depthRenderer.getDepthMap());
- }
- // Geometry renderer
- if (this._geometryBufferRenderer) {
- this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
- }
- // RenderPipeline
- if (this._postProcessRenderPipelineManager) {
- this._postProcessRenderPipelineManager.update();
- }
- // Multi-cameras?
- if (this.activeCameras.length > 0) {
- for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
- if (cameraIndex > 0) {
- this._engine.clear(null, false, true, 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++) {
- var data = this._toBeDisposed.data[index];
- if (data) {
- data.dispose();
- }
- this._toBeDisposed[index] = null;
- }
- this._toBeDisposed.reset();
- if (this.dumpNextRenderTargets) {
- this.dumpNextRenderTargets = false;
- }
- this._activeBones.addCount(0, true);
- this._activeIndices.addCount(0, true);
- this._activeParticles.addCount(0, true);
- };
- Scene.prototype._updateAudioParameters = function () {
- if (!this.audioEnabled || !this._mainSoundTrack || (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) {
- audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
- // for VR cameras
- if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
- listeningCamera = listeningCamera.rigCameras[0];
- }
- var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
- var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
- cameraDirection.normalize();
- // To avoid some errors on GearVR
- if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
- 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.enableGeometryBufferRenderer = function (ratio) {
- if (ratio === void 0) { ratio = 1; }
- if (this._geometryBufferRenderer) {
- return this._geometryBufferRenderer;
- }
- this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
- if (!this._geometryBufferRenderer.isSupported) {
- this._geometryBufferRenderer = null;
- }
- return this._geometryBufferRenderer;
- };
- Scene.prototype.disableGeometryBufferRenderer = function () {
- if (!this._geometryBufferRenderer) {
- return;
- }
- this._geometryBufferRenderer.dispose();
- this._geometryBufferRenderer = 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.morphTargetManagers = [];
- this.importedMeshesFiles = new Array();
- this.stopAllAnimations();
- this.resetCachedMaterial();
- if (this._depthRenderer) {
- this._depthRenderer.dispose();
- }
- if (this._gamepadManager) {
- this._gamepadManager.dispose();
- this._gamepadManager = null;
- }
- // Smart arrays
- if (this.activeCamera) {
- this.activeCamera._activeMeshes.dispose();
- this.activeCamera = null;
- }
- this._activeMeshes.dispose();
- this._renderingManager.dispose();
- this._processedMaterials.dispose();
- this._activeParticleSystems.dispose();
- this._activeSkeletons.dispose();
- this._softwareSkinnedMeshes.dispose();
- this._renderTargets.dispose();
- if (this._boundingBoxRenderer) {
- this._boundingBoxRenderer.dispose();
- }
- this._meshesForIntersections.dispose();
- this._toBeDisposed.dispose();
- // Abort active requests
- for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
- var request = _a[_i];
- request.abort();
- }
- // Debug layer
- if (this._debugLayer) {
- this._debugLayer.hide();
- }
- // Events
- this.onDisposeObservable.notifyObservers(this);
- this.onDisposeObservable.clear();
- this.onBeforeRenderObservable.clear();
- this.onAfterRenderObservable.clear();
- this.OnBeforeRenderTargetsRenderObservable.clear();
- this.OnAfterRenderTargetsRenderObservable.clear();
- this.onAfterStepObservable.clear();
- this.onBeforeStepObservable.clear();
- this.onBeforeActiveMeshesEvaluationObservable.clear();
- this.onAfterActiveMeshesEvaluationObservable.clear();
- this.onBeforeParticlesRenderingObservable.clear();
- this.onAfterParticlesRenderingObservable.clear();
- this.onBeforeSpritesRenderingObservable.clear();
- this.onAfterSpritesRenderingObservable.clear();
- this.onBeforeDrawPhaseObservable.clear();
- this.onAfterDrawPhaseObservable.clear();
- this.onBeforePhysicsObservable.clear();
- this.onAfterPhysicsObservable.clear();
- this.onBeforeAnimationsObservable.clear();
- this.onAfterAnimationsObservable.clear();
- this.onDataLoadedObservable.clear();
- this.detachControl();
- // Release sounds & sounds tracks
- if (BABYLON.AudioEngine) {
- this.disposeSounds();
- }
- // VR Helper
- if (this.VRHelper) {
- this.VRHelper.dispose();
- }
- // Detach cameras
- var canvas = this._engine.getRenderingCanvas();
- if (canvas) {
- var index;
- for (index = 0; index < this.cameras.length; index++) {
- this.cameras[index].detachControl(canvas);
- }
- }
- // Release animation groups
- while (this.animationGroups.length) {
- this.animationGroups[0].dispose();
- }
- // Release lights
- while (this.lights.length) {
- this.lights[0].dispose();
- }
- // Release meshes
- while (this.meshes.length) {
- this.meshes[0].dispose(true);
- }
- while (this.transformNodes.length) {
- this.removeTransformNode(this.transformNodes[0]);
- }
- // Release cameras
- while (this.cameras.length) {
- this.cameras[0].dispose();
- }
- // Release materials
- if (this.defaultMaterial) {
- this.defaultMaterial.dispose();
- }
- while (this.multiMaterials.length) {
- this.multiMaterials[0].dispose();
- }
- 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 postProcesses
- while (this.postProcesses.length) {
- this.postProcesses[0].dispose();
- }
- // Release layers
- while (this.layers.length) {
- this.layers[0].dispose();
- }
- while (this.highlightLayers.length) {
- this.highlightLayers[0].dispose();
- }
- // Release textures
- while (this.textures.length) {
- this.textures[0].dispose();
- }
- // Release UBO
- this._sceneUbo.dispose();
- if (this._alternateSceneUbo) {
- this._alternateSceneUbo.dispose();
- }
- // Post-processes
- this.postProcessManager.dispose();
- if (this._postProcessRenderPipelineManager) {
- this._postProcessRenderPipelineManager.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(true);
- this._isDisposed = true;
- };
- Object.defineProperty(Scene.prototype, "isDisposed", {
- get: function () {
- return this._isDisposed;
- },
- enumerable: true,
- configurable: true
- });
- // Release sounds & sounds tracks
- Scene.prototype.disposeSounds = function () {
- if (!this._mainSoundTrack) {
- return;
- }
- 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];
- if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
- continue;
- }
- mesh.computeWorldMatrix(true);
- var boundingInfo = mesh.getBoundingInfo();
- var minBox = boundingInfo.boundingBox.minimumWorld;
- var maxBox = boundingInfo.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 result = BABYLON.Ray.Zero();
- this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
- return result;
- };
- Scene.prototype.createPickingRayToRef = function (x, y, world, result, 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);
- result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
- return this;
- };
- Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
- var result = BABYLON.Ray.Zero();
- this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
- return result;
- };
- Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
- if (!BABYLON.PickingInfo) {
- return this;
- }
- 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);
- result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
- return this;
- };
- Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
- if (!BABYLON.PickingInfo) {
- return null;
- }
- 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._internalMultiPick = function (rayFunction, predicate) {
- if (!BABYLON.PickingInfo) {
- return null;
- }
- var pickingInfos = new Array();
- 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, false);
- if (!result || !result.hit)
- continue;
- pickingInfos.push(result);
- }
- return pickingInfos;
- };
- Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
- if (!BABYLON.PickingInfo) {
- return null;
- }
- var pickingInfo = null;
- if (!camera) {
- if (!this.activeCamera) {
- return null;
- }
- 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();
- };
- /** Launch a ray to try to pick a mesh in the scene
- * @param x position on screen
- * @param y position on screen
- * @param 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 fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
- * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
- */
- Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
- var _this = this;
- if (!BABYLON.PickingInfo) {
- return null;
- }
- return this._internalPick(function (world) {
- _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
- return _this._tempPickingRay;
- }, predicate, fastCheck);
- };
- /** Launch a ray to try to pick a sprite in the scene
- * @param x position on screen
- * @param y position on screen
- * @param 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 fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
- * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
- */
- Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
- this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
- return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
- };
- /** Use the given ray to pick a mesh in the scene
- * @param ray The ray to use to pick meshes
- * @param 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 fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
- */
- 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);
- if (!_this._cachedRayForTransform) {
- _this._cachedRayForTransform = BABYLON.Ray.Zero();
- }
- BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
- return _this._cachedRayForTransform;
- }, predicate, fastCheck);
- };
- /**
- * Launch a ray to try to pick a mesh in the scene
- * @param x X position on screen
- * @param y Y position on screen
- * @param 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 camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
- */
- Scene.prototype.multiPick = function (x, y, predicate, camera) {
- var _this = this;
- return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
- };
- /**
- * Launch a ray to try to pick a mesh in the scene
- * @param ray Ray to use
- * @param 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
- */
- Scene.prototype.multiPickWithRay = function (ray, predicate) {
- var _this = this;
- return this._internalMultiPick(function (world) {
- if (!_this._pickWithRayInverseMatrix) {
- _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
- }
- world.invertToRef(_this._pickWithRayInverseMatrix);
- if (!_this._cachedRayForTransform) {
- _this._cachedRayForTransform = BABYLON.Ray.Zero();
- }
- BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
- return _this._cachedRayForTransform;
- }, predicate);
- };
- 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 (gravity === void 0) { gravity = null; }
- 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 = null;
- };
- Scene.prototype.isPhysicsEnabled = function () {
- return this._physicsEngine !== undefined;
- };
- Scene.prototype.deleteCompoundImpostor = function (compound) {
- var mesh = compound.parts[0].mesh;
- if (mesh.physicsImpostor) {
- mesh.physicsImpostor.dispose();
- mesh.physicsImpostor = null;
- }
- };
- // Misc.
- Scene.prototype._rebuildGeometries = function () {
- for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
- var geometry = _a[_i];
- geometry._rebuild();
- }
- for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
- var mesh = _c[_b];
- mesh._rebuild();
- }
- if (this.postProcessManager) {
- this.postProcessManager._rebuild();
- }
- for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
- var layer = _e[_d];
- layer._rebuild();
- }
- for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
- var highlightLayer = _g[_f];
- highlightLayer._rebuild();
- }
- if (this._boundingBoxRenderer) {
- this._boundingBoxRenderer._rebuild();
- }
- for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
- var system = _j[_h];
- system.rebuild();
- }
- if (this._postProcessRenderPipelineManager) {
- this._postProcessRenderPipelineManager._rebuild();
- }
- };
- Scene.prototype._rebuildTextures = function () {
- for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
- var texture = _a[_i];
- texture._rebuild();
- }
- this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
- };
- Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
- if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
- if (replace === void 0) { replace = false; }
- if (attachCameraControls === void 0) { attachCameraControls = false; }
- // Dispose existing camera or light in replace mode.
- if (replace) {
- if (this.activeCamera) {
- this.activeCamera.dispose();
- this.activeCamera = null;
- }
- if (this.lights) {
- for (var i = 0; i < this.lights.length; i++) {
- this.lights[i].dispose();
- }
- }
- }
- // Light
- if (this.lights.length === 0) {
- new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
- }
- // Camera
- if (!this.activeCamera) {
- var worldExtends = this.getWorldExtends();
- var worldSize = worldExtends.max.subtract(worldExtends.min);
- var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
- var camera;
- var radius = worldSize.length() * 1.5;
- if (createArcRotateCamera) {
- var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
- arcRotateCamera.lowerRadiusLimit = radius * 0.01;
- arcRotateCamera.wheelPrecision = 100 / radius;
- camera = arcRotateCamera;
- }
- else {
- var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
- freeCamera.setTarget(worldCenter);
- camera = freeCamera;
- }
- camera.minZ = radius * 0.01;
- camera.maxZ = radius * 1000;
- camera.speed = radius * 0.2;
- this.activeCamera = camera;
- var canvas = this.getEngine().getRenderingCanvas();
- if (attachCameraControls && canvas) {
- camera.attachControl(canvas);
- }
- }
- };
- Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
- if (pbr === void 0) { pbr = false; }
- if (scale === void 0) { scale = 1000; }
- if (blur === void 0) { blur = 0; }
- if (environmentTexture) {
- this.environmentTexture = environmentTexture;
- }
- if (!this.environmentTexture) {
- BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
- return null;
- }
- // Skybox
- var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
- if (pbr) {
- var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
- hdrSkyboxMaterial.backFaceCulling = false;
- hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
- if (hdrSkyboxMaterial.reflectionTexture) {
- hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
- }
- hdrSkyboxMaterial.microSurface = 1.0 - blur;
- hdrSkyboxMaterial.disableLighting = true;
- hdrSkyboxMaterial.twoSidedLighting = true;
- hdrSkybox.infiniteDistance = true;
- hdrSkybox.material = hdrSkyboxMaterial;
- }
- else {
- var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
- skyboxMaterial.backFaceCulling = false;
- skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
- if (skyboxMaterial.reflectionTexture) {
- skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
- }
- skyboxMaterial.disableLighting = true;
- hdrSkybox.infiniteDistance = true;
- hdrSkybox.material = skyboxMaterial;
- }
- return hdrSkybox;
- };
- Scene.prototype.createDefaultEnvironment = function (options) {
- if (BABYLON.EnvironmentHelper) {
- return new BABYLON.EnvironmentHelper(options, this);
- }
- return null;
- };
- Scene.prototype.createDefaultVRExperience = function (webVROptions) {
- if (webVROptions === void 0) { webVROptions = {}; }
- return new BABYLON.VRExperienceHelper(this, webVROptions);
- };
- // 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 && 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));
- };
- /**
- * Overrides the default sort function applied in the renderging group to prepare the meshes.
- * This allowed control for front to back rendering or reversly depending of the special needs.
- *
- * @param renderingGroupId The rendering group id corresponding to its index
- * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
- * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
- * @param transparentSortCompareFn The transparent queue comparison function use to sort.
- */
- Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
- if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
- if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
- if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
- this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
- };
- /**
- * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
- *
- * @param renderingGroupId The rendering group id corresponding to its index
- * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
- * @param depth Automatically clears depth between groups if true and autoClear is true.
- * @param stencil Automatically clears stencil between groups if true and autoClear is true.
- */
- Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
- if (depth === void 0) { depth = true; }
- if (stencil === void 0) { stencil = true; }
- this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
- };
- /**
- * Will flag all materials as dirty to trigger new shader compilation
- * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
- */
- Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
- for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
- var material = _a[_i];
- if (predicate && !predicate(material)) {
- continue;
- }
- material.markAsDirty(flag);
- }
- };
- Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
- var _this = this;
- var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
- this._activeRequests.push(request);
- request.onCompleteObservable.add(function (request) {
- _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
- });
- return request;
- };
- // Statics
- Scene._FOGMODE_NONE = 0;
- Scene._FOGMODE_EXP = 1;
- Scene._FOGMODE_EXP2 = 2;
- Scene._FOGMODE_LINEAR = 3;
- Scene._uniqueIdCounter = 0;
- Scene.MinDeltaTime = 1.0;
- Scene.MaxDeltaTime = 1000.0;
- /** The distance in pixel that you have to move to prevent some events */
- Scene.DragMovementThreshold = 10; // in pixels
- /** Time in milliseconds to wait to raise long press events if button is still pressed */
- Scene.LongPressDelay = 500; // in milliseconds
- /** Time in milliseconds with two consecutive clicks will be considered as a double click */
- Scene.DoubleClickDelay = 300; // in milliseconds
- /** If you need to check double click without raising a single click at first click, enable this flag */
- Scene.ExclusiveDoubleClickMode = false;
- return Scene;
- }());
- BABYLON.Scene = Scene;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.scene.js.map
- var BABYLON;
- (function (BABYLON) {
- var Buffer = /** @class */ (function () {
- function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
- if (instanced === void 0) { instanced = false; }
- if (engine instanceof BABYLON.Mesh) {
- this._engine = engine.getScene().getEngine();
- }
- else {
- this._engine = engine;
- }
- this._updatable = updatable;
- this._data = data;
- this._strideSize = stride;
- if (!postponeInternalCreation) {
- this.create();
- }
- this._instanced = instanced;
- this._instanceDivisor = instanced ? 1 : 0;
- }
- Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
- // a lot of these parameters are ignored as they are overriden by the buffer
- return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
- };
- // Properties
- Buffer.prototype.isUpdatable = function () {
- return this._updatable;
- };
- Buffer.prototype.getData = function () {
- return this._data;
- };
- Buffer.prototype.getBuffer = function () {
- return this._buffer;
- };
- Buffer.prototype.getStrideSize = function () {
- return this._strideSize;
- };
- Buffer.prototype.getIsInstanced = function () {
- return this._instanced;
- };
- Object.defineProperty(Buffer.prototype, "instanceDivisor", {
- get: function () {
- return this._instanceDivisor;
- },
- set: function (value) {
- this._instanceDivisor = value;
- if (value == 0) {
- this._instanced = false;
- }
- else {
- this._instanced = true;
- }
- },
- enumerable: true,
- configurable: true
- });
- // Methods
- Buffer.prototype.create = function (data) {
- if (data === void 0) { data = null; }
- if (!data && this._buffer) {
- return; // nothing to do
- }
- data = data || this._data;
- if (!data) {
- return;
- }
- if (!this._buffer) {
- if (this._updatable) {
- this._buffer = this._engine.createDynamicVertexBuffer(data);
- this._data = data;
- }
- else {
- this._buffer = this._engine.createVertexBuffer(data);
- }
- }
- else if (this._updatable) {
- this._engine.updateDynamicVertexBuffer(this._buffer, data);
- this._data = data;
- }
- };
- Buffer.prototype._rebuild = function () {
- this._buffer = null;
- this.create(this._data);
- };
- Buffer.prototype.update = function (data) {
- this.create(data);
- };
- Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
- if (!this._buffer) {
- return;
- }
- if (this._updatable) {
- this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
- this._data = null;
- }
- };
- Buffer.prototype.dispose = function () {
- if (!this._buffer) {
- return;
- }
- if (this._engine._releaseBuffer(this._buffer)) {
- this._buffer = null;
- }
- };
- return Buffer;
- }());
- BABYLON.Buffer = Buffer;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.buffer.js.map
- var BABYLON;
- (function (BABYLON) {
- var VertexBuffer = /** @class */ (function () {
- function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
- if (!stride) {
- // Deduce stride from kind
- switch (kind) {
- case VertexBuffer.PositionKind:
- stride = 3;
- break;
- case VertexBuffer.NormalKind:
- stride = 3;
- break;
- case VertexBuffer.UVKind:
- case VertexBuffer.UV2Kind:
- case VertexBuffer.UV3Kind:
- case VertexBuffer.UV4Kind:
- case VertexBuffer.UV5Kind:
- case VertexBuffer.UV6Kind:
- stride = 2;
- break;
- case VertexBuffer.TangentKind:
- case VertexBuffer.ColorKind:
- stride = 4;
- break;
- case VertexBuffer.MatricesIndicesKind:
- case VertexBuffer.MatricesIndicesExtraKind:
- stride = 4;
- break;
- case VertexBuffer.MatricesWeightsKind:
- case VertexBuffer.MatricesWeightsExtraKind:
- default:
- stride = 4;
- break;
- }
- }
- if (data instanceof BABYLON.Buffer) {
- if (!stride) {
- stride = data.getStrideSize();
- }
- this._buffer = data;
- this._ownsBuffer = false;
- }
- else {
- this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
- this._ownsBuffer = true;
- }
- this._stride = stride;
- this._offset = offset ? offset : 0;
- this._size = size ? size : stride;
- this._kind = kind;
- }
- VertexBuffer.prototype._rebuild = function () {
- if (!this._buffer) {
- return;
- }
- this._buffer._rebuild();
- };
- /**
- * Returns the kind of the VertexBuffer (string).
- */
- VertexBuffer.prototype.getKind = function () {
- return this._kind;
- };
- // Properties
- /**
- * Boolean : is the VertexBuffer updatable ?
- */
- VertexBuffer.prototype.isUpdatable = function () {
- return this._buffer.isUpdatable();
- };
- /**
- * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
- */
- VertexBuffer.prototype.getData = function () {
- return this._buffer.getData();
- };
- /**
- * Returns the WebGLBuffer associated to the VertexBuffer.
- */
- VertexBuffer.prototype.getBuffer = function () {
- return this._buffer.getBuffer();
- };
- /**
- * Returns the stride of the VertexBuffer (integer).
- */
- VertexBuffer.prototype.getStrideSize = function () {
- return this._stride;
- };
- /**
- * Returns the offset (integer).
- */
- VertexBuffer.prototype.getOffset = function () {
- return this._offset;
- };
- /**
- * Returns the VertexBuffer total size (integer).
- */
- VertexBuffer.prototype.getSize = function () {
- return this._size;
- };
- /**
- * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
- */
- VertexBuffer.prototype.getIsInstanced = function () {
- return this._buffer.getIsInstanced();
- };
- /**
- * Returns the instancing divisor, zero for non-instanced (integer).
- */
- VertexBuffer.prototype.getInstanceDivisor = function () {
- return this._buffer.instanceDivisor;
- };
- // Methods
- /**
- * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
- * Returns the created WebGLBuffer.
- */
- VertexBuffer.prototype.create = function (data) {
- return this._buffer.create(data);
- };
- /**
- * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
- * Returns the updated WebGLBuffer.
- */
- VertexBuffer.prototype.update = function (data) {
- return this._buffer.update(data);
- };
- /**
- * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
- * Returns the directly updated WebGLBuffer.
- */
- VertexBuffer.prototype.updateDirectly = function (data, offset) {
- return this._buffer.updateDirectly(data, offset);
- };
- /**
- * Disposes the VertexBuffer and the underlying WebGLBuffer.
- */
- VertexBuffer.prototype.dispose = function () {
- if (this._ownsBuffer) {
- this._buffer.dispose();
- }
- };
- 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, "TangentKind", {
- get: function () {
- return VertexBuffer._TangentKind;
- },
- 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._TangentKind = "tangent";
- 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 = {}));
- //# sourceMappingURL=babylon.vertexBuffer.js.map
- var BABYLON;
- (function (BABYLON) {
- var InternalTexture = /** @class */ (function () {
- function InternalTexture(engine, dataSource) {
- this.onLoadedObservable = new BABYLON.Observable();
- // Private
- this._initialSlot = -1;
- this._designatedSlot = -1;
- this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
- this._references = 1;
- this._engine = engine;
- this._dataSource = dataSource;
- this._webGLTexture = engine._createTexture();
- }
- Object.defineProperty(InternalTexture.prototype, "dataSource", {
- get: function () {
- return this._dataSource;
- },
- enumerable: true,
- configurable: true
- });
- InternalTexture.prototype.incrementReferences = function () {
- this._references++;
- };
- InternalTexture.prototype.updateSize = function (width, height, depth) {
- if (depth === void 0) { depth = 1; }
- this.width = width;
- this.height = height;
- this.depth = depth;
- this.baseWidth = width;
- this.baseHeight = height;
- this.baseDepth = depth;
- this._size = width * height * depth;
- };
- InternalTexture.prototype._rebuild = function () {
- var _this = this;
- var proxy;
- this.isReady = false;
- this._cachedCoordinatesMode = null;
- this._cachedWrapU = null;
- this._cachedWrapV = null;
- this._cachedAnisotropicFilteringLevel = null;
- switch (this._dataSource) {
- case InternalTexture.DATASOURCE_TEMP:
- return;
- case InternalTexture.DATASOURCE_URL:
- proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
- _this.isReady = true;
- }, null, this._buffer, undefined, this.format);
- proxy._swapAndDie(this);
- return;
- case InternalTexture.DATASOURCE_RAW:
- proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
- proxy._swapAndDie(this);
- this.isReady = true;
- return;
- case InternalTexture.DATASOURCE_RAW3D:
- proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
- proxy._swapAndDie(this);
- this.isReady = true;
- return;
- case InternalTexture.DATASOURCE_DYNAMIC:
- proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
- proxy._swapAndDie(this);
- // The engine will make sure to update content so no need to flag it as isReady = true
- return;
- case InternalTexture.DATASOURCE_RENDERTARGET:
- var options = new BABYLON.RenderTargetCreationOptions();
- options.generateDepthBuffer = this._generateDepthBuffer;
- options.generateMipMaps = this.generateMipMaps;
- options.generateStencilBuffer = this._generateStencilBuffer;
- options.samplingMode = this.samplingMode;
- options.type = this.type;
- if (this.isCube) {
- proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
- }
- else {
- var size = {
- width: this.width,
- height: this.height
- };
- proxy = this._engine.createRenderTargetTexture(size, options);
- }
- proxy._swapAndDie(this);
- this.isReady = true;
- return;
- case InternalTexture.DATASOURCE_CUBE:
- proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
- _this.isReady = true;
- }, null, this.format, this._extension);
- proxy._swapAndDie(this);
- return;
- case InternalTexture.DATASOURCE_CUBERAW:
- proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
- proxy._swapAndDie(this);
- this.isReady = true;
- return;
- case InternalTexture.DATASOURCE_CUBEPREFILTERED:
- proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
- if (proxy) {
- proxy._swapAndDie(_this);
- }
- _this.isReady = true;
- }, null, this.format, this._extension);
- return;
- }
- };
- InternalTexture.prototype._swapAndDie = function (target) {
- target._webGLTexture = this._webGLTexture;
- if (this._framebuffer) {
- target._framebuffer = this._framebuffer;
- }
- if (this._depthStencilBuffer) {
- target._depthStencilBuffer = this._depthStencilBuffer;
- }
- if (this._lodTextureHigh) {
- if (target._lodTextureHigh) {
- target._lodTextureHigh.dispose();
- }
- target._lodTextureHigh = this._lodTextureHigh;
- }
- if (this._lodTextureMid) {
- if (target._lodTextureMid) {
- target._lodTextureMid.dispose();
- }
- target._lodTextureMid = this._lodTextureMid;
- }
- if (this._lodTextureLow) {
- if (target._lodTextureLow) {
- target._lodTextureLow.dispose();
- }
- target._lodTextureLow = this._lodTextureLow;
- }
- var cache = this._engine.getLoadedTexturesCache();
- var index = cache.indexOf(this);
- if (index !== -1) {
- cache.splice(index, 1);
- }
- };
- InternalTexture.prototype.dispose = function () {
- if (!this._webGLTexture) {
- return;
- }
- this._references--;
- if (this._references === 0) {
- this._engine._releaseTexture(this);
- this._webGLTexture = null;
- }
- };
- InternalTexture.DATASOURCE_UNKNOWN = 0;
- InternalTexture.DATASOURCE_URL = 1;
- InternalTexture.DATASOURCE_TEMP = 2;
- InternalTexture.DATASOURCE_RAW = 3;
- InternalTexture.DATASOURCE_DYNAMIC = 4;
- InternalTexture.DATASOURCE_RENDERTARGET = 5;
- InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
- InternalTexture.DATASOURCE_CUBE = 7;
- InternalTexture.DATASOURCE_CUBERAW = 8;
- InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
- InternalTexture.DATASOURCE_RAW3D = 10;
- return InternalTexture;
- }());
- BABYLON.InternalTexture = InternalTexture;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.internalTexture.js.map
- var BABYLON;
- (function (BABYLON) {
- var BaseTexture = /** @class */ (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.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
- this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
- this.isCube = false;
- this.is3D = false;
- this.gammaSpace = true;
- this.invertZ = false;
- this.lodLevelInAlpha = false;
- this.lodGenerationOffset = 0.0;
- this.lodGenerationScale = 0.8;
- this.isRenderTarget = false;
- this.animations = new Array();
- /**
- * An event triggered when the texture is disposed.
- * @type {BABYLON.Observable}
- */
- this.onDisposeObservable = new BABYLON.Observable();
- this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
- this._scene = scene || BABYLON.Engine.LastCreatedScene;
- if (this._scene) {
- this._scene.textures.push(this);
- }
- this._uid = null;
- }
- Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
- get: function () {
- return this._hasAlpha;
- },
- set: function (value) {
- if (this._hasAlpha === value) {
- return;
- }
- this._hasAlpha = value;
- if (this._scene) {
- this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
- get: function () {
- return this._coordinatesMode;
- },
- set: function (value) {
- if (this._coordinatesMode === value) {
- return;
- }
- this._coordinatesMode = value;
- if (this._scene) {
- this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(BaseTexture.prototype, "uid", {
- get: function () {
- if (!this._uid) {
- this._uid = BABYLON.Tools.RandomId();
- }
- return this._uid;
- },
- enumerable: true,
- configurable: true
- });
- BaseTexture.prototype.toString = function () {
- return this.name;
- };
- BaseTexture.prototype.getClassName = function () {
- return "BaseTexture";
- };
- Object.defineProperty(BaseTexture.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(BaseTexture.prototype, "isBlocking", {
- get: function () {
- return true;
- },
- enumerable: true,
- configurable: true
- });
- BaseTexture.prototype.getScene = function () {
- return this._scene;
- };
- BaseTexture.prototype.getTextureMatrix = function () {
- return BABYLON.Matrix.IdentityReadOnly;
- };
- BaseTexture.prototype.getReflectionTextureMatrix = function () {
- return BABYLON.Matrix.IdentityReadOnly;
- };
- BaseTexture.prototype.getInternalTexture = function () {
- return this._texture;
- };
- BaseTexture.prototype.isReadyOrNotBlocking = function () {
- return !this.isBlocking || this.isReady();
- };
- BaseTexture.prototype.isReady = function () {
- if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
- this.delayLoad();
- return false;
- }
- if (this._texture) {
- return this._texture.isReady;
- }
- return false;
- };
- BaseTexture.prototype.getSize = function () {
- if (this._texture && this._texture.width) {
- return new BABYLON.Size(this._texture.width, this._texture.height);
- }
- if (this._texture && this._texture._size) {
- return new BABYLON.Size(this._texture._size, this._texture._size);
- }
- return BABYLON.Size.Zero();
- };
- BaseTexture.prototype.getBaseSize = function () {
- if (!this.isReady() || !this._texture)
- return BABYLON.Size.Zero();
- if (this._texture._size) {
- return new BABYLON.Size(this._texture._size, this._texture._size);
- }
- return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
- };
- BaseTexture.prototype.scale = function (ratio) {
- };
- Object.defineProperty(BaseTexture.prototype, "canRescale", {
- get: function () {
- return false;
- },
- enumerable: true,
- configurable: true
- });
- BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
- if (!this._scene) {
- return null;
- }
- var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
- for (var index = 0; index < texturesCache.length; index++) {
- var texturesCacheEntry = texturesCache[index];
- if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
- if (!sampling || sampling === texturesCacheEntry.samplingMode) {
- texturesCacheEntry.incrementReferences();
- return texturesCacheEntry;
- }
- }
- }
- return null;
- };
- BaseTexture.prototype._rebuild = function () {
- };
- BaseTexture.prototype.delayLoad = function () {
- };
- BaseTexture.prototype.clone = function () {
- return null;
- };
- Object.defineProperty(BaseTexture.prototype, "textureType", {
- get: function () {
- if (!this._texture) {
- return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
- }
- return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(BaseTexture.prototype, "textureFormat", {
- get: function () {
- if (!this._texture) {
- return BABYLON.Engine.TEXTUREFORMAT_RGBA;
- }
- return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
- },
- enumerable: true,
- configurable: true
- });
- BaseTexture.prototype.readPixels = function (faceIndex) {
- if (faceIndex === void 0) { faceIndex = 0; }
- if (!this._texture) {
- return null;
- }
- var size = this.getSize();
- var scene = this.getScene();
- if (!scene) {
- return null;
- }
- var engine = scene.getEngine();
- if (this._texture.isCube) {
- return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
- }
- return engine._readTexturePixels(this._texture, size.width, size.height, -1);
- };
- BaseTexture.prototype.releaseInternalTexture = function () {
- if (this._texture) {
- this._texture.dispose();
- this._texture = null;
- }
- };
- Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
- get: function () {
- if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
- return null;
- }
- if (!this._texture._sphericalPolynomial) {
- this._texture._sphericalPolynomial =
- BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
- }
- return this._texture._sphericalPolynomial;
- },
- set: function (value) {
- if (this._texture) {
- this._texture._sphericalPolynomial = value;
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
- get: function () {
- if (this._texture) {
- return this._texture._lodTextureHigh;
- }
- return null;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
- get: function () {
- if (this._texture) {
- return this._texture._lodTextureMid;
- }
- return null;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
- get: function () {
- if (this._texture) {
- return this._texture._lodTextureLow;
- }
- return null;
- },
- enumerable: true,
- configurable: true
- });
- BaseTexture.prototype.dispose = function () {
- if (!this._scene) {
- return;
- }
- // Animations
- this._scene.stopAnimation(this);
- // Remove from scene
- this._scene._removePendingData(this);
- 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
- this.onDisposeObservable.notifyObservers(this);
- this.onDisposeObservable.clear();
- };
- BaseTexture.prototype.serialize = function () {
- if (!this.name) {
- return null;
- }
- var serializationObject = BABYLON.SerializationHelper.Serialize(this);
- // Animations
- BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
- return serializationObject;
- };
- BaseTexture.WhenAllReady = function (textures, callback) {
- var numRemaining = textures.length;
- if (numRemaining === 0) {
- callback();
- return;
- }
- var _loop_1 = function () {
- texture = textures[i];
- if (texture.isReady()) {
- if (--numRemaining === 0) {
- callback();
- }
- }
- else {
- onLoadObservable = texture.onLoadObservable;
- var onLoadCallback_1 = function () {
- onLoadObservable.removeCallback(onLoadCallback_1);
- if (--numRemaining === 0) {
- callback();
- }
- };
- onLoadObservable.add(onLoadCallback_1);
- }
- };
- var texture, onLoadObservable;
- for (var i = 0; i < textures.length; i++) {
- _loop_1();
- }
- };
- BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
- __decorate([
- BABYLON.serialize()
- ], BaseTexture.prototype, "name", void 0);
- __decorate([
- BABYLON.serialize("hasAlpha")
- ], 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("coordinatesMode")
- ], 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, "wrapR", void 0);
- __decorate([
- BABYLON.serialize()
- ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
- __decorate([
- BABYLON.serialize()
- ], BaseTexture.prototype, "isCube", void 0);
- __decorate([
- BABYLON.serialize()
- ], BaseTexture.prototype, "is3D", void 0);
- __decorate([
- BABYLON.serialize()
- ], BaseTexture.prototype, "gammaSpace", void 0);
- __decorate([
- BABYLON.serialize()
- ], BaseTexture.prototype, "invertZ", void 0);
- __decorate([
- BABYLON.serialize()
- ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
- __decorate([
- BABYLON.serialize()
- ], BaseTexture.prototype, "lodGenerationOffset", void 0);
- __decorate([
- BABYLON.serialize()
- ], BaseTexture.prototype, "lodGenerationScale", void 0);
- __decorate([
- BABYLON.serialize()
- ], BaseTexture.prototype, "isRenderTarget", void 0);
- return BaseTexture;
- }());
- BABYLON.BaseTexture = BaseTexture;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.baseTexture.js.map
- var BABYLON;
- (function (BABYLON) {
- var Texture = /** @class */ (function (_super) {
- __extends(Texture, _super);
- function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
- if (noMipmap === void 0) { noMipmap = false; }
- if (invertY === void 0) { invertY = true; }
- 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; }
- var _this = _super.call(this, scene) || this;
- _this.uOffset = 0;
- _this.vOffset = 0;
- _this.uScale = 1.0;
- _this.vScale = 1.0;
- _this.uAng = 0;
- _this.vAng = 0;
- _this.wAng = 0;
- _this._isBlocking = true;
- _this.name = url || "";
- _this.url = url;
- _this._noMipmap = noMipmap;
- _this._invertY = invertY;
- _this._samplingMode = samplingMode;
- _this._buffer = buffer;
- _this._deleteBuffer = deleteBuffer;
- if (format) {
- _this._format = format;
- }
- scene = _this.getScene();
- if (!scene) {
- return _this;
- }
- scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
- var load = function () {
- if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
- _this.onLoadObservable.notifyObservers(_this);
- }
- if (onLoad) {
- onLoad();
- }
- if (!_this.isBlocking && scene) {
- scene.resetCachedMaterial();
- }
- };
- if (!_this.url) {
- _this._delayedOnLoad = load;
- _this._delayedOnError = onError;
- return _this;
- }
- _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
- if (!_this._texture) {
- if (!scene.useDelayedTextureLoading) {
- _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
- if (deleteBuffer) {
- delete _this._buffer;
- }
- }
- else {
- _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
- _this._delayedOnLoad = load;
- _this._delayedOnError = onError;
- }
- }
- else {
- if (_this._texture.isReady) {
- BABYLON.Tools.SetImmediate(function () { return load(); });
- }
- else {
- _this._texture.onLoadedObservable.add(load);
- }
- }
- return _this;
- }
- Object.defineProperty(Texture.prototype, "noMipmap", {
- get: function () {
- return this._noMipmap;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Texture.prototype, "isBlocking", {
- get: function () {
- return this._isBlocking;
- },
- set: function (value) {
- this._isBlocking = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Texture.prototype, "samplingMode", {
- get: function () {
- return this._samplingMode;
- },
- enumerable: true,
- configurable: true
- });
- Texture.prototype.updateURL = function (url) {
- this.url = url;
- this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
- this.delayLoad();
- };
- Texture.prototype.delayLoad = function () {
- var _this = this;
- if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
- return;
- }
- var scene = this.getScene();
- if (!scene) {
- return;
- }
- this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
- this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
- if (!this._texture) {
- this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
- if (this._deleteBuffer) {
- delete this._buffer;
- }
- }
- else {
- if (this._texture.isReady) {
- BABYLON.Tools.SetImmediate(function () {
- if (!_this._delayedOnLoad) {
- return;
- }
- _this._delayedOnLoad();
- });
- }
- else {
- if (this._delayedOnLoad) {
- this._texture.onLoadedObservable.add(this._delayedOnLoad);
- }
- }
- }
- };
- Texture.prototype.updateSamplingMode = function (samplingMode) {
- if (!this._texture) {
- return;
- }
- var scene = this.getScene();
- if (!scene) {
- return;
- }
- this._samplingMode = samplingMode;
- scene.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 () {
- var _this = this;
- 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;
- var scene = this.getScene();
- if (!scene) {
- return this._cachedTextureMatrix;
- }
- scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
- return mat.hasTexture(_this);
- });
- return this._cachedTextureMatrix;
- };
- Texture.prototype.getReflectionTextureMatrix = function () {
- var _this = this;
- var scene = this.getScene();
- if (!scene) {
- return this._cachedTextureMatrix;
- }
- if (this.uOffset === this._cachedUOffset &&
- this.vOffset === this._cachedVOffset &&
- this.uScale === this._cachedUScale &&
- this.vScale === this._cachedVScale &&
- this.coordinatesMode === this._cachedCoordinatesMode) {
- if (this.coordinatesMode === Texture.PROJECTION_MODE) {
- if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
- return this._cachedTextureMatrix;
- }
- }
- else {
- return this._cachedTextureMatrix;
- }
- }
- if (!this._cachedTextureMatrix) {
- this._cachedTextureMatrix = BABYLON.Matrix.Zero();
- }
- if (!this._projectionModeMatrix) {
- this._projectionModeMatrix = BABYLON.Matrix.Zero();
- }
- this._cachedUOffset = this.uOffset;
- this._cachedVOffset = this.vOffset;
- this._cachedUScale = this.uScale;
- this._cachedVScale = this.vScale;
- 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;
- var projectionMatrix = scene.getProjectionMatrix();
- this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
- projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
- break;
- default:
- BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
- break;
- }
- scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
- return (mat.getActiveTextures().indexOf(_this) !== -1);
- });
- return this._cachedTextureMatrix;
- };
- Texture.prototype.clone = function () {
- var _this = this;
- return BABYLON.SerializationHelper.Clone(function () {
- return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
- }, this);
- };
- Object.defineProperty(Texture.prototype, "onLoadObservable", {
- get: function () {
- if (!this._onLoadObservable) {
- this._onLoadObservable = new BABYLON.Observable();
- }
- return this._onLoadObservable;
- },
- enumerable: true,
- configurable: true
- });
- Texture.prototype.serialize = function () {
- var serializationObject = _super.prototype.serialize.call(this);
- if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
- serializationObject.base64String = this._buffer;
- serializationObject.name = serializationObject.name.replace("data:", "");
- }
- return serializationObject;
- };
- Texture.prototype.getClassName = function () {
- return "Texture";
- };
- Texture.prototype.dispose = function () {
- _super.prototype.dispose.call(this);
- if (this.onLoadObservable) {
- this.onLoadObservable.clear();
- this._onLoadObservable = null;
- }
- this._delayedOnLoad = null;
- this._delayedOnError = null;
- };
- // Statics
- Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
- if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
- if (onLoad === void 0) { onLoad = null; }
- if (onError === void 0) { onError = null; }
- if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
- return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
- };
- Texture.Parse = function (parsedTexture, scene, rootUrl) {
- if (parsedTexture.customType) {
- var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
- // Update Sampling Mode
- var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
- if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
- if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
- parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
- }
- }
- return parsedCustomTexture;
- }
- if (parsedTexture.isCube) {
- return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
- }
- if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
- return null;
- }
- var texture = BABYLON.SerializationHelper.Parse(function () {
- var generateMipMaps = true;
- if (parsedTexture.noMipmap) {
- generateMipMaps = false;
- }
- if (parsedTexture.mirrorPlane) {
- var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
- 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, generateMipMaps);
- renderTargetTexture._waitingRenderList = parsedTexture.renderList;
- return renderTargetTexture;
- }
- else {
- var texture;
- if (parsedTexture.base64String) {
- texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
- }
- else {
- texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
- }
- return texture;
- }
- }, parsedTexture, scene);
- // Update Sampling Mode
- if (parsedTexture.samplingMode) {
- var sampling = parsedTexture.samplingMode;
- if (texture._samplingMode !== sampling) {
- texture.updateSamplingMode(sampling);
- }
- }
- // 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;
- };
- Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
- if (deleteBuffer === void 0) { deleteBuffer = false; }
- if (noMipmap === void 0) { noMipmap = false; }
- if (invertY === void 0) { invertY = true; }
- if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
- if (onLoad === void 0) { onLoad = null; }
- if (onError === void 0) { onError = null; }
- if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
- if (name.substr(0, 5) !== "data:") {
- name = "data:" + name;
- }
- return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
- };
- // Constants
- Texture.NEAREST_SAMPLINGMODE = 1;
- Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
- Texture.BILINEAR_SAMPLINGMODE = 2;
- Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
- Texture.TRILINEAR_SAMPLINGMODE = 3;
- Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
- Texture.NEAREST_NEAREST_MIPNEAREST = 4;
- Texture.NEAREST_LINEAR_MIPNEAREST = 5;
- Texture.NEAREST_LINEAR_MIPLINEAR = 6;
- Texture.NEAREST_LINEAR = 7;
- Texture.NEAREST_NEAREST = 8;
- Texture.LINEAR_NEAREST_MIPNEAREST = 9;
- Texture.LINEAR_NEAREST_MIPLINEAR = 10;
- Texture.LINEAR_LINEAR = 11;
- Texture.LINEAR_NEAREST = 12;
- 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.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
- 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);
- __decorate([
- BABYLON.serialize()
- ], Texture.prototype, "isBlocking", null);
- return Texture;
- }(BABYLON.BaseTexture));
- BABYLON.Texture = Texture;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.texture.js.map
- var BABYLON;
- (function (BABYLON) {
- var _InstancesBatch = /** @class */ (function () {
- function _InstancesBatch() {
- this.mustReturn = false;
- this.visibleInstances = new Array();
- this.renderSelf = new Array();
- }
- return _InstancesBatch;
- }());
- BABYLON._InstancesBatch = _InstancesBatch;
- var Mesh = /** @class */ (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.
- * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
- */
- function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
- if (scene === void 0) { scene = null; }
- if (parent === void 0) { parent = null; }
- if (source === void 0) { source = null; }
- if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
- var _this = _super.call(this, name, scene) || this;
- // 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
- // Use by builder only to know what orientation were the mesh build in.
- _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
- _this.overrideMaterialSideOrientation = null;
- _this._areNormalsFrozen = false; // Will be used by ribbons mainly
- // Will be used to save a source mesh reference, If any
- _this._source = null;
- scene = _this.getScene();
- if (source) {
- // Source mesh
- _this._source = source;
- // Geometry
- if (source._geometry) {
- source._geometry.applyToMesh(_this);
- }
- // Deep copy
- BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
- // Metadata
- if (source.metadata && source.metadata.clone) {
- _this.metadata = source.metadata.clone();
- }
- else {
- _this.metadata = source.metadata;
- }
- // Tags
- if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
- BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
- }
- // Parent
- _this.parent = source.parent;
- // Pivot
- _this.setPivotMatrix(source.getPivotMatrix());
- _this.id = name + "." + source.id;
- // Material
- _this.material = source.material;
- var index;
- if (!doNotCloneChildren) {
- // Children
- var directDescendants = source.getDescendants(true);
- for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
- var child = directDescendants[index_1];
- if (child.clone) {
- child.clone(name + "." + child.name, _this);
- }
- }
- }
- // 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;
- }
- return _this;
- }
- 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
- });
- Object.defineProperty(Mesh.prototype, "morphTargetManager", {
- get: function () {
- return this._morphTargetManager;
- },
- set: function (value) {
- if (this._morphTargetManager === value) {
- return;
- }
- this._morphTargetManager = value;
- this._syncGeometryWithMorphTargetManager();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Mesh.prototype, "source", {
- get: function () {
- return this._source;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Mesh.prototype, "isUnIndexed", {
- get: function () {
- return this._unIndexed;
- },
- set: function (value) {
- if (this._unIndexed !== value) {
- this._unIndexed = value;
- this._markSubMeshesAsAttributesDirty();
- }
- },
- enumerable: true,
- configurable: true
- });
- // Methods
- /**
- * Returns the string "Mesh".
- */
- Mesh.prototype.getClassName = function () {
- return "Mesh";
- };
- /**
- * Returns a string.
- * @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) {
- if (this._geometry) {
- var ib = this.getIndices();
- var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- if (vb && ib) {
- ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
- }
- }
- else {
- ret += ", flat shading: UNKNOWN";
- }
- }
- return ret;
- };
- Object.defineProperty(Mesh.prototype, "hasLODLevels", {
- /**
- * True if the mesh has some Levels Of Details (LOD).
- * Returns a boolean.
- */
- 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.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
- * Returns an object Mesh or `null`.
- */
- 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 bSphere;
- if (boundingSphere) {
- bSphere = boundingSphere;
- }
- else {
- var boundingInfo = this.getBoundingInfo();
- bSphere = boundingInfo.boundingSphere;
- }
- var distanceToCamera = bSphere.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 === null || this._geometry === undefined) {
- 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.
- * You can force the copy with forceCopy === true
- * 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, forceCopy) {
- if (!this._geometry) {
- return null;
- }
- return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
- };
- /**
- * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
- * Returns `null` 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 null;
- }
- 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 boolean defining if the vertex data for the requested `kind` is updatable.
- * 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.isVertexBufferUpdatable = function (kind) {
- if (!this._geometry) {
- if (this._delayInfo) {
- return this._delayInfo.indexOf(kind) !== -1;
- }
- return false;
- }
- return this._geometry.isVertexBufferUpdatable(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 = new Array();
- if (this._delayInfo) {
- this._delayInfo.forEach(function (kind, index, array) {
- 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 typed array (Int32Array, Uint32Array, Uint16Array) 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);
- };
- 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.
- * Returns the Mesh.
- */
- Mesh.prototype.freezeNormals = function () {
- this._areNormalsFrozen = true;
- return this;
- };
- /**
- * 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.
- * Returns the Mesh.
- */
- Mesh.prototype.unfreezeNormals = function () {
- this._areNormalsFrozen = false;
- return this;
- };
- Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
- /**
- * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
- */
- set: function (count) {
- this._overridenInstanceCount = count;
- },
- enumerable: true,
- configurable: true
- });
- // Methods
- Mesh.prototype._preActivate = function () {
- var sceneRenderId = this.getScene().getRenderId();
- if (this._preActivateId === sceneRenderId) {
- return this;
- }
- this._preActivateId = sceneRenderId;
- this._visibleInstances = null;
- return this;
- };
- Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
- if (this._visibleInstances) {
- this._visibleInstances.intermediateDefaultRenderId = renderId;
- }
- return this;
- };
- 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);
- return this;
- };
- /**
- * 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.
- * Returns the Mesh.
- */
- Mesh.prototype.refreshBoundingInfo = function () {
- return this._refreshBoundingInfo(false);
- };
- Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
- if (this._boundingInfo && this._boundingInfo.isLocked) {
- return this;
- }
- var data = this._getPositionData(applySkeleton);
- 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();
- return this;
- };
- Mesh.prototype._getPositionData = function (applySkeleton) {
- var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- if (data && applySkeleton && this.skeleton) {
- data = data.slice();
- var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
- var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
- if (matricesWeightsData && matricesIndicesData) {
- 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 = this.skeleton.getTransformMatrices(this);
- var tempVector = BABYLON.Tmp.Vector3[0];
- var finalMatrix = BABYLON.Tmp.Matrix[0];
- var tempMatrix = BABYLON.Tmp.Matrix[1];
- var matWeightIdx = 0;
- for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
- finalMatrix.reset();
- var inf;
- var weight;
- for (inf = 0; inf < 4; inf++) {
- weight = matricesWeightsData[matWeightIdx + inf];
- if (weight <= 0)
- break;
- BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
- finalMatrix.addToSelf(tempMatrix);
- }
- if (needExtras) {
- for (inf = 0; inf < 4; inf++) {
- weight = matricesWeightsExtraData[matWeightIdx + inf];
- if (weight <= 0)
- break;
- BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
- finalMatrix.addToSelf(tempMatrix);
- }
- }
- BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
- tempVector.toArray(data, index);
- }
- }
- }
- return data;
- };
- Mesh.prototype._createGlobalSubMesh = function (force) {
- var totalVertices = this.getTotalVertices();
- if (!totalVertices || !this.getIndices()) {
- return null;
- }
- // Check if we need to recreate the submeshes
- if (this.subMeshes && this.subMeshes.length > 0) {
- var ib = this.getIndices();
- if (!ib) {
- return null;
- }
- var totalIndices = ib.length;
- var needToRecreate = false;
- if (force) {
- needToRecreate = true;
- }
- else {
- for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
- var submesh = _a[_i];
- if (submesh.indexStart + submesh.indexCount >= totalIndices) {
- needToRecreate = true;
- break;
- }
- if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
- needToRecreate = true;
- break;
- }
- }
- }
- if (!needToRecreate) {
- return this.subMeshes[0];
- }
- }
- 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
- *
- * Returns the Mesh.
- */
- Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
- if (updatable === void 0) { updatable = false; }
- 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);
- }
- return this;
- };
- Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
- if (updatable === void 0) { updatable = true; }
- var vb = this.getVertexBuffer(kind);
- if (!vb || vb.isUpdatable() === updatable) {
- return;
- }
- this.setVerticesData(kind, this.getVerticesData(kind), updatable);
- };
- /**
- * Sets the mesh VertexBuffer.
- * Returns the Mesh.
- */
- Mesh.prototype.setVerticesBuffer = function (buffer) {
- if (!this._geometry) {
- this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
- }
- this._geometry.setVerticesBuffer(buffer);
- return this;
- };
- /**
- * 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
- *
- * Returns the Mesh.
- */
- Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
- if (!this._geometry) {
- return this;
- }
- if (!makeItUnique) {
- this._geometry.updateVerticesData(kind, data, updateExtends);
- }
- else {
- this.makeGeometryUnique();
- this.updateVerticesData(kind, data, updateExtends, false);
- }
- return this;
- };
- /**
- * 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.
- * Returns the Mesh.
- */
- Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
- if (computeNormals === void 0) { computeNormals = true; }
- var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- if (!positions) {
- return this;
- }
- positionFunction(positions);
- this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
- if (computeNormals) {
- var indices = this.getIndices();
- var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
- if (!normals) {
- return this;
- }
- BABYLON.VertexData.ComputeNormals(positions, indices, normals);
- this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
- }
- return this;
- };
- /**
- * Creates a un-shared specific occurence of the geometry for the mesh.
- * Returns the Mesh.
- */
- Mesh.prototype.makeGeometryUnique = function () {
- if (!this._geometry) {
- return this;
- }
- var oldGeometry = this._geometry;
- var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
- oldGeometry.releaseForMesh(this, true);
- geometry.applyToMesh(this);
- return this;
- };
- /**
- * Sets the mesh indices.
- * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
- * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
- * 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.
- * Returns the Mesh.
- */
- Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
- if (totalVertices === void 0) { totalVertices = null; }
- if (updatable === void 0) { updatable = false; }
- if (!this._geometry) {
- var vertexData = new BABYLON.VertexData();
- vertexData.indices = indices;
- var scene = this.getScene();
- new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
- }
- else {
- this._geometry.setIndices(indices, totalVertices, updatable);
- }
- return this;
- };
- /**
- * Update the current index buffer
- * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
- * Returns the Mesh.
- */
- Mesh.prototype.updateIndices = function (indices, offset) {
- if (!this._geometry) {
- return this;
- }
- this._geometry.updateIndices(indices, offset);
- return this;
- };
- /**
- * Invert the geometry to move from a right handed system to a left handed one.
- * Returns the Mesh.
- */
- Mesh.prototype.toLeftHanded = function () {
- if (!this._geometry) {
- return this;
- }
- this._geometry.toLeftHanded();
- return this;
- };
- Mesh.prototype._bind = function (subMesh, effect, fillMode) {
- if (!this._geometry) {
- return this;
- }
- 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
- this._geometry._bind(effect, indexToBind);
- return this;
- };
- Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
- if (alternate === void 0) { alternate = false; }
- if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
- return this;
- }
- this.onBeforeDrawObservable.notifyObservers(this);
- var scene = this.getScene();
- var engine = scene.getEngine();
- if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
- // or triangles as points
- engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
- }
- else if (fillMode == BABYLON.Material.WireFrameFillMode) {
- // Triangles as wireframe
- engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
- }
- else {
- engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
- }
- if (scene._isAlternateRenderingEnabled && !alternate) {
- var effect = subMesh.effect || this._effectiveMaterial.getEffect();
- if (!effect || !scene.activeCamera) {
- return this;
- }
- scene._switchToAlternateCameraConfiguration(true);
- this._effectiveMaterial.bindView(effect);
- this._effectiveMaterial.bindViewProjection(effect);
- engine.setViewport(scene.activeCamera._alternateCamera.viewport);
- this._draw(subMesh, fillMode, instancesCount, true);
- engine.setViewport(scene.activeCamera.viewport);
- scene._switchToAlternateCameraConfiguration(false);
- this._effectiveMaterial.bindView(effect);
- this._effectiveMaterial.bindViewProjection(effect);
- }
- return this;
- };
- /**
- * Registers for this mesh a javascript function called just before the rendering process.
- * This function is passed the current mesh.
- * Return the Mesh.
- */
- Mesh.prototype.registerBeforeRender = function (func) {
- this.onBeforeRenderObservable.add(func);
- return this;
- };
- /**
- * Disposes a previously registered javascript function called before the rendering.
- * This function is passed the current mesh.
- * Returns the Mesh.
- */
- Mesh.prototype.unregisterBeforeRender = function (func) {
- this.onBeforeRenderObservable.removeCallback(func);
- return this;
- };
- /**
- * Registers for this mesh a javascript function called just after the rendering is complete.
- * This function is passed the current mesh.
- * Returns the Mesh.
- */
- Mesh.prototype.registerAfterRender = function (func) {
- this.onAfterRenderObservable.add(func);
- return this;
- };
- /**
- * Disposes a previously registered javascript function called after the rendering.
- * This function is passed the current mesh.
- * Return the Mesh.
- */
- Mesh.prototype.unregisterAfterRender = function (func) {
- this.onAfterRenderObservable.removeCallback(func);
- return this;
- };
- 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);
- }
- var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
- if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.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];
- if (!visibleInstances) {
- return this;
- }
- var matricesCount = visibleInstances.length + 1;
- var bufferSize = matricesCount * 16 * 4;
- var currentInstancesBufferSize = this._instancesBufferSize;
- var instancesBuffer = this._instancesBuffer;
- while (this._instancesBufferSize < bufferSize) {
- this._instancesBufferSize *= 2;
- }
- if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
- this._instancesData = new Float32Array(this._instancesBufferSize / 4);
- }
- var offset = 0;
- var instancesCount = 0;
- var world = this.getWorldMatrix();
- if (batch.renderSelf[subMesh._id]) {
- world.copyToArray(this._instancesData, offset);
- offset += 16;
- instancesCount++;
- }
- if (visibleInstances) {
- for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
- var instance = visibleInstances[instanceIndex];
- instance.getWorldMatrix().copyToArray(this._instancesData, offset);
- offset += 16;
- instancesCount++;
- }
- }
- if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
- if (instancesBuffer) {
- instancesBuffer.dispose();
- }
- instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
- this._instancesBuffer = instancesBuffer;
- this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
- this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
- this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
- this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
- }
- else {
- instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
- }
- this._bind(subMesh, effect, fillMode);
- this._draw(subMesh, fillMode, instancesCount);
- engine.unbindInstanceAttributes();
- return this;
- };
- Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
- 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(), effectiveMaterial);
- }
- this._draw(subMesh, fillMode, this._overridenInstanceCount);
- }
- var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
- if (visibleInstancesForSubMesh) {
- for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
- var instance = visibleInstancesForSubMesh[instanceIndex];
- // World
- var world = instance.getWorldMatrix();
- if (onBeforeDraw) {
- onBeforeDraw(true, world, effectiveMaterial);
- }
- // Draw
- this._draw(subMesh, fillMode);
- }
- }
- }
- return this;
- };
- /**
- * 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.
- * Returns the Mesh.
- */
- Mesh.prototype.render = function (subMesh, enableAlphaMode) {
- this.checkOcclusionQuery();
- if (this._isOccluded) {
- return this;
- }
- var scene = this.getScene();
- // Managing instances
- var batch = this._getInstancesRenderList(subMesh._id);
- if (batch.mustReturn) {
- return this;
- }
- // Checking geometry state
- if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
- return this;
- }
- this.onBeforeRenderObservable.notifyObservers(this);
- var engine = scene.getEngine();
- var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
- // Material
- var material = subMesh.getMaterial();
- if (!material) {
- return this;
- }
- this._effectiveMaterial = material;
- if (this._effectiveMaterial.storeEffectOnSubMeshes) {
- if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
- return this;
- }
- }
- else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
- return this;
- }
- // Alpha mode
- if (enableAlphaMode) {
- engine.setAlphaMode(this._effectiveMaterial.alphaMode);
- }
- // Outline - step 1
- var savedDepthWrite = engine.getDepthWrite();
- if (this.renderOutline) {
- engine.setDepthWrite(false);
- scene.getOutlineRenderer().render(subMesh, batch);
- engine.setDepthWrite(savedDepthWrite);
- }
- var effect;
- if (this._effectiveMaterial.storeEffectOnSubMeshes) {
- effect = subMesh.effect;
- }
- else {
- effect = this._effectiveMaterial.getEffect();
- }
- if (!effect) {
- return this;
- }
- var sideOrientation = this.overrideMaterialSideOrientation;
- if (sideOrientation == null) {
- sideOrientation = this._effectiveMaterial.sideOrientation;
- if (this._getWorldMatrixDeterminant() < 0) {
- sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
- }
- }
- var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
- if (this._effectiveMaterial.forceDepthWrite) {
- engine.setDepthWrite(true);
- }
- // Bind
- var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
- if (!hardwareInstancedRendering) {
- this._bind(subMesh, effect, fillMode);
- }
- var world = this.getWorldMatrix();
- if (this._effectiveMaterial.storeEffectOnSubMeshes) {
- this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
- }
- else {
- this._effectiveMaterial.bind(world, this);
- }
- if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
- engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
- this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
- engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
- }
- // Draw
- this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
- // Unbind
- this._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);
- return this;
- };
- Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
- if (isInstance && effectiveMaterial) {
- effectiveMaterial.bindOnlyWorldMatrix(world);
- }
- };
- /**
- * 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];
- var emitter = particleSystem.emitter;
- if (emitter.position && descendants.indexOf(emitter) !== -1) {
- results.push(particleSystem);
- }
- }
- return results;
- };
- Mesh.prototype._checkDelayState = function () {
- var scene = this.getScene();
- if (this._geometry) {
- this._geometry.load(scene);
- }
- else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
- this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
- this._queueLoad(scene);
- }
- return this;
- };
- Mesh.prototype._queueLoad = function (scene) {
- var _this = this;
- scene._addPendingData(this);
- 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.instances.forEach(function (instance) {
- instance._syncSubMeshes();
- });
- _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
- scene._removePendingData(_this);
- }, function () { }, scene.database, getBinaryData);
- return this;
- };
- /**
- * 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 the Mesh.
- */
- Mesh.prototype.setMaterialByID = function (id) {
- var materials = this.getScene().materials;
- var index;
- for (index = materials.length - 1; index > -1; index--) {
- if (materials[index].id === id) {
- this.material = materials[index];
- return this;
- }
- }
- // Multi
- var multiMaterials = this.getScene().multiMaterials;
- for (index = multiMaterials.length - 1; index > -1; index--) {
- if (multiMaterials[index].id === id) {
- this.material = multiMaterials[index];
- return this;
- }
- }
- return this;
- };
- /**
- * Returns as a new array populated with the mesh material and/or skeleton, if any.
- */
- Mesh.prototype.getAnimatables = function () {
- var results = new Array();
- 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.
- * Returns the Mesh.
- */
- Mesh.prototype.bakeTransformIntoVertices = function (transform) {
- // Position
- if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
- return this;
- }
- var submeshes = this.subMeshes.splice(0);
- this._resetPointsArrayCache();
- var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- var temp = new Array();
- 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 this;
- }
- 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();
- }
- // Restore submeshes
- this.releaseSubMeshes();
- this.subMeshes = submeshes;
- return this;
- };
- /**
- * 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/resources/baking_transformations
- * Note that, under the hood, this method sets a new VertexBuffer each call.
- * Returns the Mesh.
- */
- 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();
- return this;
- };
- Object.defineProperty(Mesh.prototype, "_positions", {
- // Cache
- get: function () {
- if (this._geometry) {
- return this._geometry._positions;
- }
- return null;
- },
- enumerable: true,
- configurable: true
- });
- Mesh.prototype._resetPointsArrayCache = function () {
- if (this._geometry) {
- this._geometry._resetPointsArrayCache();
- }
- return this;
- };
- Mesh.prototype._generatePointsArray = function () {
- if (this._geometry) {
- return this._geometry._generatePointsArray();
- }
- return false;
- };
- /**
- * 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.
- * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
- * Returns nothing.
- */
- Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
- var _this = this;
- if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
- this.morphTargetManager = null;
- if (this._geometry) {
- this._geometry.releaseForMesh(this, true);
- }
- // Sources
- var meshes = this.getScene().meshes;
- meshes.forEach(function (abstractMesh) {
- var mesh = abstractMesh;
- if (mesh._source && mesh._source === _this) {
- mesh._source = null;
- }
- });
- this._source = null;
- // Instances
- if (this._instancesBuffer) {
- this._instancesBuffer.dispose();
- this._instancesBuffer = null;
- }
- while (this.instances.length) {
- this.instances[0].dispose();
- }
- // Highlight layers.
- var highlightLayers = this.getScene().highlightLayers;
- for (var i = 0; i < highlightLayers.length; i++) {
- var highlightLayer = highlightLayers[i];
- if (highlightLayer) {
- highlightLayer.removeMesh(this);
- highlightLayer.removeExcludedMesh(this);
- }
- }
- _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
- };
- /**
- * 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.
- * The parameter `uvOffset` is an optional vector2 used to offset UV.
- * The parameter `uvScale` is an optional vector2 used to scale UV.
- *
- * Returns the Mesh.
- */
- Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
- 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, uvOffset, uvScale);
- //execute success callback, if set
- if (onSuccess) {
- onSuccess(_this);
- }
- };
- BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
- return this;
- };
- /**
- * 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.
- * The parameter `uvOffset` is an optional vector2 used to offset UV.
- * The parameter `uvScale` is an optional vector2 used to scale UV.
- *
- * Returns the Mesh.
- */
- Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
- 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 this;
- }
- 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();
- uvOffset = uvOffset || BABYLON.Vector2.Zero();
- uvScale = uvScale || new BABYLON.Vector2(1, 1);
- 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 * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
- var v = ((Math.abs(uv.y * uvScale.y + uvOffset.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);
- return this;
- };
- /**
- * 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 the Mesh.
- * 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];
- BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
- }
- this.synchronizeInstances();
- return this;
- };
- /**
- * 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.
- * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
- * Returns the Mesh.
- */
- 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 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];
- BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
- }
- this._unIndexed = true;
- this.synchronizeInstances();
- return this;
- };
- /**
- * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
- * This method returns the Mesh.
- * 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) && vertex_data.normals) {
- for (i = 0; i < vertex_data.normals.length; i++) {
- vertex_data.normals[i] *= -1;
- }
- }
- if (vertex_data.indices) {
- 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);
- return 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 the Mesh.
- */
- Mesh.prototype.synchronizeInstances = function () {
- for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
- var instance = this.instances[instanceIndex];
- instance._syncSubMeshes();
- }
- return this;
- };
- /**
- * Simplify the mesh according to the given array of settings.
- * Function will return immediately and will simplify async. It returns the Mesh.
- * @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
- });
- return this;
- };
- /**
- * 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.
- * Returns the Mesh.
- * @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);
- if (!positions || !indices) {
- return this;
- }
- var vectorPositions = new Array();
- for (var pos = 0; pos < positions.length; pos = pos + 3) {
- vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
- }
- var dupes = new Array();
- 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);
- }
- });
- return this;
- };
- Mesh.prototype.serialize = function (serializationObject) {
- serializationObject.name = this.name;
- serializationObject.id = this.id;
- serializationObject.type = this.getClassName();
- if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
- serializationObject.tags = BABYLON.Tags.GetTags(this);
- }
- serializationObject.position = this.position.asArray();
- if (this.rotationQuaternion) {
- serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
- }
- else if (this.rotation) {
- serializationObject.rotation = this.rotation.asArray();
- }
- serializationObject.scaling = this.scaling.asArray();
- serializationObject.localMatrix = this.getPivotMatrix().asArray();
- serializationObject.isEnabled = this.isEnabled(false);
- serializationObject.isVisible = this.isVisible;
- serializationObject.infiniteDistance = this.infiniteDistance;
- serializationObject.pickable = this.isPickable;
- serializationObject.receiveShadows = this.receiveShadows;
- serializationObject.billboardMode = this.billboardMode;
- serializationObject.visibility = this.visibility;
- serializationObject.checkCollisions = this.checkCollisions;
- serializationObject.isBlocker = this.isBlocker;
- // Parent
- if (this.parent) {
- serializationObject.parentId = this.parent.id;
- }
- // Geometry
- serializationObject.isUnIndexed = this.isUnIndexed;
- var geometry = this._geometry;
- if (geometry) {
- var geometryId = geometry.id;
- serializationObject.geometryId = geometryId;
- // SubMeshes
- serializationObject.subMeshes = [];
- for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
- var subMesh = this.subMeshes[subIndex];
- serializationObject.subMeshes.push({
- materialIndex: subMesh.materialIndex,
- verticesStart: subMesh.verticesStart,
- verticesCount: subMesh.verticesCount,
- indexStart: subMesh.indexStart,
- indexCount: subMesh.indexCount
- });
- }
- }
- // Material
- if (this.material) {
- serializationObject.materialId = this.material.id;
- }
- else {
- this.material = null;
- }
- // Morph targets
- if (this.morphTargetManager) {
- serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
- }
- // Skeleton
- if (this.skeleton) {
- serializationObject.skeletonId = this.skeleton.id;
- }
- // Physics
- //TODO implement correct serialization for physics impostors.
- var impostor = this.getPhysicsImpostor();
- if (impostor) {
- serializationObject.physicsMass = impostor.getParam("mass");
- serializationObject.physicsFriction = impostor.getParam("friction");
- serializationObject.physicsRestitution = impostor.getParam("mass");
- serializationObject.physicsImpostor = impostor.type;
- }
- // Metadata
- if (this.metadata) {
- serializationObject.metadata = this.metadata;
- }
- // Instances
- serializationObject.instances = [];
- for (var index = 0; index < this.instances.length; index++) {
- var instance = this.instances[index];
- var serializationInstance = {
- name: instance.name,
- id: instance.id,
- 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(this, serializationObject);
- serializationObject.ranges = this.serializeAnimationRanges();
- // Layer mask
- serializationObject.layerMask = this.layerMask;
- // Alpha
- serializationObject.alphaIndex = this.alphaIndex;
- serializationObject.hasVertexAlpha = this.hasVertexAlpha;
- // Overlay
- serializationObject.overlayAlpha = this.overlayAlpha;
- serializationObject.overlayColor = this.overlayColor.asArray();
- serializationObject.renderOverlay = this.renderOverlay;
- // Fog
- serializationObject.applyFog = this.applyFog;
- // Action Manager
- if (this.actionManager) {
- serializationObject.actions = this.actionManager.serialize(this.name);
- }
- };
- Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
- if (!this.geometry) {
- return;
- }
- this._markSubMeshesAsAttributesDirty();
- var morphTargetManager = this._morphTargetManager;
- if (morphTargetManager && morphTargetManager.vertexCount) {
- if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
- BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
- this.morphTargetManager = null;
- return;
- }
- for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
- var morphTarget = morphTargetManager.getActiveTarget(index);
- var positions = morphTarget.getPositions();
- if (!positions) {
- BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
- return;
- }
- this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
- var normals = morphTarget.getNormals();
- if (normals) {
- this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
- }
- var tangents = morphTarget.getTangents();
- if (tangents) {
- this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
- }
- }
- }
- else {
- var index = 0;
- // Positions
- while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
- this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
- if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
- this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
- }
- if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
- this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
- }
- index++;
- }
- }
- };
- // Statics
- /**
- * Returns a new Mesh object parsed from the source provided.
- * The parameter `parsedMesh` is the source.
- * 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;
- if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
- mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
- }
- else {
- mesh = new Mesh(parsedMesh.name, scene);
- }
- mesh.id = parsedMesh.id;
- if (BABYLON.Tags) {
- BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
- }
- mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
- if (parsedMesh.metadata !== undefined) {
- mesh.metadata = parsedMesh.metadata;
- }
- 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;
- if (parsedMesh.isBlocker !== undefined) {
- mesh.isBlocker = parsedMesh.isBlocker;
- }
- 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;
- }
- // Overlay
- if (parsedMesh.overlayAlpha !== undefined) {
- mesh.overlayAlpha = parsedMesh.overlayAlpha;
- }
- if (parsedMesh.overlayColor !== undefined) {
- mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
- }
- if (parsedMesh.renderOverlay !== undefined) {
- mesh.renderOverlay = parsedMesh.renderOverlay;
- }
- // Geometry
- mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
- 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;
- }
- // Morph targets
- if (parsedMesh.morphTargetManagerId > -1) {
- mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
- }
- // 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;
- }
- // 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);
- if (parsedInstance.id) {
- instance.id = parsedInstance.id;
- }
- if (BABYLON.Tags) {
- BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
- }
- instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
- if (parsedInstance.parentId) {
- instance._waitingParentId = parsedInstance.parentId;
- }
- 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) {
- if (closeArray === void 0) { closeArray = false; }
- if (updatable === void 0) { updatable = false; }
- 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) {
- if (scene === void 0) { scene = null; }
- 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) {
- if (scene === void 0) { scene = null; }
- 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) {
- if (scene === void 0) { scene = null; }
- if (updatable === void 0) { updatable = false; }
- if (instance === void 0) { instance = null; }
- 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) {
- if (scene === void 0) { scene = null; }
- var options = {
- points: points,
- dashSize: dashSize,
- gapSize: gapSize,
- dashNb: dashNb,
- updatable: updatable,
- instance: instance
- };
- return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
- };
- /**
- * Creates a polygon mesh.
- * Please consider using the same method from the MeshBuilder class instead.
- * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
- * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors.
- * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
- * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
- * Remember you can only change the shape positions, not their number when updating a polygon.
- */
- Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
- var options = {
- shape: shape,
- holes: holes,
- updatable: updatable,
- sideOrientation: sideOrientation
- };
- return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
- };
- /**
- * Creates an extruded polygon mesh, with depth in the Y direction.
- * Please consider using the same method from the MeshBuilder class instead.
- */
- Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
- var options = {
- shape: shape,
- holes: holes,
- depth: depth,
- updatable: updatable,
- sideOrientation: sideOrientation
- };
- return BABYLON.MeshBuilder.ExtrudePolygon(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) {
- if (scene === void 0) { scene = null; }
- 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 :
- * ```javascript
- * var 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 :
- * ```javascript
- * var 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 :
- * ```javascript
- * 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) :
- * ```javascript
- * 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 () {
- if (!this._sourcePositions) {
- var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- if (!source) {
- return this._sourcePositions;
- }
- this._sourcePositions = new Float32Array(source);
- if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
- 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 () {
- if (!this._sourceNormals) {
- var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
- if (!source) {
- return this._sourceNormals;
- }
- this._sourceNormals = new Float32Array(source);
- if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
- this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
- }
- }
- return this._sourceNormals;
- };
- /**
- * Updates the vertex buffer by applying transformation from the bones.
- * Returns the Mesh.
- *
- * @param {skeleton} skeleton to apply
- */
- Mesh.prototype.applySkeleton = function (skeleton) {
- if (!this.geometry) {
- return this;
- }
- if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
- return this;
- }
- 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) {
- var submeshes = this.subMeshes.slice();
- this.setPositionsForCPUSkinning();
- this.subMeshes = submeshes;
- }
- 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) {
- return this;
- }
- 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) {
- return this;
- }
- if (!(normalsData instanceof Float32Array)) {
- normalsData = new Float32Array(normalsData);
- }
- var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
- var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
- if (!matricesWeightsData || !matricesIndicesData) {
- return this;
- }
- 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;
- meshes.forEach(function (mesh, index, array) {
- var boundingInfo = mesh.getBoundingInfo();
- var boundingBox = boundingInfo.boundingBox;
- if (!minVector || !maxVector) {
- minVector = boundingBox.minimumWorld;
- maxVector = boundingBox.maximumWorld;
- }
- else {
- minVector.MinimizeInPlace(boundingBox.minimumWorld);
- maxVector.MaximizeInPlace(boundingBox.maximumWorld);
- }
- });
- if (!minVector || !maxVector) {
- return {
- min: BABYLON.Vector3.Zero(),
- max: BABYLON.Vector3.Zero()
- };
- }
- 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 instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : 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.
- * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
- */
- Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
- 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 = null;
- var otherVertexData;
- var indiceArray = new Array();
- var source = null;
- 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 (subdivideWithSubMeshes) {
- indiceArray.push(meshes[index].getTotalIndices());
- }
- }
- }
- source = source;
- 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();
- }
- }
- }
- // Subdivide
- if (subdivideWithSubMeshes) {
- //-- Suppresions du submesh global
- meshSubclass.releaseSubMeshes();
- index = 0;
- var offset = 0;
- //-- aplique la subdivision en fonction du tableau d'indices
- while (index < indiceArray.length) {
- BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
- offset += indiceArray[index];
- index++;
- }
- }
- 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 = {}));
- //# sourceMappingURL=babylon.mesh.js.map
- var BABYLON;
- (function (BABYLON) {
- var BaseSubMesh = /** @class */ (function () {
- function BaseSubMesh() {
- }
- Object.defineProperty(BaseSubMesh.prototype, "effect", {
- get: function () {
- return this._materialEffect;
- },
- enumerable: true,
- configurable: true
- });
- BaseSubMesh.prototype.setEffect = function (effect, defines) {
- if (defines === void 0) { defines = null; }
- if (this._materialEffect === effect) {
- if (!effect) {
- this._materialDefines = null;
- }
- return;
- }
- this._materialDefines = defines;
- this._materialEffect = effect;
- };
- return BaseSubMesh;
- }());
- BABYLON.BaseSubMesh = BaseSubMesh;
- var SubMesh = /** @class */ (function (_super) {
- __extends(SubMesh, _super);
- function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
- if (createBoundingBox === void 0) { createBoundingBox = true; }
- var _this = _super.call(this) || this;
- _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);
- }
- return _this;
- }
- SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
- if (createBoundingBox === void 0) { createBoundingBox = true; }
- return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
- };
- Object.defineProperty(SubMesh.prototype, "IsGlobal", {
- get: function () {
- return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Returns the submesh BoudingInfo object.
- */
- SubMesh.prototype.getBoundingInfo = function () {
- if (this.IsGlobal) {
- return this._mesh.getBoundingInfo();
- }
- return this._boundingInfo;
- };
- /**
- * Sets the submesh BoundingInfo.
- * Return the SubMesh.
- */
- SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
- this._boundingInfo = boundingInfo;
- return this;
- };
- /**
- * Returns the mesh of the current submesh.
- */
- SubMesh.prototype.getMesh = function () {
- return this._mesh;
- };
- /**
- * Returns the rendering mesh of the submesh.
- */
- SubMesh.prototype.getRenderingMesh = function () {
- return this._renderingMesh;
- };
- /**
- * Returns the submesh material.
- */
- SubMesh.prototype.getMaterial = function () {
- var rootMaterial = this._renderingMesh.material;
- if (rootMaterial === null || rootMaterial === undefined) {
- return this._mesh.getScene().defaultMaterial;
- }
- else if (rootMaterial.getSubMaterial) {
- var multiMaterial = rootMaterial;
- var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
- if (this._currentMaterial !== effectiveMaterial) {
- this._currentMaterial = effectiveMaterial;
- this._materialDefines = null;
- }
- return effectiveMaterial;
- }
- return rootMaterial;
- };
- // Methods
- /**
- * Sets a new updated BoundingInfo object to the submesh.
- * Returns the SubMesh.
- */
- SubMesh.prototype.refreshBoundingInfo = function () {
- this._lastColliderWorldVertices = null;
- if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
- return this;
- }
- var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- if (!data) {
- this._boundingInfo = this._mesh.getBoundingInfo();
- return this;
- }
- var indices = this._renderingMesh.getIndices();
- var extend;
- //is this the only submesh?
- if (this.indexStart === 0 && this.indexCount === indices.length) {
- var boundingInfo = this._renderingMesh.getBoundingInfo();
- //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
- extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.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);
- return this;
- };
- SubMesh.prototype._checkCollision = function (collider) {
- var boundingInfo = this._renderingMesh.getBoundingInfo();
- return boundingInfo._checkCollision(collider);
- };
- /**
- * Updates the submesh BoundingInfo.
- * Returns the Submesh.
- */
- SubMesh.prototype.updateBoundingInfo = function (world) {
- var boundingInfo = this.getBoundingInfo();
- if (!boundingInfo) {
- this.refreshBoundingInfo();
- boundingInfo = this.getBoundingInfo();
- }
- boundingInfo.update(world);
- return this;
- };
- /**
- * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
- * Boolean returned.
- */
- SubMesh.prototype.isInFrustum = function (frustumPlanes) {
- var boundingInfo = this.getBoundingInfo();
- if (!boundingInfo) {
- return false;
- }
- return boundingInfo.isInFrustum(frustumPlanes);
- };
- /**
- * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
- * Boolean returned.
- */
- SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
- var boundingInfo = this.getBoundingInfo();
- if (!boundingInfo) {
- return false;
- }
- return boundingInfo.isCompletelyInFrustum(frustumPlanes);
- };
- /**
- * Renders the submesh.
- * Returns it.
- */
- SubMesh.prototype.render = function (enableAlphaMode) {
- this._renderingMesh.render(this, enableAlphaMode);
- return this;
- };
- /**
- * Returns a new Index Buffer.
- * Type returned : WebGLBuffer.
- */
- 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;
- };
- /**
- * True is the passed Ray intersects the submesh bounding box.
- * Boolean returned.
- */
- SubMesh.prototype.canIntersects = function (ray) {
- var boundingInfo = this.getBoundingInfo();
- if (!boundingInfo) {
- return false;
- }
- return ray.intersectsBox(boundingInfo.boundingBox);
- };
- /**
- * Returns an object IntersectionInfo.
- */
- SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
- var intersectInfo = null;
- // LineMesh first as it's also a Mesh...
- if (BABYLON.LinesMesh && 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;
- };
- SubMesh.prototype._rebuild = function () {
- if (this._linesIndexBuffer) {
- this._linesIndexBuffer = null;
- }
- };
- // Clone
- /**
- * Creates a new Submesh from the passed Mesh.
- */
- 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) {
- var boundingInfo = this.getBoundingInfo();
- if (!boundingInfo) {
- return result;
- }
- result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
- }
- return result;
- };
- // Dispose
- /**
- * Disposes the Submesh.
- * Returns nothing.
- */
- 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
- /**
- * Creates a new Submesh from the passed parameters :
- * - materialIndex (integer) : the index of the main mesh material.
- * - startIndex (integer) : the index where to start the copy in the mesh indices array.
- * - indexCount (integer) : the number of indices to copy then from the startIndex.
- * - mesh (Mesh) : the main mesh to create the submesh from.
- * - renderingMesh (optional Mesh) : rendering mesh.
- */
- 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;
- }(BaseSubMesh));
- BABYLON.SubMesh = SubMesh;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.subMesh.js.map
- var __assign = (this && this.__assign) || Object.assign || function(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
- t[p] = s[p];
- }
- return t;
- };
- var BABYLON;
- (function (BABYLON) {
- var MaterialDefines = /** @class */ (function () {
- function MaterialDefines() {
- this._isDirty = true;
- this._areLightsDirty = true;
- this._areAttributesDirty = true;
- this._areTexturesDirty = true;
- this._areFresnelDirty = true;
- this._areMiscDirty = true;
- this._areImageProcessingDirty = true;
- this._normals = false;
- this._uvs = false;
- this._needNormals = false;
- this._needUVs = false;
- }
- Object.defineProperty(MaterialDefines.prototype, "isDirty", {
- get: function () {
- return this._isDirty;
- },
- enumerable: true,
- configurable: true
- });
- MaterialDefines.prototype.markAsProcessed = function () {
- this._isDirty = false;
- this._areAttributesDirty = false;
- this._areTexturesDirty = false;
- this._areFresnelDirty = false;
- this._areLightsDirty = false;
- this._areMiscDirty = false;
- this._areImageProcessingDirty = false;
- };
- MaterialDefines.prototype.markAsUnprocessed = function () {
- this._isDirty = true;
- };
- MaterialDefines.prototype.markAllAsDirty = function () {
- this._areTexturesDirty = true;
- this._areAttributesDirty = true;
- this._areLightsDirty = true;
- this._areFresnelDirty = true;
- this._areMiscDirty = true;
- this._areImageProcessingDirty = true;
- this._isDirty = true;
- };
- MaterialDefines.prototype.markAsImageProcessingDirty = function () {
- this._areImageProcessingDirty = true;
- this._isDirty = true;
- };
- MaterialDefines.prototype.markAsLightDirty = function () {
- this._areLightsDirty = true;
- this._isDirty = true;
- };
- MaterialDefines.prototype.markAsAttributesDirty = function () {
- this._areAttributesDirty = true;
- this._isDirty = true;
- };
- MaterialDefines.prototype.markAsTexturesDirty = function () {
- this._areTexturesDirty = true;
- this._isDirty = true;
- };
- MaterialDefines.prototype.markAsFresnelDirty = function () {
- this._areFresnelDirty = true;
- this._isDirty = true;
- };
- MaterialDefines.prototype.markAsMiscDirty = function () {
- this._areMiscDirty = true;
- this._isDirty = true;
- };
- MaterialDefines.prototype.rebuild = function () {
- if (this._keys) {
- delete this._keys;
- }
- this._keys = [];
- for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
- var key = _a[_i];
- if (key[0] === "_") {
- continue;
- }
- this._keys.push(key);
- }
- };
- MaterialDefines.prototype.isEqual = function (other) {
- if (this._keys.length !== other._keys.length) {
- return false;
- }
- 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) {
- if (this._keys.length !== other._keys.length) {
- other._keys = this._keys.slice(0);
- }
- 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];
- var value = this[prop];
- if (typeof (value) === "number") {
- result += "#define " + prop + " " + this[prop] + "\n";
- }
- else if (value) {
- result += "#define " + prop + "\n";
- }
- }
- return result;
- };
- return MaterialDefines;
- }());
- BABYLON.MaterialDefines = MaterialDefines;
- var Material = /** @class */ (function () {
- function Material(name, scene, doNotAdd) {
- this.checkReadyOnEveryCall = false;
- this.checkReadyOnlyOnce = false;
- this.state = "";
- this.alpha = 1.0;
- this._backFaceCulling = true;
- this.doNotSerialize = false;
- this.storeEffectOnSubMeshes = false;
- /**
- * An event triggered when the material is disposed.
- * @type {BABYLON.Observable}
- */
- this.onDisposeObservable = new BABYLON.Observable();
- /**
- * An event triggered when the material is bound.
- * @type {BABYLON.Observable}
- */
- this.onBindObservable = new BABYLON.Observable();
- /**
- * An event triggered when the material is unbound.
- * @type {BABYLON.Observable}
- */
- this.onUnBindObservable = new BABYLON.Observable();
- this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
- this._needDepthPrePass = false;
- this.disableDepthWrite = false;
- this.forceDepthWrite = false;
- this.separateCullingPass = false;
- this._fogEnabled = true;
- this.pointSize = 1.0;
- this.zOffset = 0;
- this._wasPreviouslyReady = false;
- this._fillMode = Material.TriangleFillMode;
- this.name = name;
- this.id = name || BABYLON.Tools.RandomId();
- this._scene = scene || BABYLON.Engine.LastCreatedScene;
- if (this._scene.useRightHandedSystem) {
- this.sideOrientation = Material.ClockWiseSideOrientation;
- }
- else {
- this.sideOrientation = Material.CounterClockWiseSideOrientation;
- }
- this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
- this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
- if (!doNotAdd) {
- this._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, "PointListDrawMode", {
- get: function () {
- return Material._PointListDrawMode;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Material, "LineListDrawMode", {
- get: function () {
- return Material._LineListDrawMode;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Material, "LineLoopDrawMode", {
- get: function () {
- return Material._LineLoopDrawMode;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Material, "LineStripDrawMode", {
- get: function () {
- return Material._LineStripDrawMode;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Material, "TriangleStripDrawMode", {
- get: function () {
- return Material._TriangleStripDrawMode;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Material, "TriangleFanDrawMode", {
- get: function () {
- return Material._TriangleFanDrawMode;
- },
- 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, "TextureDirtyFlag", {
- get: function () {
- return Material._TextureDirtyFlag;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Material, "LightDirtyFlag", {
- get: function () {
- return Material._LightDirtyFlag;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Material, "FresnelDirtyFlag", {
- get: function () {
- return Material._FresnelDirtyFlag;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Material, "AttributesDirtyFlag", {
- get: function () {
- return Material._AttributesDirtyFlag;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Material, "MiscDirtyFlag", {
- get: function () {
- return Material._MiscDirtyFlag;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Material.prototype, "backFaceCulling", {
- get: function () {
- return this._backFaceCulling;
- },
- set: function (value) {
- if (this._backFaceCulling === value) {
- return;
- }
- this._backFaceCulling = value;
- this.markAsDirty(Material.TextureDirtyFlag);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Material.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(Material.prototype, "onBind", {
- set: function (callback) {
- if (this._onBindObserver) {
- this.onBindObservable.remove(this._onBindObserver);
- }
- this._onBindObserver = this.onBindObservable.add(callback);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Material.prototype, "alphaMode", {
- get: function () {
- return this._alphaMode;
- },
- set: function (value) {
- if (this._alphaMode === value) {
- return;
- }
- this._alphaMode = value;
- this.markAsDirty(Material.TextureDirtyFlag);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Material.prototype, "needDepthPrePass", {
- get: function () {
- return this._needDepthPrePass;
- },
- set: function (value) {
- if (this._needDepthPrePass === value) {
- return;
- }
- this._needDepthPrePass = value;
- if (this._needDepthPrePass) {
- this.checkReadyOnEveryCall = true;
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Material.prototype, "fogEnabled", {
- get: function () {
- return this._fogEnabled;
- },
- set: function (value) {
- if (this._fogEnabled === value) {
- return;
- }
- this._fogEnabled = value;
- this.markAsDirty(Material.MiscDirtyFlag);
- },
- 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) {
- if (this._fillMode === value) {
- return;
- }
- this._fillMode = value;
- this.markAsDirty(Material.MiscDirtyFlag);
- },
- 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;
- };
- /**
- * Child classes can use it to update shaders
- */
- Material.prototype.getClassName = function () {
- return "Material";
- };
- 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.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
- return false;
- };
- 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.needAlphaBlendingForMesh = function (mesh) {
- return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
- };
- Material.prototype.needAlphaTesting = function () {
- return false;
- };
- Material.prototype.getAlphaTestTexture = function () {
- return null;
- };
- Material.prototype.markDirty = function () {
- this._wasPreviouslyReady = false;
- };
- Material.prototype._preBind = function (effect, overrideOrientation) {
- if (overrideOrientation === void 0) { overrideOrientation = null; }
- var engine = this._scene.getEngine();
- var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
- var reverse = orientation === Material.ClockWiseSideOrientation;
- engine.enableEffect(effect ? effect : this._effect);
- engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
- return reverse;
- };
- Material.prototype.bind = function (world, mesh) {
- };
- Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
- };
- Material.prototype.bindOnlyWorldMatrix = function (world) {
- };
- Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
- sceneUbo.bindToEffect(effect, "Scene");
- };
- Material.prototype.bindView = function (effect) {
- if (!this._useUBO) {
- effect.setMatrix("view", this.getScene().getViewMatrix());
- }
- else {
- this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
- }
- };
- Material.prototype.bindViewProjection = function (effect) {
- if (!this._useUBO) {
- effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
- }
- else {
- this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
- }
- };
- Material.prototype._afterBind = function (mesh) {
- this._scene._cachedMaterial = this;
- if (mesh) {
- this._scene._cachedVisibility = mesh.visibility;
- }
- else {
- this._scene._cachedVisibility = 1;
- }
- if (mesh) {
- this.onBindObservable.notifyObservers(mesh);
- }
- if (this.disableDepthWrite) {
- var engine = this._scene.getEngine();
- this._cachedDepthWriteState = engine.getDepthWrite();
- engine.setDepthWrite(false);
- }
- };
- Material.prototype.unbind = function () {
- this.onUnBindObservable.notifyObservers(this);
- if (this.disableDepthWrite) {
- var engine = this._scene.getEngine();
- engine.setDepthWrite(this._cachedDepthWriteState);
- }
- };
- Material.prototype.getActiveTextures = function () {
- return [];
- };
- Material.prototype.hasTexture = function (texture) {
- return false;
- };
- 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;
- };
- /**
- * Force shader compilation including textures ready check
- */
- Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
- var _this = this;
- var localOptions = __assign({ alphaTest: null, clipPlane: false }, options);
- var subMesh = new BABYLON.BaseSubMesh();
- var scene = this.getScene();
- var engine = scene.getEngine();
- var checkReady = function () {
- if (!_this._scene || !_this._scene.getEngine()) {
- return;
- }
- if (subMesh._materialDefines) {
- subMesh._materialDefines._renderId = -1;
- }
- var alphaTestState = engine.getAlphaTesting();
- var clipPlaneState = scene.clipPlane;
- engine.setAlphaTesting(localOptions.alphaTest || (!_this.needAlphaBlendingForMesh(mesh) && _this.needAlphaTesting()));
- if (localOptions.clipPlane) {
- scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
- }
- if (_this.storeEffectOnSubMeshes) {
- if (_this.isReadyForSubMesh(mesh, subMesh)) {
- if (onCompiled) {
- onCompiled(_this);
- }
- }
- else {
- setTimeout(checkReady, 16);
- }
- }
- else {
- if (_this.isReady(mesh)) {
- if (onCompiled) {
- onCompiled(_this);
- }
- }
- else {
- setTimeout(checkReady, 16);
- }
- }
- engine.setAlphaTesting(alphaTestState);
- if (options && options.clipPlane) {
- scene.clipPlane = clipPlaneState;
- }
- };
- checkReady();
- };
- Material.prototype.markAsDirty = function (flag) {
- if (flag & Material.TextureDirtyFlag) {
- this._markAllSubMeshesAsTexturesDirty();
- }
- if (flag & Material.LightDirtyFlag) {
- this._markAllSubMeshesAsLightsDirty();
- }
- if (flag & Material.FresnelDirtyFlag) {
- this._markAllSubMeshesAsFresnelDirty();
- }
- if (flag & Material.AttributesDirtyFlag) {
- this._markAllSubMeshesAsAttributesDirty();
- }
- if (flag & Material.MiscDirtyFlag) {
- this._markAllSubMeshesAsMiscDirty();
- }
- this.getScene().resetCachedMaterial();
- };
- Material.prototype._markAllSubMeshesAsDirty = function (func) {
- for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
- var mesh = _a[_i];
- if (!mesh.subMeshes) {
- continue;
- }
- for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
- var subMesh = _c[_b];
- if (subMesh.getMaterial() !== this) {
- continue;
- }
- if (!subMesh._materialDefines) {
- continue;
- }
- func(subMesh._materialDefines);
- }
- }
- };
- Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
- this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
- };
- Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
- this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
- };
- Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
- this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
- };
- Material.prototype._markAllSubMeshesAsLightsDirty = function () {
- this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
- };
- Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
- this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
- };
- Material.prototype._markAllSubMeshesAsMiscDirty = function () {
- this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
- };
- 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);
- }
- // 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;
- if (mesh.geometry) {
- var geometry = (mesh.geometry);
- if (this.storeEffectOnSubMeshes) {
- for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
- var subMesh = _a[_i];
- geometry._releaseVertexArrayObject(subMesh._materialEffect);
- if (forceDisposeEffect && subMesh._materialEffect) {
- this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
- }
- }
- }
- else {
- geometry._releaseVertexArrayObject(this._effect);
- }
- }
- }
- }
- this._uniformBuffer.dispose();
- // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
- if (forceDisposeEffect && this._effect) {
- if (!this.storeEffectOnSubMeshes) {
- this._scene.getEngine()._releaseEffect(this._effect);
- }
- this._effect = null;
- }
- // Callback
- this.onDisposeObservable.notifyObservers(this);
- this.onDisposeObservable.clear();
- this.onBindObservable.clear();
- this.onUnBindObservable.clear();
- };
- 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;
- if (BABYLON.Tags) {
- 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);
- }
- if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
- parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
- if (!BABYLON.LegacyPBRMaterial) {
- BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
- return;
- }
- }
- var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
- return materialType.Parse(parsedMaterial, scene, rootUrl);
- ;
- };
- // Triangle views
- Material._TriangleFillMode = 0;
- Material._WireFrameFillMode = 1;
- Material._PointFillMode = 2;
- // Draw modes
- Material._PointListDrawMode = 3;
- Material._LineListDrawMode = 4;
- Material._LineLoopDrawMode = 5;
- Material._LineStripDrawMode = 6;
- Material._TriangleStripDrawMode = 7;
- Material._TriangleFanDrawMode = 8;
- Material._ClockWiseSideOrientation = 0;
- Material._CounterClockWiseSideOrientation = 1;
- Material._TextureDirtyFlag = 1;
- Material._LightDirtyFlag = 2;
- Material._FresnelDirtyFlag = 4;
- Material._AttributesDirtyFlag = 8;
- Material._MiscDirtyFlag = 16;
- __decorate([
- BABYLON.serialize()
- ], Material.prototype, "id", void 0);
- __decorate([
- BABYLON.serialize()
- ], Material.prototype, "name", 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("backFaceCulling")
- ], Material.prototype, "_backFaceCulling", void 0);
- __decorate([
- BABYLON.serialize()
- ], Material.prototype, "sideOrientation", void 0);
- __decorate([
- BABYLON.serialize("alphaMode")
- ], Material.prototype, "_alphaMode", void 0);
- __decorate([
- BABYLON.serialize()
- ], Material.prototype, "_needDepthPrePass", void 0);
- __decorate([
- BABYLON.serialize()
- ], Material.prototype, "disableDepthWrite", void 0);
- __decorate([
- BABYLON.serialize()
- ], Material.prototype, "forceDepthWrite", void 0);
- __decorate([
- BABYLON.serialize()
- ], Material.prototype, "separateCullingPass", void 0);
- __decorate([
- BABYLON.serialize("fogEnabled")
- ], 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 = {}));
- //# sourceMappingURL=babylon.material.js.map
- var BABYLON;
- (function (BABYLON) {
- var UniformBuffer = /** @class */ (function () {
- /**
- * Uniform buffer objects.
- *
- * Handles blocks of uniform on the GPU.
- *
- * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
- *
- * For more information, please refer to :
- * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
- */
- function UniformBuffer(engine, data, dynamic) {
- this._engine = engine;
- this._noUBO = !engine.supportsUniformBuffers;
- this._dynamic = dynamic;
- this._data = data || [];
- this._uniformLocations = {};
- this._uniformSizes = {};
- this._uniformLocationPointer = 0;
- this._needSync = false;
- if (this._noUBO) {
- this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
- this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
- this.updateFloat = this._updateFloatForEffect;
- this.updateFloat2 = this._updateFloat2ForEffect;
- this.updateFloat3 = this._updateFloat3ForEffect;
- this.updateFloat4 = this._updateFloat4ForEffect;
- this.updateMatrix = this._updateMatrixForEffect;
- this.updateVector3 = this._updateVector3ForEffect;
- this.updateVector4 = this._updateVector4ForEffect;
- this.updateColor3 = this._updateColor3ForEffect;
- this.updateColor4 = this._updateColor4ForEffect;
- }
- else {
- this._engine._uniformBuffers.push(this);
- this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
- this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
- this.updateFloat = this._updateFloatForUniform;
- this.updateFloat2 = this._updateFloat2ForUniform;
- this.updateFloat3 = this._updateFloat3ForUniform;
- this.updateFloat4 = this._updateFloat4ForUniform;
- this.updateMatrix = this._updateMatrixForUniform;
- this.updateVector3 = this._updateVector3ForUniform;
- this.updateVector4 = this._updateVector4ForUniform;
- this.updateColor3 = this._updateColor3ForUniform;
- this.updateColor4 = this._updateColor4ForUniform;
- }
- }
- Object.defineProperty(UniformBuffer.prototype, "useUbo", {
- // Properties
- /**
- * Indicates if the buffer is using the WebGL2 UBO implementation,
- * or just falling back on setUniformXXX calls.
- */
- get: function () {
- return !this._noUBO;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(UniformBuffer.prototype, "isSync", {
- /**
- * Indicates if the WebGL underlying uniform buffer is in sync
- * with the javascript cache data.
- */
- get: function () {
- return !this._needSync;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Indicates if the WebGL underlying uniform buffer is dynamic.
- * Also, a dynamic UniformBuffer will disable cache verification and always
- * update the underlying WebGL uniform buffer to the GPU.
- */
- UniformBuffer.prototype.isDynamic = function () {
- return this._dynamic !== undefined;
- };
- /**
- * The data cache on JS side.
- */
- UniformBuffer.prototype.getData = function () {
- return this._bufferData;
- };
- /**
- * The underlying WebGL Uniform buffer.
- */
- UniformBuffer.prototype.getBuffer = function () {
- return this._buffer;
- };
- /**
- * std140 layout specifies how to align data within an UBO structure.
- * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
- * for specs.
- */
- UniformBuffer.prototype._fillAlignment = function (size) {
- // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
- // and 4x4 matrices
- // TODO : change if other types are used
- var alignment;
- if (size <= 2) {
- alignment = size;
- }
- else {
- alignment = 4;
- }
- if ((this._uniformLocationPointer % alignment) !== 0) {
- var oldPointer = this._uniformLocationPointer;
- this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
- var diff = this._uniformLocationPointer - oldPointer;
- for (var i = 0; i < diff; i++) {
- this._data.push(0);
- }
- }
- };
- /**
- * Adds an uniform in the buffer.
- * Warning : the subsequents calls of this function must be in the same order as declared in the shader
- * for the layout to be correct !
- * @param {string} name Name of the uniform, as used in the uniform block in the shader.
- * @param {number|number[]} size Data size, or data directly.
- */
- UniformBuffer.prototype.addUniform = function (name, size) {
- if (this._noUBO) {
- return;
- }
- if (this._uniformLocations[name] !== undefined) {
- // Already existing uniform
- return;
- }
- // This function must be called in the order of the shader layout !
- // size can be the size of the uniform, or data directly
- var data;
- if (size instanceof Array) {
- data = size;
- size = data.length;
- }
- else {
- size = size;
- data = [];
- // Fill with zeros
- for (var i = 0; i < size; i++) {
- data.push(0);
- }
- }
- this._fillAlignment(size);
- this._uniformSizes[name] = size;
- this._uniformLocations[name] = this._uniformLocationPointer;
- this._uniformLocationPointer += size;
- for (var i = 0; i < size; i++) {
- this._data.push(data[i]);
- }
- this._needSync = true;
- };
- /**
- * Wrapper for addUniform.
- * @param {string} name Name of the uniform, as used in the uniform block in the shader.
- * @param {Matrix} mat A 4x4 matrix.
- */
- UniformBuffer.prototype.addMatrix = function (name, mat) {
- this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
- };
- /**
- * Wrapper for addUniform.
- * @param {string} name Name of the uniform, as used in the uniform block in the shader.
- * @param {number} x
- * @param {number} y
- */
- UniformBuffer.prototype.addFloat2 = function (name, x, y) {
- var temp = [x, y];
- this.addUniform(name, temp);
- };
- /**
- * Wrapper for addUniform.
- * @param {string} name Name of the uniform, as used in the uniform block in the shader.
- * @param {number} x
- * @param {number} y
- * @param {number} z
- */
- UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
- var temp = [x, y, z];
- this.addUniform(name, temp);
- };
- /**
- * Wrapper for addUniform.
- * @param {string} name Name of the uniform, as used in the uniform block in the shader.
- * @param {Color3} color
- */
- UniformBuffer.prototype.addColor3 = function (name, color) {
- var temp = new Array();
- color.toArray(temp);
- this.addUniform(name, temp);
- };
- /**
- * Wrapper for addUniform.
- * @param {string} name Name of the uniform, as used in the uniform block in the shader.
- * @param {Color3} color
- * @param {number} alpha
- */
- UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
- var temp = new Array();
- color.toArray(temp);
- temp.push(alpha);
- this.addUniform(name, temp);
- };
- /**
- * Wrapper for addUniform.
- * @param {string} name Name of the uniform, as used in the uniform block in the shader.
- * @param {Vector3} vector
- */
- UniformBuffer.prototype.addVector3 = function (name, vector) {
- var temp = new Array();
- vector.toArray(temp);
- this.addUniform(name, temp);
- };
- /**
- * Wrapper for addUniform.
- * @param {string} name Name of the uniform, as used in the uniform block in the shader.
- */
- UniformBuffer.prototype.addMatrix3x3 = function (name) {
- this.addUniform(name, 12);
- };
- /**
- * Wrapper for addUniform.
- * @param {string} name Name of the uniform, as used in the uniform block in the shader.
- */
- UniformBuffer.prototype.addMatrix2x2 = function (name) {
- this.addUniform(name, 8);
- };
- /**
- * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
- */
- UniformBuffer.prototype.create = function () {
- if (this._noUBO) {
- return;
- }
- if (this._buffer) {
- return; // nothing to do
- }
- // See spec, alignment must be filled as a vec4
- this._fillAlignment(4);
- this._bufferData = new Float32Array(this._data);
- this._rebuild();
- this._needSync = true;
- };
- UniformBuffer.prototype._rebuild = function () {
- if (this._noUBO) {
- return;
- }
- if (this._dynamic) {
- this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
- }
- else {
- this._buffer = this._engine.createUniformBuffer(this._bufferData);
- }
- };
- /**
- * Updates the WebGL Uniform Buffer on the GPU.
- * If the `dynamic` flag is set to true, no cache comparison is done.
- * Otherwise, the buffer will be updated only if the cache differs.
- */
- UniformBuffer.prototype.update = function () {
- if (!this._buffer) {
- this.create();
- return;
- }
- if (!this._dynamic && !this._needSync) {
- return;
- }
- this._engine.updateUniformBuffer(this._buffer, this._bufferData);
- this._needSync = false;
- };
- /**
- * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
- * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
- * @param {number[]|Float32Array} data Flattened data
- * @param {number} size Size of the data.
- */
- UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
- var location = this._uniformLocations[uniformName];
- if (location === undefined) {
- if (this._buffer) {
- // Cannot add an uniform if the buffer is already created
- BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
- return;
- }
- this.addUniform(uniformName, size);
- location = this._uniformLocations[uniformName];
- }
- if (!this._buffer) {
- this.create();
- }
- if (!this._dynamic) {
- // Cache for static uniform buffers
- var changed = false;
- for (var i = 0; i < size; i++) {
- if (this._bufferData[location + i] !== data[i]) {
- changed = true;
- this._bufferData[location + i] = data[i];
- }
- }
- this._needSync = this._needSync || changed;
- }
- else {
- // No cache for dynamic
- for (var i = 0; i < size; i++) {
- this._bufferData[location + i] = data[i];
- }
- }
- };
- // Update methods
- UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
- // To match std140, matrix must be realigned
- for (var i = 0; i < 3; i++) {
- UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
- UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
- UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
- UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
- }
- this.updateUniform(name, UniformBuffer._tempBuffer, 12);
- };
- UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
- this._currentEffect.setMatrix3x3(name, matrix);
- };
- UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
- this._currentEffect.setMatrix2x2(name, matrix);
- };
- UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
- // To match std140, matrix must be realigned
- for (var i = 0; i < 2; i++) {
- UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
- UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
- UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
- UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
- }
- this.updateUniform(name, UniformBuffer._tempBuffer, 8);
- };
- UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
- this._currentEffect.setFloat(name, x);
- };
- UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
- UniformBuffer._tempBuffer[0] = x;
- this.updateUniform(name, UniformBuffer._tempBuffer, 1);
- };
- UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
- if (suffix === void 0) { suffix = ""; }
- this._currentEffect.setFloat2(name + suffix, x, y);
- };
- UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
- if (suffix === void 0) { suffix = ""; }
- UniformBuffer._tempBuffer[0] = x;
- UniformBuffer._tempBuffer[1] = y;
- this.updateUniform(name, UniformBuffer._tempBuffer, 2);
- };
- UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
- if (suffix === void 0) { suffix = ""; }
- this._currentEffect.setFloat3(name + suffix, x, y, z);
- };
- UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
- if (suffix === void 0) { suffix = ""; }
- UniformBuffer._tempBuffer[0] = x;
- UniformBuffer._tempBuffer[1] = y;
- UniformBuffer._tempBuffer[2] = z;
- this.updateUniform(name, UniformBuffer._tempBuffer, 3);
- };
- UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
- if (suffix === void 0) { suffix = ""; }
- this._currentEffect.setFloat4(name + suffix, x, y, z, w);
- };
- UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
- if (suffix === void 0) { suffix = ""; }
- UniformBuffer._tempBuffer[0] = x;
- UniformBuffer._tempBuffer[1] = y;
- UniformBuffer._tempBuffer[2] = z;
- UniformBuffer._tempBuffer[3] = w;
- this.updateUniform(name, UniformBuffer._tempBuffer, 4);
- };
- UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
- this._currentEffect.setMatrix(name, mat);
- };
- UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
- this.updateUniform(name, mat.toArray(), 16);
- };
- UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
- this._currentEffect.setVector3(name, vector);
- };
- UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
- vector.toArray(UniformBuffer._tempBuffer);
- this.updateUniform(name, UniformBuffer._tempBuffer, 3);
- };
- UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
- this._currentEffect.setVector4(name, vector);
- };
- UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
- vector.toArray(UniformBuffer._tempBuffer);
- this.updateUniform(name, UniformBuffer._tempBuffer, 4);
- };
- UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
- if (suffix === void 0) { suffix = ""; }
- this._currentEffect.setColor3(name + suffix, color);
- };
- UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
- if (suffix === void 0) { suffix = ""; }
- color.toArray(UniformBuffer._tempBuffer);
- this.updateUniform(name, UniformBuffer._tempBuffer, 3);
- };
- UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
- if (suffix === void 0) { suffix = ""; }
- this._currentEffect.setColor4(name + suffix, color, alpha);
- };
- UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
- if (suffix === void 0) { suffix = ""; }
- color.toArray(UniformBuffer._tempBuffer);
- UniformBuffer._tempBuffer[3] = alpha;
- this.updateUniform(name, UniformBuffer._tempBuffer, 4);
- };
- /**
- * Sets a sampler uniform on the effect.
- * @param {string} name Name of the sampler.
- * @param {Texture} texture
- */
- UniformBuffer.prototype.setTexture = function (name, texture) {
- this._currentEffect.setTexture(name, texture);
- };
- /**
- * Directly updates the value of the uniform in the cache AND on the GPU.
- * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
- * @param {number[]|Float32Array} data Flattened data
- */
- UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
- this.updateUniform(uniformName, data, data.length);
- this.update();
- };
- /**
- * Binds this uniform buffer to an effect.
- * @param {Effect} effect
- * @param {string} name Name of the uniform block in the shader.
- */
- UniformBuffer.prototype.bindToEffect = function (effect, name) {
- this._currentEffect = effect;
- if (this._noUBO || !this._buffer) {
- return;
- }
- effect.bindUniformBuffer(this._buffer, name);
- };
- /**
- * Disposes the uniform buffer.
- */
- UniformBuffer.prototype.dispose = function () {
- if (this._noUBO) {
- return;
- }
- var index = this._engine._uniformBuffers.indexOf(this);
- if (index !== -1) {
- this._engine._uniformBuffers.splice(index, 1);
- }
- if (!this._buffer) {
- return;
- }
- if (this._engine._releaseBuffer(this._buffer)) {
- this._buffer = null;
- }
- };
- // Pool for avoiding memory leaks
- UniformBuffer._MAX_UNIFORM_SIZE = 256;
- UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
- return UniformBuffer;
- }());
- BABYLON.UniformBuffer = UniformBuffer;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.uniformBuffer.js.map
- var BABYLON;
- (function (BABYLON) {
- var VertexData = /** @class */ (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.TangentKind:
- this.tangents = 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;
- }
- };
- /**
- * Associates the vertexData to the passed Mesh.
- * Sets it as updatable or not (default `false`).
- * Returns the VertexData.
- */
- VertexData.prototype.applyToMesh = function (mesh, updatable) {
- this._applyTo(mesh, updatable);
- return this;
- };
- /**
- * Associates the vertexData to the passed Geometry.
- * Sets it as updatable or not (default `false`).
- * Returns the VertexData.
- */
- VertexData.prototype.applyToGeometry = function (geometry, updatable) {
- this._applyTo(geometry, updatable);
- return this;
- };
- /**
- * Updates the associated mesh.
- * Returns the VertexData.
- */
- VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
- this._update(mesh);
- return this;
- };
- /**
- * Updates the associated geometry.
- * Returns the VertexData.
- */
- VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
- this._update(geometry);
- return this;
- };
- VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
- if (updatable === void 0) { updatable = false; }
- if (this.positions) {
- meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
- }
- if (this.normals) {
- meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
- }
- if (this.tangents) {
- meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, 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, null, updatable);
- }
- return this;
- };
- 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.tangents) {
- meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, 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, null);
- }
- return this;
- };
- /**
- * Transforms each position and each normal of the vertexData according to the passed Matrix.
- * Returns the VertexData.
- */
- 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;
- }
- }
- if (this.tangents) {
- var tangent = BABYLON.Vector4.Zero();
- var tangentTransformed = BABYLON.Vector4.Zero();
- for (index = 0; index < this.tangents.length; index += 4) {
- BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
- BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
- this.tangents[index] = tangentTransformed.x;
- this.tangents[index + 1] = tangentTransformed.y;
- this.tangents[index + 2] = tangentTransformed.z;
- this.tangents[index + 3] = tangentTransformed.w;
- }
- }
- return this;
- };
- /**
- * Merges the passed VertexData into the current one.
- * Returns the modified VertexData.
- */
- VertexData.prototype.merge = function (other, options) {
- options = options || {};
- 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 | Uint32Array | Uint16Array!
- this.indices.push(other.indices[index] + offset);
- }
- }
- this.positions = this._mergeElement(this.positions, other.positions);
- if (!this.positions) {
- return this;
- }
- var count = this.positions.length / 3;
- this.normals = this._mergeElement(this.normals, other.normals, count * 3);
- this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
- this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
- this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
- this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
- this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
- this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
- this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
- this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
- this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
- this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
- this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
- this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
- return this;
- };
- VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
- if (length === void 0) { length = 0; }
- if (defaultValue === void 0) { defaultValue = 0; }
- if (!other && !source) {
- return null;
- }
- if (!other) {
- var padding = new Float32Array(source.length);
- padding.fill(defaultValue);
- return this._mergeElement(source, padding, length);
- }
- if (!source) {
- if (length === 0 || length === other.length) {
- return other;
- }
- var padding = new Float32Array(length - other.length);
- padding.fill(defaultValue);
- return this._mergeElement(padding, other, length);
- }
- 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;
- // source is number[], when other is also use concat
- }
- else if (!isOthTypedArray) {
- return source.concat(other);
- // source is a number[], but other is a Float32Array, loop required
- }
- 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;
- }
- };
- /**
- * Serializes the VertexData.
- * Returns a serialized object.
- */
- VertexData.prototype.serialize = function () {
- var serializationObject = this.serialize();
- if (this.positions) {
- serializationObject.positions = this.positions;
- }
- if (this.normals) {
- serializationObject.normals = this.normals;
- }
- if (this.tangents) {
- serializationObject.tangents = this.tangents;
- }
- 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
- /**
- * Returns the object VertexData associated to the passed mesh.
- */
- VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
- return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
- };
- /**
- * Returns the object VertexData associated to the passed geometry.
- */
- VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
- return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
- };
- VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
- var result = new VertexData();
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
- result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
- result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
- result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
- result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
- result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
- result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
- result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
- result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
- result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
- result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
- result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
- result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
- result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
- }
- if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
- result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
- }
- result.indices = meshOrGeometry.getIndices(copyWhenShared);
- return result;
- };
- /**
- * Creates the vertexData of the Ribbon.
- */
- VertexData.CreateRibbon = function (options) {
- var pathArray = options.pathArray;
- var closeArray = options.closeArray || false;
- var closePath = options.closePath || false;
- var invertUV = options.invertUV || 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 customUV = options.uvs;
- var customColors = options.colors;
- 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; // the final index will be +1 if closePath
- 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 = null;
- var vertex2 = null;
- 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 && vertex2 && vertex1) {
- 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;
- if (customUV) {
- for (p = 0; p < customUV.length; p++) {
- uvs.push(customUV[p].x, customUV[p].y);
- }
- }
- else {
- for (p = 0; p < pathArray.length; p++) {
- for (i = 0; i < minlg + closePathCorr; i++) {
- u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
- v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
- if (invertUV) {
- uvs.push(v, u);
- }
- else {
- 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, options.frontUVs, options.backUVs);
- // Colors
- var colors = null;
- if (customColors) {
- colors = new Float32Array(customColors.length * 4);
- for (var c = 0; c < customColors.length; c++) {
- colors[c * 4] = customColors[c].r;
- colors[c * 4 + 1] = customColors[c].g;
- colors[c * 4 + 2] = customColors[c].b;
- colors[c * 4 + 3] = customColors[c].a;
- }
- }
- // Result
- var vertexData = new VertexData();
- var positions32 = new Float32Array(positions);
- var normals32 = new Float32Array(normals);
- var uvs32 = new Float32Array(uvs);
- vertexData.indices = indices;
- vertexData.positions = positions32;
- vertexData.normals = normals32;
- vertexData.uvs = uvs32;
- if (colors) {
- vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
- }
- if (closePath) {
- vertexData._idx = idx;
- }
- return vertexData;
- };
- /**
- * Creates the VertexData of the Box.
- */
- 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, options.frontUVs, options.backUVs);
- // 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;
- };
- /**
- * Creates the VertexData of the Sphere.
- */
- 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 && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
- var slice = options.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, options.frontUVs, options.backUVs);
- // Result
- var vertexData = new VertexData();
- vertexData.indices = indices;
- vertexData.positions = positions;
- vertexData.normals = normals;
- vertexData.uvs = uvs;
- return vertexData;
- };
- /**
- * Creates the VertexData of the Cylinder or 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 === 0) ? 0 : options.diameterBottom || options.diameter || 1;
- var tessellation = options.tessellation || 24;
- var subdivisions = options.subdivisions || 1;
- var hasRings = options.hasRings ? true : false;
- var enclose = options.enclose ? true : false;
- var arc = options.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 = new Array();
- var positions = new Array();
- var normals = new Array();
- var uvs = new Array();
- var colors = new Array();
- 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++) {
- var i0 = 0;
- var i1 = 0;
- var i2 = 0;
- var i3 = 0;
- for (j = 0; j < tessellation; j++) {
- i0 = i * (e + 1) + j;
- i1 = (i + 1) * (e + 1) + j;
- i2 = i * (e + 1) + (j + 1);
- 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 = null;
- 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 (c) {
- 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 (c) {
- 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, options.frontUVs, options.backUVs);
- var vertexData = new VertexData();
- vertexData.indices = indices;
- vertexData.positions = positions;
- vertexData.normals = normals;
- vertexData.uvs = uvs;
- if (faceColors) {
- vertexData.colors = colors;
- }
- return vertexData;
- };
- /**
- * Creates the VertexData of the Torus.
- */
- 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, options.frontUVs, options.backUVs);
- // Result
- var vertexData = new VertexData();
- vertexData.indices = indices;
- vertexData.positions = positions;
- vertexData.normals = normals;
- vertexData.uvs = uvs;
- return vertexData;
- };
- /**
- * Creates the VertexData of the LineSystem.
- */
- VertexData.CreateLineSystem = function (options) {
- var indices = [];
- var positions = [];
- var lines = options.lines;
- var colors = options.colors;
- var vertexColors = [];
- 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 (colors) {
- var color = colors[l];
- vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
- }
- if (index > 0) {
- indices.push(idx - 1);
- indices.push(idx);
- }
- idx++;
- }
- }
- var vertexData = new VertexData();
- vertexData.indices = indices;
- vertexData.positions = positions;
- if (colors) {
- vertexData.colors = vertexColors;
- }
- return vertexData;
- };
- /**
- * Create the VertexData of the DashedLines.
- */
- 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;
- };
- /**
- * Creates the VertexData of the Ground.
- */
- 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 subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
- var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
- for (row = 0; row <= subdivisionsY; row++) {
- for (col = 0; col <= subdivisionsX; col++) {
- var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (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 / subdivisionsX, 1.0 - row / subdivisionsY);
- }
- }
- for (row = 0; row < subdivisionsY; row++) {
- for (col = 0; col < subdivisionsX; col++) {
- indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
- indices.push(col + 1 + row * (subdivisionsX + 1));
- indices.push(col + row * (subdivisionsX + 1));
- indices.push(col + (row + 1) * (subdivisionsX + 1));
- indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
- indices.push(col + row * (subdivisionsX + 1));
- }
- }
- // Result
- var vertexData = new VertexData();
- vertexData.indices = indices;
- vertexData.positions = positions;
- vertexData.normals = normals;
- vertexData.uvs = uvs;
- return vertexData;
- };
- /**
- * Creates the VertexData of the TiledGround.
- */
- VertexData.CreateTiledGround = function (options) {
- var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
- var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
- var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
- var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
- var subdivisions = options.subdivisions || { w: 1, h: 1 };
- var precision = options.precision || { w: 1, h: 1 };
- var indices = new Array();
- var positions = new Array();
- var normals = new Array();
- var uvs = new Array();
- var row, col, tileRow, tileCol;
- subdivisions.h = (subdivisions.h < 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;
- };
- /**
- * Creates the VertexData of the Ground designed from a heightmap.
- */
- VertexData.CreateGroundFromHeightMap = function (options) {
- var indices = [];
- var positions = [];
- var normals = [];
- var uvs = [];
- var row, col;
- var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
- // 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 * filter.r + g * filter.g + b * filter.b;
- 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;
- };
- /**
- * Creates the VertexData of the Plane.
- */
- 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, options.frontUVs, options.backUVs);
- // Result
- var vertexData = new VertexData();
- vertexData.indices = indices;
- vertexData.positions = positions;
- vertexData.normals = normals;
- vertexData.uvs = uvs;
- return vertexData;
- };
- /**
- * Creates the VertexData of the Disc or regular Polygon.
- */
- VertexData.CreateDisc = function (options) {
- var positions = new Array();
- var indices = new Array();
- var normals = new Array();
- var uvs = new Array();
- var radius = options.radius || 0.5;
- var tessellation = options.tessellation || 64;
- var arc = options.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, options.frontUVs, options.backUVs);
- var vertexData = new VertexData();
- vertexData.indices = indices;
- vertexData.positions = positions;
- vertexData.normals = normals;
- vertexData.uvs = uvs;
- return vertexData;
- };
- /**
- * Re-creates the VertexData of the Polygon for sideOrientation.
- */
- VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
- var faceUV = fUV || new Array(3);
- var faceColors = fColors;
- var colors = [];
- // default face colors and UV if undefined
- for (var f = 0; f < 3; 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 positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
- var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
- var indices = polygon.getIndices();
- // set face colours and textures
- var idx = 0;
- var face = 0;
- for (var index = 0; index < normals.length; index += 3) {
- //Edge Face no. 1
- if (Math.abs(normals[index + 1]) < 0.001) {
- face = 1;
- }
- //Top Face no. 0
- if (Math.abs(normals[index + 1] - 1) < 0.001) {
- face = 0;
- }
- //Bottom Face no. 2
- if (Math.abs(normals[index + 1] + 1) < 0.001) {
- face = 2;
- }
- idx = index / 3;
- uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
- uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
- if (faceColors) {
- colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
- }
- }
- // sides
- VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
- // 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;
- };
- /**
- * Creates the VertexData of the IcoSphere.
- */
- 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 = new Array();
- var positions = new Array();
- var normals = new Array();
- var uvs = new Array();
- 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, options.frontUVs, options.backUVs);
- // 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
- /**
- * Creates the VertexData of the Polyhedron.
- */
- 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 && (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 = new Array();
- var indices = new Array();
- var normals = new Array();
- var uvs = new Array();
- var colors = new Array();
- var index = 0;
- var faceIdx = 0; // face cursor in the array "indexes"
- var indexes = new Array();
- 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, options.frontUVs, options.backUVs);
- 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
- /**
- * Creates the VertexData of the Torus Knot.
- */
- VertexData.CreateTorusKnot = function (options) {
- var indices = new Array();
- var positions = new Array();
- var normals = new Array();
- var uvs = new Array();
- 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, options.frontUVs, options.backUVs);
- // 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)
- * options (optional) :
- * facetPositions : optional array of facet positions (vector3)
- * facetNormals : optional array of facet normals (vector3)
- * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
- * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
- * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
- * bbSize : optional bounding box size data, required for facetPartitioning computation
- * bInfo : optional bounding info, required for facetPartitioning computation
- * useRightHandedSystem: optional boolean to for right handed system computation
- * depthSort : optional boolean to enable the facet depth sort computation
- * distanceTo : optional Vector3 to compute the facet depth from this location
- * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
- */
- VertexData.ComputeNormals = function (positions, indices, normals, options) {
- // temporary scalar variables
- var index = 0; // facet index
- var p1p2x = 0.0; // p1p2 vector x coordinate
- var p1p2y = 0.0; // p1p2 vector y coordinate
- var p1p2z = 0.0; // p1p2 vector z coordinate
- var p3p2x = 0.0; // p3p2 vector x coordinate
- var p3p2y = 0.0; // p3p2 vector y coordinate
- var p3p2z = 0.0; // p3p2 vector z coordinate
- var faceNormalx = 0.0; // facet normal x coordinate
- var faceNormaly = 0.0; // facet normal y coordinate
- var faceNormalz = 0.0; // facet normal z coordinate
- var length = 0.0; // facet normal length before normalization
- var v1x = 0; // vector1 x index in the positions array
- var v1y = 0; // vector1 y index in the positions array
- var v1z = 0; // vector1 z index in the positions array
- var v2x = 0; // vector2 x index in the positions array
- var v2y = 0; // vector2 y index in the positions array
- var v2z = 0; // vector2 z index in the positions array
- var v3x = 0; // vector3 x index in the positions array
- var v3y = 0; // vector3 y index in the positions array
- var v3z = 0; // vector3 z index in the positions array
- var computeFacetNormals = false;
- var computeFacetPositions = false;
- var computeFacetPartitioning = false;
- var computeDepthSort = false;
- var faceNormalSign = 1;
- var ratio = 0;
- var distanceTo = null;
- if (options) {
- computeFacetNormals = (options.facetNormals) ? true : false;
- computeFacetPositions = (options.facetPositions) ? true : false;
- computeFacetPartitioning = (options.facetPartitioning) ? true : false;
- faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
- ratio = options.ratio || 0;
- computeDepthSort = (options.depthSort) ? true : false;
- distanceTo = (options.distanceTo);
- if (computeDepthSort) {
- if (distanceTo === undefined) {
- distanceTo = BABYLON.Vector3.Zero();
- }
- var depthSortedFacets = options.depthSortedFacets;
- }
- }
- // facetPartitioning reinit if needed
- var xSubRatio = 0;
- var ySubRatio = 0;
- var zSubRatio = 0;
- var subSq = 0;
- if (computeFacetPartitioning && options && options.bbSize) {
- var ox = 0; // X partitioning index for facet position
- var oy = 0; // Y partinioning index for facet position
- var oz = 0; // Z partinioning index for facet position
- var b1x = 0; // X partitioning index for facet v1 vertex
- var b1y = 0; // Y partitioning index for facet v1 vertex
- var b1z = 0; // z partitioning index for facet v1 vertex
- var b2x = 0; // X partitioning index for facet v2 vertex
- var b2y = 0; // Y partitioning index for facet v2 vertex
- var b2z = 0; // Z partitioning index for facet v2 vertex
- var b3x = 0; // X partitioning index for facet v3 vertex
- var b3y = 0; // Y partitioning index for facet v3 vertex
- var b3z = 0; // Z partitioning index for facet v3 vertex
- var block_idx_o = 0; // facet barycenter block index
- var block_idx_v1 = 0; // v1 vertex block index
- var block_idx_v2 = 0; // v2 vertex block index
- var block_idx_v3 = 0; // v3 vertex block index
- var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
- bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
- xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
- ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
- zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
- subSq = options.subDiv.max * options.subDiv.max;
- options.facetPartitioning.length = 0;
- }
- // reset the normals
- for (index = 0; index < positions.length; index++) {
- normals[index] = 0.0;
- }
- // Loop : 1 indice triplet = 1 facet
- var nbFaces = (indices.length / 3) | 0;
- for (index = 0; index < nbFaces; index++) {
- // get the indexes of the coordinates of each vertex of the facet
- v1x = indices[index * 3] * 3;
- v1y = v1x + 1;
- v1z = v1x + 2;
- v2x = indices[index * 3 + 1] * 3;
- v2y = v2x + 1;
- v2z = v2x + 2;
- v3x = indices[index * 3 + 2] * 3;
- v3y = v3x + 1;
- v3z = v3x + 2;
- p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
- p1p2y = positions[v1y] - positions[v2y];
- p1p2z = positions[v1z] - positions[v2z];
- p3p2x = positions[v3x] - positions[v2x];
- p3p2y = positions[v3y] - positions[v2y];
- p3p2z = positions[v3z] - positions[v2z];
- // compute the face normal with the cross product
- faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
- faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
- faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
- // normalize this normal and store it in the array facetData
- length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
- length = (length === 0) ? 1.0 : length;
- faceNormalx /= length;
- faceNormaly /= length;
- faceNormalz /= length;
- if (computeFacetNormals && options) {
- options.facetNormals[index].x = faceNormalx;
- options.facetNormals[index].y = faceNormaly;
- options.facetNormals[index].z = faceNormalz;
- }
- if (computeFacetPositions && options) {
- // compute and the facet barycenter coordinates in the array facetPositions
- options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
- options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
- options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
- }
- if (computeFacetPartitioning && options) {
- // store the facet indexes in arrays in the main facetPartitioning array :
- // compute each facet vertex (+ facet barycenter) index in the partiniong array
- ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
- oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
- oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
- b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
- b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
- b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
- b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
- b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
- b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
- b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
- b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
- b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
- block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
- block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
- block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
- block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
- options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
- options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
- options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
- options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
- // push each facet index in each block containing the vertex
- options.facetPartitioning[block_idx_v1].push(index);
- if (block_idx_v2 != block_idx_v1) {
- options.facetPartitioning[block_idx_v2].push(index);
- }
- if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
- options.facetPartitioning[block_idx_v3].push(index);
- }
- if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
- options.facetPartitioning[block_idx_o].push(index);
- }
- }
- if (computeDepthSort && options && options.facetPositions) {
- var dsf = depthSortedFacets[index];
- dsf.ind = index * 3;
- dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
- }
- // compute the normals anyway
- normals[v1x] += faceNormalx; // accumulate all the normals per face
- normals[v1y] += faceNormaly;
- normals[v1z] += faceNormalz;
- normals[v2x] += faceNormalx;
- normals[v2y] += faceNormaly;
- normals[v2z] += faceNormalz;
- normals[v3x] += faceNormalx;
- normals[v3y] += faceNormaly;
- normals[v3z] += 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, frontUVs, backUVs) {
- 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;
- var u = 0;
- for (u = 0; u < lu; u++) {
- uvs[u + lu] = uvs[u];
- }
- frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
- backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
- u = 0;
- for (i = 0; i < lu / 2; i++) {
- uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
- uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
- uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
- uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
- u += 2;
- }
- break;
- }
- };
- /**
- * Creates a new VertexData from the imported parameters.
- */
- 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);
- }
- // tangents
- var tangents = parsedVertexData.tangents;
- if (tangents) {
- vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
- }
- // 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 = {}));
- //# sourceMappingURL=babylon.mesh.vertexData.js.map
- var BABYLON;
- (function (BABYLON) {
- var Geometry = /** @class */ (function () {
- function Geometry(id, scene, vertexData, updatable, mesh) {
- if (updatable === void 0) { updatable = false; }
- if (mesh === void 0) { mesh = null; }
- this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
- this._totalVertices = 0;
- this._isDisposed = false;
- this._indexBufferIsUpdatable = false;
- this.id = id;
- this._engine = scene.getEngine();
- this._meshes = [];
- this._scene = scene;
- //Init vertex buffer cache
- this._vertexBuffers = {};
- this._indices = [];
- this._updatable = updatable;
- // vertexData
- if (vertexData) {
- this.setAllVerticesData(vertexData, updatable);
- }
- else {
- this._totalVertices = 0;
- this._indices = [];
- }
- if (this._engine.getCaps().vertexArrayObject) {
- this._vertexArrayObjects = {};
- }
- // applyToMesh
- if (mesh) {
- if (mesh.getClassName() === "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
- });
- Geometry.CreateGeometryForMesh = function (mesh) {
- var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
- geometry.applyToMesh(mesh);
- return geometry;
- };
- 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;
- };
- Object.defineProperty(Geometry.prototype, "doNotSerialize", {
- get: function () {
- for (var index = 0; index < this._meshes.length; index++) {
- if (!this._meshes[index].doNotSerialize) {
- return false;
- }
- }
- return true;
- },
- enumerable: true,
- configurable: true
- });
- Geometry.prototype._rebuild = function () {
- if (this._vertexArrayObjects) {
- this._vertexArrayObjects = {};
- }
- // Index buffer
- if (this._meshes.length !== 0 && this._indices) {
- this._indexBuffer = this._engine.createIndexBuffer(this._indices);
- }
- // Vertex buffers
- for (var key in this._vertexBuffers) {
- var vertexBuffer = this._vertexBuffers[key];
- vertexBuffer._rebuild();
- }
- };
- Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
- vertexData.applyToGeometry(this, updatable);
- this.notifyUpdate();
- };
- Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
- if (updatable === void 0) { updatable = false; }
- var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
- this.setVerticesBuffer(buffer);
- };
- Geometry.prototype.removeVerticesData = function (kind) {
- if (this._vertexBuffers[kind]) {
- this._vertexBuffers[kind].dispose();
- delete this._vertexBuffers[kind];
- }
- };
- Geometry.prototype.setVerticesBuffer = function (buffer) {
- var kind = buffer.getKind();
- if (this._vertexBuffers[kind]) {
- this._vertexBuffers[kind].dispose();
- }
- this._vertexBuffers[kind] = buffer;
- if (kind === BABYLON.VertexBuffer.PositionKind) {
- var data = buffer.getData();
- var stride = buffer.getStrideSize();
- this._totalVertices = data.length / stride;
- this.updateExtend(data, stride);
- this._resetPointsArrayCache();
- var meshes = this._meshes;
- var numOfMeshes = meshes.length;
- for (var index = 0; index < numOfMeshes; index++) {
- var mesh = meshes[index];
- mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
- mesh._createGlobalSubMesh(false);
- mesh.computeWorldMatrix(true);
- }
- }
- this.notifyUpdate(kind);
- if (this._vertexArrayObjects) {
- this._disposeVertexArrayObjects();
- this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
- }
- };
- 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) {
- if (updateExtends === void 0) { updateExtends = false; }
- 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;
- this._resetPointsArrayCache();
- for (var index = 0; index < numOfMeshes; index++) {
- var mesh = meshes[index];
- 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._bind = function (effect, indexToBind) {
- if (!effect) {
- return;
- }
- if (indexToBind === undefined) {
- indexToBind = this._indexBuffer;
- }
- var vbs = this.getVertexBuffers();
- if (!vbs) {
- return;
- }
- if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
- this._engine.bindBuffers(vbs, indexToBind, effect);
- return;
- }
- // Using VAO
- if (!this._vertexArrayObjects[effect.key]) {
- this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
- }
- this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
- };
- Geometry.prototype.getTotalVertices = function () {
- if (!this.isReady()) {
- return 0;
- }
- return this._totalVertices;
- };
- Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
- var vertexBuffer = this.getVertexBuffer(kind);
- if (!vertexBuffer) {
- return null;
- }
- var orig = vertexBuffer.getData();
- if (!forceCopy && (!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;
- }
- };
- /**
- * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
- * 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
- */
- Geometry.prototype.isVertexBufferUpdatable = function (kind) {
- var vb = this._vertexBuffers[kind];
- if (!vb) {
- return false;
- }
- return vb.isUpdatable();
- };
- 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.updateIndices = function (indices, offset) {
- if (!this._indexBuffer) {
- return;
- }
- if (!this._indexBufferIsUpdatable) {
- this.setIndices(indices, null, true);
- }
- else {
- this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
- }
- };
- Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
- if (totalVertices === void 0) { totalVertices = null; }
- if (updatable === void 0) { updatable = false; }
- if (this._indexBuffer) {
- this._engine._releaseBuffer(this._indexBuffer);
- }
- this._disposeVertexArrayObjects();
- this._indices = indices;
- this._indexBufferIsUpdatable = updatable;
- if (this._meshes.length !== 0 && this._indices) {
- this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
- }
- if (totalVertices != undefined) {
- this._totalVertices = totalVertices;
- }
- var meshes = this._meshes;
- var numOfMeshes = meshes.length;
- for (var index = 0; index < numOfMeshes; index++) {
- meshes[index]._createGlobalSubMesh(true);
- }
- 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._releaseVertexArrayObject = function (effect) {
- if (effect === void 0) { effect = null; }
- if (!effect || !this._vertexArrayObjects) {
- return;
- }
- if (this._vertexArrayObjects[effect.key]) {
- this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
- delete this._vertexArrayObjects[effect.key];
- }
- };
- Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
- var meshes = this._meshes;
- var index = meshes.indexOf(mesh);
- if (index === -1) {
- return;
- }
- 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, stride) {
- 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, stride);
- };
- Geometry.prototype._applyToMesh = function (mesh) {
- var numOfMeshes = this._meshes.length;
- // vertexBuffers
- for (var kind in this._vertexBuffers) {
- if (numOfMeshes === 1) {
- this._vertexBuffers[kind].create();
- }
- var buffer = this._vertexBuffers[kind].getBuffer();
- if (buffer)
- buffer.references = numOfMeshes;
- if (kind === BABYLON.VertexBuffer.PositionKind) {
- if (!this._extend) {
- this.updateExtend(this._vertexBuffers[kind].getData());
- }
- mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
- mesh._createGlobalSubMesh(false);
- //bounding info was just created again, world matrix should be applied again.
- mesh._updateBoundingInfo();
- }
- }
- // indexBuffer
- if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
- 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);
- }
- for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
- var mesh = _a[_i];
- mesh._markSubMeshesAsAttributesDirty();
- }
- };
- Geometry.prototype.load = function (scene, onLoaded) {
- if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
- return;
- }
- if (this.isReady()) {
- if (onLoaded) {
- onLoaded();
- }
- return;
- }
- this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
- this._queueLoad(scene, onLoaded);
- };
- Geometry.prototype._queueLoad = function (scene, onLoaded) {
- var _this = this;
- if (!this.delayLoadingFile) {
- return;
- }
- scene._addPendingData(this);
- scene._loadFile(this.delayLoadingFile, function (data) {
- if (!_this._delayLoadingFunction) {
- return;
- }
- _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();
- }
- }, undefined, true);
- };
- /**
- * Invert the geometry to move from a right handed system to a left handed one.
- */
- Geometry.prototype.toLeftHanded = function () {
- // Flip faces
- var tIndices = this.getIndices(false);
- if (tIndices != null && tIndices.length > 0) {
- for (var i = 0; i < tIndices.length; i += 3) {
- var tTemp = tIndices[i + 0];
- tIndices[i + 0] = tIndices[i + 2];
- tIndices[i + 2] = tTemp;
- }
- this.setIndices(tIndices);
- }
- // Negate position.z
- var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
- if (tPositions != null && tPositions.length > 0) {
- for (var i = 0; i < tPositions.length; i += 3) {
- tPositions[i + 2] = -tPositions[i + 2];
- }
- this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
- }
- // Negate normal.z
- var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
- if (tNormals != null && tNormals.length > 0) {
- for (var i = 0; i < tNormals.length; i += 3) {
- tNormals[i + 2] = -tNormals[i + 2];
- }
- this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
- }
- };
- // Cache
- Geometry.prototype._resetPointsArrayCache = function () {
- this._positions = null;
- };
- Geometry.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;
- };
- Geometry.prototype.isDisposed = function () {
- return this._isDisposed;
- };
- Geometry.prototype._disposeVertexArrayObjects = function () {
- if (this._vertexArrayObjects) {
- for (var kind in this._vertexArrayObjects) {
- this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
- }
- this._vertexArrayObjects = {};
- }
- };
- 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 = [];
- this._disposeVertexArrayObjects();
- 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();
- if (indices) {
- 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) {
- var vb = this.getVertexBuffer(kind);
- if (vb) {
- updatable = vb.isUpdatable();
- stopChecking = !updatable;
- }
- }
- }
- var geometry = new Geometry(id, this._scene, vertexData, updatable);
- 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;
- serializationObject.updatable = this._updatable;
- if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
- serializationObject.tags = BABYLON.Tags.GetTags(this);
- }
- return serializationObject;
- };
- Geometry.prototype.toNumberArray = function (origin) {
- if (Array.isArray(origin)) {
- return origin;
- }
- else {
- return Array.prototype.slice.call(origin);
- }
- };
- Geometry.prototype.serializeVerticeData = function () {
- var serializationObject = this.serialize();
- if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
- serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
- if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
- serializationObject.positions._updatable = true;
- }
- }
- if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
- serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
- if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
- serializationObject.normals._updatable = true;
- }
- }
- if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
- serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
- if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
- serializationObject.uvs._updatable = true;
- }
- }
- if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
- serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
- if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
- serializationObject.uv2s._updatable = true;
- }
- }
- if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
- serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
- if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
- serializationObject.uv3s._updatable = true;
- }
- }
- if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
- serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
- if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
- serializationObject.uv4s._updatable = true;
- }
- }
- if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
- serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
- if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
- serializationObject.uv5s._updatable = true;
- }
- }
- if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
- serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
- if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
- serializationObject.uv6s._updatable = true;
- }
- }
- if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
- serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
- if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
- serializationObject.colors._updatable = true;
- }
- }
- if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
- serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
- serializationObject.matricesIndices._isExpanded = true;
- if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
- serializationObject.matricesIndices._updatable = true;
- }
- }
- if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
- serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
- if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
- serializationObject.matricesWeights._updatable = true;
- }
- }
- serializationObject.indices = this.toNumberArray(this.getIndices());
- return serializationObject;
- };
- // Statics
- Geometry.ExtractFromMesh = function (mesh, id) {
- var geometry = mesh._geometry;
- if (!geometry) {
- return null;
- }
- return geometry.copy(id);
- };
- /**
- * You should now use Tools.RandomId(), this method is still here for legacy reasons.
- * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
- * Be aware Math.random() could cause collisions, but:
- * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
- */
- Geometry.RandomId = function () {
- return BABYLON.Tools.RandomId();
- };
- 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, null);
- }
- 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];
- BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
- }
- }
- }
- else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
- mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
- mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
- if (parsedGeometry.uvs) {
- mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
- }
- if (parsedGeometry.uvs2) {
- mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
- }
- if (parsedGeometry.uvs3) {
- mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
- }
- if (parsedGeometry.uvs4) {
- mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
- }
- if (parsedGeometry.uvs5) {
- mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
- }
- if (parsedGeometry.uvs6) {
- mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
- }
- if (parsedGeometry.colors) {
- mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
- }
- 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, parsedGeometry.matricesIndices._updatable);
- }
- else {
- delete parsedGeometry.matricesIndices._isExpanded;
- mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
- }
- }
- 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, parsedGeometry.matricesIndicesExtra._updatable);
- }
- else {
- delete parsedGeometry.matricesIndices._isExpanded;
- mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
- }
- }
- if (parsedGeometry.matricesWeights) {
- Geometry._CleanMatricesWeights(parsedGeometry, mesh);
- mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
- }
- if (parsedGeometry.matricesWeightsExtra) {
- mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
- }
- mesh.setIndices(parsedGeometry.indices, null);
- }
- // SubMeshes
- if (parsedGeometry.subMeshes) {
- mesh.subMeshes = [];
- for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
- var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
- BABYLON.SubMesh.AddToMesh(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
- var sceneOctree = scene.selectionOctree;
- if (sceneOctree !== undefined && sceneOctree !== null) {
- sceneOctree.addMesh(mesh);
- }
- };
- Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
- var epsilon = 1e-3;
- if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
- return;
- }
- var noInfluenceBoneIndex = 0.0;
- if (parsedGeometry.skeletonId > -1) {
- var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
- if (!skeleton) {
- return;
- }
- noInfluenceBoneIndex = skeleton.bones.length;
- }
- else {
- return;
- }
- var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
- var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
- var matricesWeights = parsedGeometry.matricesWeights;
- var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
- var influencers = parsedGeometry.numBoneInfluencer;
- var size = matricesWeights.length;
- for (var i = 0; i < size; i += 4) {
- var weight = 0.0;
- var firstZeroWeight = -1;
- for (var j = 0; j < 4; j++) {
- var w = matricesWeights[i + j];
- weight += w;
- if (w < epsilon && firstZeroWeight < 0) {
- firstZeroWeight = j;
- }
- }
- if (matricesWeightsExtra) {
- for (var j = 0; j < 4; j++) {
- var w = matricesWeightsExtra[i + j];
- weight += w;
- if (w < epsilon && firstZeroWeight < 0) {
- firstZeroWeight = j + 4;
- }
- }
- }
- if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
- firstZeroWeight = influencers - 1;
- }
- if (weight > epsilon) {
- var mweight = 1.0 / weight;
- for (var j = 0; j < 4; j++) {
- matricesWeights[i + j] *= mweight;
- }
- if (matricesWeightsExtra) {
- for (var j = 0; j < 4; j++) {
- matricesWeightsExtra[i + j] *= mweight;
- }
- }
- }
- else {
- if (firstZeroWeight >= 4) {
- matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
- matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
- }
- else {
- matricesWeights[i + firstZeroWeight] = 1.0 - weight;
- matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
- }
- }
- }
- mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
- if (parsedGeometry.matricesWeightsExtra) {
- mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
- }
- };
- 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, undefined, parsedVertexData.updatable);
- if (BABYLON.Tags) {
- 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 //////////////////////////////////////////////
- //export module Geometry.Primitives {
- /// Abstract class
- var _PrimitiveGeometry = /** @class */ (function (_super) {
- __extends(_PrimitiveGeometry, _super);
- function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
- if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
- if (mesh === void 0) { mesh = null; }
- var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
- _this._canBeRegenerated = _canBeRegenerated;
- _this._beingRegenerated = true;
- _this.regenerate();
- _this._beingRegenerated = false;
- return _this;
- }
- _PrimitiveGeometry.prototype.canBeRegenerated = function () {
- return this._canBeRegenerated;
- };
- _PrimitiveGeometry.prototype.regenerate = function () {
- if (!this._canBeRegenerated) {
- return;
- }
- this._beingRegenerated = true;
- this.setAllVerticesData(this._regenerateVertexData(), false);
- this._beingRegenerated = false;
- };
- _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
- return _super.prototype.copy.call(this, id);
- };
- // overrides
- _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
- if (!this._beingRegenerated) {
- return;
- }
- _super.prototype.setAllVerticesData.call(this, vertexData, false);
- };
- _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
- if (!this._beingRegenerated) {
- return;
- }
- _super.prototype.setVerticesData.call(this, kind, data, false);
- };
- // to override
- // protected
- _PrimitiveGeometry.prototype._regenerateVertexData = function () {
- throw new Error("Abstract method");
- };
- _PrimitiveGeometry.prototype.copy = function (id) {
- throw new Error("Must be overriden in sub-classes.");
- };
- _PrimitiveGeometry.prototype.serialize = function () {
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.canBeRegenerated = this.canBeRegenerated();
- return serializationObject;
- };
- return _PrimitiveGeometry;
- }(Geometry));
- BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
- var RibbonGeometry = /** @class */ (function (_super) {
- __extends(RibbonGeometry, _super);
- // Members
- function RibbonGeometry(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
- if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
- var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
- _this.pathArray = pathArray;
- _this.closeArray = closeArray;
- _this.closePath = closePath;
- _this.offset = offset;
- _this.side = side;
- return _this;
- }
- RibbonGeometry.prototype._regenerateVertexData = function () {
- return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
- };
- RibbonGeometry.prototype.copy = function (id) {
- return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
- };
- return RibbonGeometry;
- }(_PrimitiveGeometry));
- BABYLON.RibbonGeometry = RibbonGeometry;
- var BoxGeometry = /** @class */ (function (_super) {
- __extends(BoxGeometry, _super);
- // Members
- function BoxGeometry(id, scene, size, canBeRegenerated, mesh, side) {
- if (mesh === void 0) { mesh = null; }
- if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
- var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
- _this.size = size;
- _this.side = side;
- return _this;
- }
- BoxGeometry.prototype._regenerateVertexData = function () {
- return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
- };
- BoxGeometry.prototype.copy = function (id) {
- return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
- };
- BoxGeometry.prototype.serialize = function () {
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.size = this.size;
- return serializationObject;
- };
- BoxGeometry.Parse = function (parsedBox, scene) {
- if (scene.getGeometryByID(parsedBox.id)) {
- return null; // null since geometry could be something else than a box...
- }
- var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
- if (BABYLON.Tags) {
- BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
- }
- scene.pushGeometry(box, true);
- return box;
- };
- return BoxGeometry;
- }(_PrimitiveGeometry));
- BABYLON.BoxGeometry = BoxGeometry;
- var SphereGeometry = /** @class */ (function (_super) {
- __extends(SphereGeometry, _super);
- function SphereGeometry(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
- if (mesh === void 0) { mesh = null; }
- if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
- var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
- _this.segments = segments;
- _this.diameter = diameter;
- _this.side = side;
- return _this;
- }
- SphereGeometry.prototype._regenerateVertexData = function () {
- return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
- };
- SphereGeometry.prototype.copy = function (id) {
- return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
- };
- SphereGeometry.prototype.serialize = function () {
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.segments = this.segments;
- serializationObject.diameter = this.diameter;
- return serializationObject;
- };
- SphereGeometry.Parse = function (parsedSphere, scene) {
- if (scene.getGeometryByID(parsedSphere.id)) {
- return null; // null since geometry could be something else than a sphere...
- }
- var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
- if (BABYLON.Tags) {
- BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
- }
- scene.pushGeometry(sphere, true);
- return sphere;
- };
- return SphereGeometry;
- }(_PrimitiveGeometry));
- BABYLON.SphereGeometry = SphereGeometry;
- var DiscGeometry = /** @class */ (function (_super) {
- __extends(DiscGeometry, _super);
- // Members
- function DiscGeometry(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
- if (mesh === void 0) { mesh = null; }
- if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
- var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
- _this.radius = radius;
- _this.tessellation = tessellation;
- _this.side = side;
- return _this;
- }
- DiscGeometry.prototype._regenerateVertexData = function () {
- return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
- };
- DiscGeometry.prototype.copy = function (id) {
- return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
- };
- return DiscGeometry;
- }(_PrimitiveGeometry));
- BABYLON.DiscGeometry = DiscGeometry;
- var CylinderGeometry = /** @class */ (function (_super) {
- __extends(CylinderGeometry, _super);
- function CylinderGeometry(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
- if (subdivisions === void 0) { subdivisions = 1; }
- if (mesh === void 0) { mesh = null; }
- if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
- var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
- _this.height = height;
- _this.diameterTop = diameterTop;
- _this.diameterBottom = diameterBottom;
- _this.tessellation = tessellation;
- _this.subdivisions = subdivisions;
- _this.side = side;
- return _this;
- }
- CylinderGeometry.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 });
- };
- CylinderGeometry.prototype.copy = function (id) {
- return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
- };
- CylinderGeometry.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;
- };
- CylinderGeometry.Parse = function (parsedCylinder, scene) {
- if (scene.getGeometryByID(parsedCylinder.id)) {
- return null; // null since geometry could be something else than a cylinder...
- }
- var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
- if (BABYLON.Tags) {
- BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
- }
- scene.pushGeometry(cylinder, true);
- return cylinder;
- };
- return CylinderGeometry;
- }(_PrimitiveGeometry));
- BABYLON.CylinderGeometry = CylinderGeometry;
- var TorusGeometry = /** @class */ (function (_super) {
- __extends(TorusGeometry, _super);
- function TorusGeometry(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
- if (mesh === void 0) { mesh = null; }
- if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
- var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
- _this.diameter = diameter;
- _this.thickness = thickness;
- _this.tessellation = tessellation;
- _this.side = side;
- return _this;
- }
- TorusGeometry.prototype._regenerateVertexData = function () {
- return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
- };
- TorusGeometry.prototype.copy = function (id) {
- return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
- };
- TorusGeometry.prototype.serialize = function () {
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.diameter = this.diameter;
- serializationObject.thickness = this.thickness;
- serializationObject.tessellation = this.tessellation;
- return serializationObject;
- };
- TorusGeometry.Parse = function (parsedTorus, scene) {
- if (scene.getGeometryByID(parsedTorus.id)) {
- return null; // null since geometry could be something else than a torus...
- }
- var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
- if (BABYLON.Tags) {
- BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
- }
- scene.pushGeometry(torus, true);
- return torus;
- };
- return TorusGeometry;
- }(_PrimitiveGeometry));
- BABYLON.TorusGeometry = TorusGeometry;
- var GroundGeometry = /** @class */ (function (_super) {
- __extends(GroundGeometry, _super);
- function GroundGeometry(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
- if (mesh === void 0) { mesh = null; }
- var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
- _this.width = width;
- _this.height = height;
- _this.subdivisions = subdivisions;
- return _this;
- }
- GroundGeometry.prototype._regenerateVertexData = function () {
- return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
- };
- GroundGeometry.prototype.copy = function (id) {
- return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
- };
- GroundGeometry.prototype.serialize = function () {
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.width = this.width;
- serializationObject.height = this.height;
- serializationObject.subdivisions = this.subdivisions;
- return serializationObject;
- };
- GroundGeometry.Parse = function (parsedGround, scene) {
- if (scene.getGeometryByID(parsedGround.id)) {
- return null; // null since geometry could be something else than a ground...
- }
- var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
- if (BABYLON.Tags) {
- BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
- }
- scene.pushGeometry(ground, true);
- return ground;
- };
- return GroundGeometry;
- }(_PrimitiveGeometry));
- BABYLON.GroundGeometry = GroundGeometry;
- var TiledGroundGeometry = /** @class */ (function (_super) {
- __extends(TiledGroundGeometry, _super);
- function TiledGroundGeometry(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
- if (mesh === void 0) { mesh = null; }
- var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
- _this.xmin = xmin;
- _this.zmin = zmin;
- _this.xmax = xmax;
- _this.zmax = zmax;
- _this.subdivisions = subdivisions;
- _this.precision = precision;
- return _this;
- }
- TiledGroundGeometry.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 });
- };
- TiledGroundGeometry.prototype.copy = function (id) {
- return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
- };
- return TiledGroundGeometry;
- }(_PrimitiveGeometry));
- BABYLON.TiledGroundGeometry = TiledGroundGeometry;
- var PlaneGeometry = /** @class */ (function (_super) {
- __extends(PlaneGeometry, _super);
- function PlaneGeometry(id, scene, size, canBeRegenerated, mesh, side) {
- if (mesh === void 0) { mesh = null; }
- if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
- var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
- _this.size = size;
- _this.side = side;
- return _this;
- }
- PlaneGeometry.prototype._regenerateVertexData = function () {
- return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
- };
- PlaneGeometry.prototype.copy = function (id) {
- return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
- };
- PlaneGeometry.prototype.serialize = function () {
- var serializationObject = _super.prototype.serialize.call(this);
- serializationObject.size = this.size;
- return serializationObject;
- };
- PlaneGeometry.Parse = function (parsedPlane, scene) {
- if (scene.getGeometryByID(parsedPlane.id)) {
- return null; // null since geometry could be something else than a ground...
- }
- var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
- if (BABYLON.Tags) {
- BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
- }
- scene.pushGeometry(plane, true);
- return plane;
- };
- return PlaneGeometry;
- }(_PrimitiveGeometry));
- BABYLON.PlaneGeometry = PlaneGeometry;
- var TorusKnotGeometry = /** @class */ (function (_super) {
- __extends(TorusKnotGeometry, _super);
- function TorusKnotGeometry(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
- if (mesh === void 0) { mesh = null; }
- if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
- var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
- _this.radius = radius;
- _this.tube = tube;
- _this.radialSegments = radialSegments;
- _this.tubularSegments = tubularSegments;
- _this.p = p;
- _this.q = q;
- _this.side = side;
- return _this;
- }
- TorusKnotGeometry.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 });
- };
- TorusKnotGeometry.prototype.copy = function (id) {
- return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
- };
- TorusKnotGeometry.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;
- };
- ;
- TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
- if (scene.getGeometryByID(parsedTorusKnot.id)) {
- return null; // null since geometry could be something else than a ground...
- }
- var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
- if (BABYLON.Tags) {
- BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
- }
- scene.pushGeometry(torusKnot, true);
- return torusKnot;
- };
- return TorusKnotGeometry;
- }(_PrimitiveGeometry));
- BABYLON.TorusKnotGeometry = TorusKnotGeometry;
- //}
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.geometry.js.map
- var BABYLON;
- (function (BABYLON) {
- var PostProcessManager = /** @class */ (function () {
- function PostProcessManager(scene) {
- this._vertexBuffers = {};
- this._scene = scene;
- }
- PostProcessManager.prototype._prepareBuffers = function () {
- if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
- return;
- }
- // VBO
- var vertices = [];
- vertices.push(1, 1);
- vertices.push(-1, 1);
- vertices.push(-1, -1);
- vertices.push(1, -1);
- this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
- this._buildIndexBuffer();
- };
- PostProcessManager.prototype._buildIndexBuffer = function () {
- // 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);
- };
- PostProcessManager.prototype._rebuild = function () {
- var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
- if (!vb) {
- return;
- }
- vb._rebuild();
- this._buildIndexBuffer();
- };
- // Methods
- PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
- if (sourceTexture === void 0) { sourceTexture = null; }
- if (postProcesses === void 0) { postProcesses = null; }
- var camera = this._scene.activeCamera;
- if (!camera) {
- return false;
- }
- var postProcesses = postProcesses || camera._postProcesses;
- if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
- return false;
- }
- postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
- return true;
- };
- PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
- if (targetTexture === void 0) { targetTexture = null; }
- if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
- 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, 0, undefined, undefined, forceFullscreenViewport);
- }
- else {
- engine.restoreDefaultFramebuffer();
- }
- }
- var pp = postProcesses[index];
- var effect = pp.apply();
- if (effect) {
- pp.onBeforeRenderObservable.notifyObservers(effect);
- // VBOs
- this._prepareBuffers();
- engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
- // Draw order
- engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
- pp.onAfterRenderObservable.notifyObservers(effect);
- }
- }
- // Restore depth buffer
- engine.setDepthBuffer(true);
- engine.setDepthWrite(true);
- };
- PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
- if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
- var camera = this._scene.activeCamera;
- if (!camera) {
- return;
- }
- postProcesses = postProcesses || camera._postProcesses;
- if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
- return;
- }
- var engine = this._scene.getEngine();
- for (var index = 0, len = postProcesses.length; index < len; index++) {
- if (index < len - 1) {
- postProcesses[index + 1].activate(camera, targetTexture);
- }
- else {
- if (targetTexture) {
- engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
- }
- else {
- engine.restoreDefaultFramebuffer();
- }
- }
- if (doNotPresent) {
- break;
- }
- var pp = postProcesses[index];
- var effect = pp.apply();
- if (effect) {
- pp.onBeforeRenderObservable.notifyObservers(effect);
- // VBOs
- this._prepareBuffers();
- engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
- // Draw order
- engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
- pp.onAfterRenderObservable.notifyObservers(effect);
- }
- }
- // Restore states
- engine.setDepthBuffer(true);
- engine.setDepthWrite(true);
- engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
- };
- PostProcessManager.prototype.dispose = function () {
- var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
- if (buffer) {
- buffer.dispose();
- this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
- }
- if (this._indexBuffer) {
- this._scene.getEngine()._releaseBuffer(this._indexBuffer);
- this._indexBuffer = null;
- }
- };
- return PostProcessManager;
- }());
- BABYLON.PostProcessManager = PostProcessManager;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.postProcessManager.js.map
- BABYLON.Effect.IncludesShadersStore['depthPrePass'] = "#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif";
- 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";
- BABYLON.Effect.IncludesShadersStore['instancesDeclaration'] = "#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif";
- BABYLON.Effect.IncludesShadersStore['pointCloudVertexDeclaration'] = "#ifdef POINTSIZE\nuniform float pointSize;\n#endif";
- BABYLON.Effect.IncludesShadersStore['bumpVertexDeclaration'] = "#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n";
- BABYLON.Effect.IncludesShadersStore['clipPlaneVertexDeclaration'] = "#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif";
- BABYLON.Effect.IncludesShadersStore['fogVertexDeclaration'] = "#ifdef FOG\nvarying vec3 vFogDistance;\n#endif";
- BABYLON.Effect.IncludesShadersStore['morphTargetsVertexGlobalDeclaration'] = "#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif";
- BABYLON.Effect.IncludesShadersStore['morphTargetsVertexDeclaration'] = "#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif";
- BABYLON.Effect.IncludesShadersStore['logDepthDeclaration'] = "#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif";
- BABYLON.Effect.IncludesShadersStore['morphTargetsVertex'] = "#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif";
- BABYLON.Effect.IncludesShadersStore['instancesVertex'] = "#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif";
- BABYLON.Effect.IncludesShadersStore['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";
- BABYLON.Effect.IncludesShadersStore['bumpVertex'] = "#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif";
- BABYLON.Effect.IncludesShadersStore['clipPlaneVertex'] = "#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif";
- BABYLON.Effect.IncludesShadersStore['fogVertex'] = "#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif";
- BABYLON.Effect.IncludesShadersStore['shadowsVertex'] = "#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif";
- BABYLON.Effect.IncludesShadersStore['pointCloudVertex'] = "#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif";
- BABYLON.Effect.IncludesShadersStore['logDepthVertex'] = "#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif";
- BABYLON.Effect.IncludesShadersStore['helperFunctions'] = "const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 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}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor+=mix(-0.5/255.0,0.5/255.0,rand);\ncolor=max(color,0.0);\nreturn color;\n}";
- BABYLON.Effect.IncludesShadersStore['lightFragmentDeclaration'] = "#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{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";
- BABYLON.Effect.IncludesShadersStore['lightsFragmentFunctions'] = "\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\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));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\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,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\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}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=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;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\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";
- BABYLON.Effect.IncludesShadersStore['lightUboDeclaration'] = "#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif";
- BABYLON.Effect.IncludesShadersStore['defaultVertexDeclaration'] = "\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n";
- BABYLON.Effect.IncludesShadersStore['defaultFragmentDeclaration'] = "uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\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_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif";
- BABYLON.Effect.IncludesShadersStore['defaultUboDeclaration'] = "layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};";
- BABYLON.Effect.IncludesShadersStore['shadowsFragmentFunctions'] = "#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\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\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\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\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n";
- BABYLON.Effect.IncludesShadersStore['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";
- BABYLON.Effect.IncludesShadersStore['reflectionFunction'] = "vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_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;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\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.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\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}";
- BABYLON.Effect.IncludesShadersStore['imageProcessingDeclaration'] = "#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif";
- BABYLON.Effect.IncludesShadersStore['imageProcessingFunctions'] = "#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}";
- BABYLON.Effect.IncludesShadersStore['bumpFragmentFunctions'] = "#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\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 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\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";
- BABYLON.Effect.IncludesShadersStore['clipPlaneFragmentDeclaration'] = "#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif";
- BABYLON.Effect.IncludesShadersStore['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 vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif";
- BABYLON.Effect.IncludesShadersStore['clipPlaneFragment'] = "#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif";
- BABYLON.Effect.IncludesShadersStore['bumpFragment'] = "vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif";
- BABYLON.Effect.IncludesShadersStore['lightFragment'] = "#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif";
- BABYLON.Effect.IncludesShadersStore['logDepthFragment'] = "#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif";
- BABYLON.Effect.IncludesShadersStore['fogFragment'] = "#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif";
- var BABYLON;
- (function (BABYLON) {
- /**
- * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
- */
- var PerformanceMonitor = /** @class */ (function () {
- /**
- * constructor
- * @param frameSampleSize The number of samples required to saturate the sliding window
- */
- function PerformanceMonitor(frameSampleSize) {
- if (frameSampleSize === void 0) { frameSampleSize = 30; }
- this._enabled = true;
- this._rollingFrameTime = new RollingAverage(frameSampleSize);
- }
- /**
- * Samples current frame
- * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
- */
- PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
- if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
- if (!this._enabled)
- return;
- if (this._lastFrameTimeMs != null) {
- var dt = timeMs - this._lastFrameTimeMs;
- this._rollingFrameTime.add(dt);
- }
- this._lastFrameTimeMs = timeMs;
- };
- Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
- /**
- * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
- * @return Average frame time in milliseconds
- */
- get: function () {
- return this._rollingFrameTime.average;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
- /**
- * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
- * @return Frame time variance in milliseconds squared
- */
- get: function () {
- return this._rollingFrameTime.variance;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
- /**
- * Returns the frame time of the most recent frame
- * @return Frame time in milliseconds
- */
- get: function () {
- return this._rollingFrameTime.history(0);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
- /**
- * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
- * @return Framerate in frames per second
- */
- get: function () {
- return 1000.0 / this._rollingFrameTime.average;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
- /**
- * Returns the average framerate in frames per second using the most recent frame time
- * @return Framerate in frames per second
- */
- get: function () {
- var history = this._rollingFrameTime.history(0);
- if (history === 0) {
- return 0;
- }
- return 1000.0 / history;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
- /**
- * Returns true if enough samples have been taken to completely fill the sliding window
- * @return true if saturated
- */
- get: function () {
- return this._rollingFrameTime.isSaturated();
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Enables contributions to the sliding window sample set
- */
- PerformanceMonitor.prototype.enable = function () {
- this._enabled = true;
- };
- /**
- * Disables contributions to the sliding window sample set
- * Samples will not be interpolated over the disabled period
- */
- PerformanceMonitor.prototype.disable = function () {
- this._enabled = false;
- //clear last sample to avoid interpolating over the disabled period when next enabled
- this._lastFrameTimeMs = null;
- };
- Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
- /**
- * Returns true if sampling is enabled
- * @return true if enabled
- */
- get: function () {
- return this._enabled;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Resets performance monitor
- */
- PerformanceMonitor.prototype.reset = function () {
- //clear last sample to avoid interpolating over the disabled period when next enabled
- this._lastFrameTimeMs = null;
- //wipe record
- this._rollingFrameTime.reset();
- };
- return PerformanceMonitor;
- }());
- BABYLON.PerformanceMonitor = PerformanceMonitor;
- /**
- * RollingAverage
- *
- * Utility to efficiently compute the rolling average and variance over a sliding window of samples
- */
- var RollingAverage = /** @class */ (function () {
- /**
- * constructor
- * @param length The number of samples required to saturate the sliding window
- */
- function RollingAverage(length) {
- this._samples = new Array(length);
- this.reset();
- }
- /**
- * Adds a sample to the sample set
- * @param v The sample value
- */
- RollingAverage.prototype.add = function (v) {
- //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
- var delta;
- //we need to check if we've already wrapped round
- if (this.isSaturated()) {
- //remove bottom of stack from mean
- var bottomValue = this._samples[this._pos];
- delta = bottomValue - this.average;
- this.average -= delta / (this._sampleCount - 1);
- this._m2 -= delta * (bottomValue - this.average);
- }
- else {
- this._sampleCount++;
- }
- //add new value to mean
- delta = v - this.average;
- this.average += delta / (this._sampleCount);
- this._m2 += delta * (v - this.average);
- //set the new variance
- this.variance = this._m2 / (this._sampleCount - 1);
- this._samples[this._pos] = v;
- this._pos++;
- this._pos %= this._samples.length; //positive wrap around
- };
- /**
- * Returns previously added values or null if outside of history or outside the sliding window domain
- * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
- * @return Value previously recorded with add() or null if outside of range
- */
- RollingAverage.prototype.history = function (i) {
- if ((i >= this._sampleCount) || (i >= this._samples.length)) {
- return 0;
- }
- var i0 = this._wrapPosition(this._pos - 1.0);
- return this._samples[this._wrapPosition(i0 - i)];
- };
- /**
- * Returns true if enough samples have been taken to completely fill the sliding window
- * @return true if sample-set saturated
- */
- RollingAverage.prototype.isSaturated = function () {
- return this._sampleCount >= this._samples.length;
- };
- /**
- * Resets the rolling average (equivalent to 0 samples taken so far)
- */
- RollingAverage.prototype.reset = function () {
- this.average = 0;
- this.variance = 0;
- this._sampleCount = 0;
- this._pos = 0;
- this._m2 = 0;
- };
- /**
- * Wraps a value around the sample range boundaries
- * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
- * @return Wrapped position in sample range
- */
- RollingAverage.prototype._wrapPosition = function (i) {
- var max = this._samples.length;
- return ((i % max) + max) % max;
- };
- return RollingAverage;
- }());
- BABYLON.RollingAverage = RollingAverage;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.performanceMonitor.js.map
- var BABYLON;
- (function (BABYLON) {
- /**
- * This groups together the common properties used for image processing either in direct forward pass
- * or through post processing effect depending on the use of the image processing pipeline in your scene
- * or not.
- */
- var ImageProcessingConfiguration = /** @class */ (function () {
- function ImageProcessingConfiguration() {
- /**
- * Color curves setup used in the effect if colorCurvesEnabled is set to true
- */
- this.colorCurves = new BABYLON.ColorCurves();
- this._colorCurvesEnabled = false;
- this._colorGradingEnabled = false;
- this._colorGradingWithGreenDepth = true;
- this._colorGradingBGR = true;
- this._exposure = 1.0;
- this._toneMappingEnabled = false;
- this._contrast = 1.0;
- /**
- * Vignette stretch size.
- */
- this.vignetteStretch = 0;
- /**
- * Vignette centre X Offset.
- */
- this.vignetteCentreX = 0;
- /**
- * Vignette centre Y Offset.
- */
- this.vignetteCentreY = 0;
- /**
- * Vignette weight or intensity of the vignette effect.
- */
- this.vignetteWeight = 1.5;
- /**
- * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
- * if vignetteEnabled is set to true.
- */
- this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
- /**
- * Camera field of view used by the Vignette effect.
- */
- this.vignetteCameraFov = 0.5;
- this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
- this._vignetteEnabled = false;
- this._applyByPostProcess = false;
- this._isEnabled = true;
- /**
- * An event triggered when the configuration changes and requires Shader to Update some parameters.
- * @type {BABYLON.Observable}
- */
- this.onUpdateParameters = new BABYLON.Observable();
- }
- Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
- /**
- * Gets wether the color curves effect is enabled.
- */
- get: function () {
- return this._colorCurvesEnabled;
- },
- /**
- * Sets wether the color curves effect is enabled.
- */
- set: function (value) {
- if (this._colorCurvesEnabled === value) {
- return;
- }
- this._colorCurvesEnabled = value;
- this._updateParameters();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
- /**
- * Gets wether the color grading effect is enabled.
- */
- get: function () {
- return this._colorGradingEnabled;
- },
- /**
- * Sets wether the color grading effect is enabled.
- */
- set: function (value) {
- if (this._colorGradingEnabled === value) {
- return;
- }
- this._colorGradingEnabled = value;
- this._updateParameters();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
- /**
- * Gets wether the color grading effect is using a green depth for the 3d Texture.
- */
- get: function () {
- return this._colorGradingWithGreenDepth;
- },
- /**
- * Sets wether the color grading effect is using a green depth for the 3d Texture.
- */
- set: function (value) {
- if (this._colorGradingWithGreenDepth === value) {
- return;
- }
- this._colorGradingWithGreenDepth = value;
- this._updateParameters();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
- /**
- * Gets wether the color grading texture contains BGR values.
- */
- get: function () {
- return this._colorGradingBGR;
- },
- /**
- * Sets wether the color grading texture contains BGR values.
- */
- set: function (value) {
- if (this._colorGradingBGR === value) {
- return;
- }
- this._colorGradingBGR = value;
- this._updateParameters();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
- /**
- * Gets the Exposure used in the effect.
- */
- get: function () {
- return this._exposure;
- },
- /**
- * Sets the Exposure used in the effect.
- */
- set: function (value) {
- if (this._exposure === value) {
- return;
- }
- this._exposure = value;
- this._updateParameters();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
- /**
- * Gets wether the tone mapping effect is enabled.
- */
- get: function () {
- return this._toneMappingEnabled;
- },
- /**
- * Sets wether the tone mapping effect is enabled.
- */
- set: function (value) {
- if (this._toneMappingEnabled === value) {
- return;
- }
- this._toneMappingEnabled = value;
- this._updateParameters();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
- /**
- * Gets the contrast used in the effect.
- */
- get: function () {
- return this._contrast;
- },
- /**
- * Sets the contrast used in the effect.
- */
- set: function (value) {
- if (this._contrast === value) {
- return;
- }
- this._contrast = value;
- this._updateParameters();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
- /**
- * Gets the vignette blend mode allowing different kind of effect.
- */
- get: function () {
- return this._vignetteBlendMode;
- },
- /**
- * Sets the vignette blend mode allowing different kind of effect.
- */
- set: function (value) {
- if (this._vignetteBlendMode === value) {
- return;
- }
- this._vignetteBlendMode = value;
- this._updateParameters();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
- /**
- * Gets wether the vignette effect is enabled.
- */
- get: function () {
- return this._vignetteEnabled;
- },
- /**
- * Sets wether the vignette effect is enabled.
- */
- set: function (value) {
- if (this._vignetteEnabled === value) {
- return;
- }
- this._vignetteEnabled = value;
- this._updateParameters();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
- /**
- * Gets wether the image processing is applied through a post process or not.
- */
- get: function () {
- return this._applyByPostProcess;
- },
- /**
- * Sets wether the image processing is applied through a post process or not.
- */
- set: function (value) {
- if (this._applyByPostProcess === value) {
- return;
- }
- this._applyByPostProcess = value;
- this._updateParameters();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
- /**
- * Gets wether the image processing is enabled or not.
- */
- get: function () {
- return this._isEnabled;
- },
- /**
- * Sets wether the image processing is enabled or not.
- */
- set: function (value) {
- if (this._isEnabled === value) {
- return;
- }
- this._isEnabled = value;
- this._updateParameters();
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Method called each time the image processing information changes requires to recompile the effect.
- */
- ImageProcessingConfiguration.prototype._updateParameters = function () {
- this.onUpdateParameters.notifyObservers(this);
- };
- ImageProcessingConfiguration.prototype.getClassName = function () {
- return "ImageProcessingConfiguration";
- };
- /**
- * Prepare the list of uniforms associated with the Image Processing effects.
- * @param uniformsList The list of uniforms used in the effect
- * @param defines the list of defines currently in use
- */
- ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
- if (defines.EXPOSURE) {
- uniforms.push("exposureLinear");
- }
- if (defines.CONTRAST) {
- uniforms.push("contrast");
- }
- if (defines.COLORGRADING) {
- uniforms.push("colorTransformSettings");
- }
- if (defines.VIGNETTE) {
- uniforms.push("vInverseScreenSize");
- uniforms.push("vignetteSettings1");
- uniforms.push("vignetteSettings2");
- }
- if (defines.COLORCURVES) {
- BABYLON.ColorCurves.PrepareUniforms(uniforms);
- }
- };
- /**
- * Prepare the list of samplers associated with the Image Processing effects.
- * @param uniformsList The list of uniforms used in the effect
- * @param defines the list of defines currently in use
- */
- ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
- if (defines.COLORGRADING) {
- samplersList.push("txColorTransform");
- }
- };
- /**
- * Prepare the list of defines associated to the shader.
- * @param defines the list of defines to complete
- */
- ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
- if (forPostProcess === void 0) { forPostProcess = false; }
- if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
- defines.VIGNETTE = false;
- defines.TONEMAPPING = false;
- defines.CONTRAST = false;
- defines.EXPOSURE = false;
- defines.COLORCURVES = false;
- defines.COLORGRADING = false;
- defines.COLORGRADING3D = false;
- defines.IMAGEPROCESSING = false;
- defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
- return;
- }
- defines.VIGNETTE = this.vignetteEnabled;
- defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
- defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
- defines.TONEMAPPING = this.toneMappingEnabled;
- defines.CONTRAST = (this.contrast !== 1.0);
- defines.EXPOSURE = (this.exposure !== 1.0);
- defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
- defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
- if (defines.COLORGRADING) {
- defines.COLORGRADING3D = this.colorGradingTexture.is3D;
- }
- else {
- defines.COLORGRADING3D = false;
- }
- defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
- defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
- defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
- defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
- };
- /**
- * Returns true if all the image processing information are ready.
- */
- ImageProcessingConfiguration.prototype.isReady = function () {
- // Color Grading texure can not be none blocking.
- return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
- };
- /**
- * Binds the image processing to the shader.
- * @param effect The effect to bind to
- */
- ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
- if (aspectRatio === void 0) { aspectRatio = 1; }
- // Color Curves
- if (this._colorCurvesEnabled && this.colorCurves) {
- BABYLON.ColorCurves.Bind(this.colorCurves, effect);
- }
- // Vignette
- if (this._vignetteEnabled) {
- var inverseWidth = 1 / effect.getEngine().getRenderWidth();
- var inverseHeight = 1 / effect.getEngine().getRenderHeight();
- effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
- var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
- var vignetteScaleX = vignetteScaleY * aspectRatio;
- var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
- vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
- vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
- effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
- var vignettePower = -2.0 * this.vignetteWeight;
- effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
- }
- // Exposure
- effect.setFloat("exposureLinear", this.exposure);
- // Contrast
- effect.setFloat("contrast", this.contrast);
- // Color transform settings
- if (this.colorGradingTexture) {
- effect.setTexture("txColorTransform", this.colorGradingTexture);
- var textureSize = this.colorGradingTexture.getSize().height;
- effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
- 0.5 / textureSize, // textureOffset
- textureSize, // textureSize
- this.colorGradingTexture.level // weight
- );
- }
- };
- /**
- * Clones the current image processing instance.
- * @return The cloned image processing
- */
- ImageProcessingConfiguration.prototype.clone = function () {
- return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
- };
- /**
- * Serializes the current image processing instance to a json representation.
- * @return a JSON representation
- */
- ImageProcessingConfiguration.prototype.serialize = function () {
- return BABYLON.SerializationHelper.Serialize(this);
- };
- /**
- * Parses the image processing from a json representation.
- * @param source the JSON source to parse
- * @return The parsed image processing
- */
- ImageProcessingConfiguration.Parse = function (source) {
- return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
- };
- Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
- /**
- * Used to apply the vignette as a mix with the pixel color.
- */
- get: function () {
- return this._VIGNETTEMODE_MULTIPLY;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
- /**
- * Used to apply the vignette as a replacement of the pixel color.
- */
- get: function () {
- return this._VIGNETTEMODE_OPAQUE;
- },
- enumerable: true,
- configurable: true
- });
- // Static constants associated to the image processing.
- ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
- ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
- __decorate([
- BABYLON.serializeAsColorCurves()
- ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
- __decorate([
- BABYLON.serialize()
- ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
- __decorate([
- BABYLON.serializeAsTexture()
- ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
- __decorate([
- BABYLON.serialize()
- ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
- __decorate([
- BABYLON.serialize()
- ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
- __decorate([
- BABYLON.serialize()
- ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
- __decorate([
- BABYLON.serialize()
- ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
- __decorate([
- BABYLON.serialize()
- ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
- __decorate([
- BABYLON.serialize()
- ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
- __decorate([
- BABYLON.serialize()
- ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
- __decorate([
- BABYLON.serialize()
- ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
- __decorate([
- BABYLON.serialize()
- ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
- __decorate([
- BABYLON.serialize()
- ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
- __decorate([
- BABYLON.serializeAsColor4()
- ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
- __decorate([
- BABYLON.serialize()
- ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
- __decorate([
- BABYLON.serialize()
- ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
- __decorate([
- BABYLON.serialize()
- ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
- __decorate([
- BABYLON.serialize()
- ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
- __decorate([
- BABYLON.serialize()
- ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
- return ImageProcessingConfiguration;
- }());
- BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
- var BABYLON;
- (function (BABYLON) {
- /**
- * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
- * It can help converting any input color in a desired output one. This can then be used to create effects
- * from sepia, black and white to sixties or futuristic rendering...
- *
- * The only supported format is currently 3dl.
- * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
- */
- var ColorGradingTexture = /** @class */ (function (_super) {
- __extends(ColorGradingTexture, _super);
- /**
- * Instantiates a ColorGradingTexture from the following parameters.
- *
- * @param url The location of the color gradind data (currently only supporting 3dl)
- * @param scene The scene the texture will be used in
- */
- function ColorGradingTexture(url, scene) {
- var _this = _super.call(this, scene) || this;
- if (!url) {
- return _this;
- }
- _this._engine = scene.getEngine();
- _this._textureMatrix = BABYLON.Matrix.Identity();
- _this.name = url;
- _this.url = url;
- _this.hasAlpha = false;
- _this.isCube = false;
- _this.is3D = _this._engine.webGLVersion > 1;
- _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
- _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
- _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
- _this.anisotropicFilteringLevel = 1;
- _this._texture = _this._getFromCache(url, true);
- if (!_this._texture) {
- if (!scene.useDelayedTextureLoading) {
- _this.loadTexture();
- }
- else {
- _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
- }
- }
- return _this;
- }
- /**
- * Returns the texture matrix used in most of the material.
- * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
- */
- ColorGradingTexture.prototype.getTextureMatrix = function () {
- return this._textureMatrix;
- };
- /**
- * Occurs when the file being loaded is a .3dl LUT file.
- */
- ColorGradingTexture.prototype.load3dlTexture = function () {
- var engine = this._engine;
- var texture;
- if (engine.webGLVersion === 1) {
- texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
- }
- else {
- texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
- }
- this._texture = texture;
- var callback = function (text) {
- if (typeof text !== "string") {
- return;
- }
- var data = null;
- var tempData = null;
- var line;
- var lines = text.split('\n');
- var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
- var maxColor = 0;
- for (var i = 0; i < lines.length; i++) {
- line = lines[i];
- if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
- continue;
- if (line.indexOf('#') === 0)
- continue;
- var words = line.split(" ");
- if (size === 0) {
- // Number of space + one
- size = words.length;
- data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
- tempData = new Float32Array(size * size * size * 4);
- continue;
- }
- if (size != 0) {
- var r = Math.max(parseInt(words[0]), 0);
- var g = Math.max(parseInt(words[1]), 0);
- var b = Math.max(parseInt(words[2]), 0);
- maxColor = Math.max(r, maxColor);
- maxColor = Math.max(g, maxColor);
- maxColor = Math.max(b, maxColor);
- var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
- if (tempData) {
- tempData[pixelStorageIndex + 0] = r;
- tempData[pixelStorageIndex + 1] = g;
- tempData[pixelStorageIndex + 2] = b;
- }
- pixelIndexSlice++;
- if (pixelIndexSlice % size == 0) {
- pixelIndexH++;
- pixelIndexSlice = 0;
- if (pixelIndexH % size == 0) {
- pixelIndexW++;
- pixelIndexH = 0;
- }
- }
- }
- }
- if (tempData && data) {
- for (var i = 0; i < tempData.length; i++) {
- if (i > 0 && (i + 1) % 4 === 0) {
- data[i] = 255;
- }
- else {
- var value = tempData[i];
- data[i] = (value / maxColor * 255);
- }
- }
- }
- if (texture.is3D) {
- texture.updateSize(size, size, size);
- engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
- }
- else {
- texture.updateSize(size * size, size);
- engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
- }
- };
- var scene = this.getScene();
- if (scene) {
- scene._loadFile(this.url, callback);
- }
- else {
- this._engine._loadFile(this.url, callback);
- }
- return this._texture;
- };
- /**
- * Starts the loading process of the texture.
- */
- ColorGradingTexture.prototype.loadTexture = function () {
- if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
- this.load3dlTexture();
- }
- };
- /**
- * Clones the color gradind texture.
- */
- ColorGradingTexture.prototype.clone = function () {
- var newTexture = new ColorGradingTexture(this.url, this.getScene());
- // Base texture
- newTexture.level = this.level;
- return newTexture;
- };
- /**
- * Called during delayed load for textures.
- */
- ColorGradingTexture.prototype.delayLoad = function () {
- if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
- return;
- }
- this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
- this._texture = this._getFromCache(this.url, true);
- if (!this._texture) {
- this.loadTexture();
- }
- };
- /**
- * Parses a color grading texture serialized by Babylon.
- * @param parsedTexture The texture information being parsedTexture
- * @param scene The scene to load the texture in
- * @param rootUrl The root url of the data assets to load
- * @return A color gradind texture
- */
- ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
- var texture = null;
- if (parsedTexture.name && !parsedTexture.isRenderTarget) {
- texture = new ColorGradingTexture(parsedTexture.name, scene);
- texture.name = parsedTexture.name;
- texture.level = parsedTexture.level;
- }
- return texture;
- };
- /**
- * Serializes the LUT texture to json format.
- */
- ColorGradingTexture.prototype.serialize = function () {
- if (!this.name) {
- return null;
- }
- var serializationObject = {};
- serializationObject.name = this.name;
- serializationObject.level = this.level;
- serializationObject.customType = "BABYLON.ColorGradingTexture";
- return serializationObject;
- };
- /**
- * Empty line regex stored for GC.
- */
- ColorGradingTexture._noneEmptyLineRegex = /\S+/;
- return ColorGradingTexture;
- }(BABYLON.BaseTexture));
- BABYLON.ColorGradingTexture = ColorGradingTexture;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.colorGradingTexture.js.map
- var BABYLON;
- (function (BABYLON) {
- /**
- * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
- * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
- * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
- * corresponding to low luminance, medium luminance, and high luminance areas respectively.
- */
- var ColorCurves = /** @class */ (function () {
- function ColorCurves() {
- this._dirty = true;
- this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
- this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
- this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
- this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
- this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
- this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
- this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
- this._globalHue = 30;
- this._globalDensity = 0;
- this._globalSaturation = 0;
- this._globalExposure = 0;
- this._highlightsHue = 30;
- this._highlightsDensity = 0;
- this._highlightsSaturation = 0;
- this._highlightsExposure = 0;
- this._midtonesHue = 30;
- this._midtonesDensity = 0;
- this._midtonesSaturation = 0;
- this._midtonesExposure = 0;
- this._shadowsHue = 30;
- this._shadowsDensity = 0;
- this._shadowsSaturation = 0;
- this._shadowsExposure = 0;
- }
- Object.defineProperty(ColorCurves.prototype, "globalHue", {
- /**
- * Gets the global Hue value.
- * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
- */
- get: function () {
- return this._globalHue;
- },
- /**
- * Sets the global Hue value.
- * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
- */
- set: function (value) {
- this._globalHue = value;
- this._dirty = true;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ColorCurves.prototype, "globalDensity", {
- /**
- * Gets the global Density value.
- * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
- * Values less than zero provide a filter of opposite hue.
- */
- get: function () {
- return this._globalDensity;
- },
- /**
- * Sets the global Density value.
- * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
- * Values less than zero provide a filter of opposite hue.
- */
- set: function (value) {
- this._globalDensity = value;
- this._dirty = true;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
- /**
- * Gets the global Saturation value.
- * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
- */
- get: function () {
- return this._globalSaturation;
- },
- /**
- * Sets the global Saturation value.
- * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
- */
- set: function (value) {
- this._globalSaturation = value;
- this._dirty = true;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
- /**
- * Gets the highlights Hue value.
- * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
- */
- get: function () {
- return this._highlightsHue;
- },
- /**
- * Sets the highlights Hue value.
- * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
- */
- set: function (value) {
- this._highlightsHue = value;
- this._dirty = true;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
- /**
- * Gets the highlights Density value.
- * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
- * Values less than zero provide a filter of opposite hue.
- */
- get: function () {
- return this._highlightsDensity;
- },
- /**
- * Sets the highlights Density value.
- * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
- * Values less than zero provide a filter of opposite hue.
- */
- set: function (value) {
- this._highlightsDensity = value;
- this._dirty = true;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
- /**
- * Gets the highlights Saturation value.
- * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
- */
- get: function () {
- return this._highlightsSaturation;
- },
- /**
- * Sets the highlights Saturation value.
- * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
- */
- set: function (value) {
- this._highlightsSaturation = value;
- this._dirty = true;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
- /**
- * Gets the highlights Exposure value.
- * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
- */
- get: function () {
- return this._highlightsExposure;
- },
- /**
- * Sets the highlights Exposure value.
- * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
- */
- set: function (value) {
- this._highlightsExposure = value;
- this._dirty = true;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
- /**
- * Gets the midtones Hue value.
- * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
- */
- get: function () {
- return this._midtonesHue;
- },
- /**
- * Sets the midtones Hue value.
- * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
- */
- set: function (value) {
- this._midtonesHue = value;
- this._dirty = true;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
- /**
- * Gets the midtones Density value.
- * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
- * Values less than zero provide a filter of opposite hue.
- */
- get: function () {
- return this._midtonesDensity;
- },
- /**
- * Sets the midtones Density value.
- * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
- * Values less than zero provide a filter of opposite hue.
- */
- set: function (value) {
- this._midtonesDensity = value;
- this._dirty = true;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
- /**
- * Gets the midtones Saturation value.
- * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
- */
- get: function () {
- return this._midtonesSaturation;
- },
- /**
- * Sets the midtones Saturation value.
- * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
- */
- set: function (value) {
- this._midtonesSaturation = value;
- this._dirty = true;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
- /**
- * Gets the midtones Exposure value.
- * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
- */
- get: function () {
- return this._midtonesExposure;
- },
- /**
- * Sets the midtones Exposure value.
- * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
- */
- set: function (value) {
- this._midtonesExposure = value;
- this._dirty = true;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
- /**
- * Gets the shadows Hue value.
- * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
- */
- get: function () {
- return this._shadowsHue;
- },
- /**
- * Sets the shadows Hue value.
- * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
- */
- set: function (value) {
- this._shadowsHue = value;
- this._dirty = true;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
- /**
- * Gets the shadows Density value.
- * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
- * Values less than zero provide a filter of opposite hue.
- */
- get: function () {
- return this._shadowsDensity;
- },
- /**
- * Sets the shadows Density value.
- * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
- * Values less than zero provide a filter of opposite hue.
- */
- set: function (value) {
- this._shadowsDensity = value;
- this._dirty = true;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
- /**
- * Gets the shadows Saturation value.
- * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
- */
- get: function () {
- return this._shadowsSaturation;
- },
- /**
- * Sets the shadows Saturation value.
- * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
- */
- set: function (value) {
- this._shadowsSaturation = value;
- this._dirty = true;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
- /**
- * Gets the shadows Exposure value.
- * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
- */
- get: function () {
- return this._shadowsExposure;
- },
- /**
- * Sets the shadows Exposure value.
- * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
- */
- set: function (value) {
- this._shadowsExposure = value;
- this._dirty = true;
- },
- enumerable: true,
- configurable: true
- });
- ColorCurves.prototype.getClassName = function () {
- return "ColorCurves";
- };
- /**
- * Binds the color curves to the shader.
- * @param colorCurves The color curve to bind
- * @param effect The effect to bind to
- */
- ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
- if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
- if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
- if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
- if (colorCurves._dirty) {
- colorCurves._dirty = false;
- // Fill in global info.
- colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
- // Compute highlights info.
- colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
- colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
- // Compute midtones info.
- colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
- colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
- // Compute shadows info.
- colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
- colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
- // Compute deltas (neutral is midtones).
- colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
- colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
- }
- if (effect) {
- effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
- effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
- effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
- }
- };
- /**
- * Prepare the list of uniforms associated with the ColorCurves effects.
- * @param uniformsList The list of uniforms used in the effect
- */
- ColorCurves.PrepareUniforms = function (uniformsList) {
- uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
- };
- /**
- * Returns color grading data based on a hue, density, saturation and exposure value.
- * @param filterHue The hue of the color filter.
- * @param filterDensity The density of the color filter.
- * @param saturation The saturation.
- * @param exposure The exposure.
- * @param result The result data container.
- */
- ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
- if (hue == null) {
- return;
- }
- hue = ColorCurves.clamp(hue, 0, 360);
- density = ColorCurves.clamp(density, -100, 100);
- saturation = ColorCurves.clamp(saturation, -100, 100);
- exposure = ColorCurves.clamp(exposure, -100, 100);
- // Remap the slider/config filter density with non-linear mapping and also scale by half
- // so that the maximum filter density is only 50% control. This provides fine control
- // for small values and reasonable range.
- density = ColorCurves.applyColorGradingSliderNonlinear(density);
- density *= 0.5;
- exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
- if (density < 0) {
- density *= -1;
- hue = (hue + 180) % 360;
- }
- ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
- result.scaleToRef(2, result);
- result.a = 1 + 0.01 * saturation;
- };
- /**
- * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
- * @param value The input slider value in range [-100,100].
- * @returns Adjusted value.
- */
- ColorCurves.applyColorGradingSliderNonlinear = function (value) {
- value /= 100;
- var x = Math.abs(value);
- x = Math.pow(x, 2);
- if (value < 0) {
- x *= -1;
- }
- x *= 100;
- return x;
- };
- /**
- * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
- * @param hue The hue (H) input.
- * @param saturation The saturation (S) input.
- * @param brightness The brightness (B) input.
- * @result An RGBA color represented as Vector4.
- */
- ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
- var h = ColorCurves.clamp(hue, 0, 360);
- var s = ColorCurves.clamp(saturation / 100, 0, 1);
- var v = ColorCurves.clamp(brightness / 100, 0, 1);
- if (s === 0) {
- result.r = v;
- result.g = v;
- result.b = v;
- }
- else {
- // sector 0 to 5
- h /= 60;
- var i = Math.floor(h);
- // fractional part of h
- var f = h - i;
- var p = v * (1 - s);
- var q = v * (1 - s * f);
- var t = v * (1 - s * (1 - f));
- switch (i) {
- case 0:
- result.r = v;
- result.g = t;
- result.b = p;
- break;
- case 1:
- result.r = q;
- result.g = v;
- result.b = p;
- break;
- case 2:
- result.r = p;
- result.g = v;
- result.b = t;
- break;
- case 3:
- result.r = p;
- result.g = q;
- result.b = v;
- break;
- case 4:
- result.r = t;
- result.g = p;
- result.b = v;
- break;
- default:// case 5:
- result.r = v;
- result.g = p;
- result.b = q;
- break;
- }
- }
- result.a = 1;
- };
- /**
- * Returns a value clamped between min and max
- * @param value The value to clamp
- * @param min The minimum of value
- * @param max The maximum of value
- * @returns The clamped value.
- */
- ColorCurves.clamp = function (value, min, max) {
- return Math.min(Math.max(value, min), max);
- };
- /**
- * Clones the current color curve instance.
- * @return The cloned curves
- */
- ColorCurves.prototype.clone = function () {
- return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
- };
- /**
- * Serializes the current color curve instance to a json representation.
- * @return a JSON representation
- */
- ColorCurves.prototype.serialize = function () {
- return BABYLON.SerializationHelper.Serialize(this);
- };
- /**
- * Parses the color curve from a json representation.
- * @param source the JSON source to parse
- * @return The parsed curves
- */
- ColorCurves.Parse = function (source) {
- return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
- };
- __decorate([
- BABYLON.serialize()
- ], ColorCurves.prototype, "_globalHue", void 0);
- __decorate([
- BABYLON.serialize()
- ], ColorCurves.prototype, "_globalDensity", void 0);
- __decorate([
- BABYLON.serialize()
- ], ColorCurves.prototype, "_globalSaturation", void 0);
- __decorate([
- BABYLON.serialize()
- ], ColorCurves.prototype, "_globalExposure", void 0);
- __decorate([
- BABYLON.serialize()
- ], ColorCurves.prototype, "_highlightsHue", void 0);
- __decorate([
- BABYLON.serialize()
- ], ColorCurves.prototype, "_highlightsDensity", void 0);
- __decorate([
- BABYLON.serialize()
- ], ColorCurves.prototype, "_highlightsSaturation", void 0);
- __decorate([
- BABYLON.serialize()
- ], ColorCurves.prototype, "_highlightsExposure", void 0);
- __decorate([
- BABYLON.serialize()
- ], ColorCurves.prototype, "_midtonesHue", void 0);
- __decorate([
- BABYLON.serialize()
- ], ColorCurves.prototype, "_midtonesDensity", void 0);
- __decorate([
- BABYLON.serialize()
- ], ColorCurves.prototype, "_midtonesSaturation", void 0);
- __decorate([
- BABYLON.serialize()
- ], ColorCurves.prototype, "_midtonesExposure", void 0);
- return ColorCurves;
- }());
- BABYLON.ColorCurves = ColorCurves;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.colorCurves.js.map
- //# sourceMappingURL=babylon.behavior.js.map
- var BABYLON;
- (function (BABYLON) {
- var MaterialHelper = /** @class */ (function () {
- function MaterialHelper() {
- }
- MaterialHelper.BindEyePosition = function (effect, scene) {
- if (scene._forcedViewPosition) {
- effect.setVector3("vEyePosition", scene._forcedViewPosition);
- return;
- }
- effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
- };
- MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
- defines._needUVs = true;
- defines[key] = true;
- if (texture.getTextureMatrix().isIdentity(true)) {
- defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
- if (texture.coordinatesIndex === 0) {
- defines["MAINUV1"] = true;
- }
- else {
- defines["MAINUV2"] = true;
- }
- }
- else {
- defines[key + "DIRECTUV"] = 0;
- }
- };
- MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
- var matrix = texture.getTextureMatrix();
- if (!matrix.isIdentity(true)) {
- uniformBuffer.updateMatrix(key + "Matrix", matrix);
- }
- };
- MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
- if (defines._areMiscDirty) {
- defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
- defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
- defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
- defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
- }
- };
- MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
- if (forceAlphaTest === void 0) { forceAlphaTest = false; }
- var changed = false;
- if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
- defines["CLIPPLANE"] = !defines["CLIPPLANE"];
- changed = true;
- }
- if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
- defines["ALPHATEST"] = !defines["ALPHATEST"];
- changed = true;
- }
- if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
- defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
- changed = true;
- }
- if (defines["INSTANCES"] !== useInstances) {
- defines["INSTANCES"] = useInstances;
- changed = true;
- }
- if (changed) {
- defines.markAsUnprocessed();
- }
- };
- MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
- if (useMorphTargets === void 0) { useMorphTargets = false; }
- if (useVertexAlpha === void 0) { useVertexAlpha = true; }
- if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
- return false;
- }
- defines._normals = defines._needNormals;
- defines._uvs = defines._needUVs;
- defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
- if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
- defines["TANGENT"] = true;
- }
- if (defines._needUVs) {
- defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
- defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
- }
- else {
- defines["UV1"] = false;
- defines["UV2"] = false;
- }
- if (useVertexColor) {
- var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
- defines["VERTEXCOLOR"] = hasVertexColors;
- defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
- }
- if (useBones) {
- if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
- defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
- defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
- }
- else {
- defines["NUM_BONE_INFLUENCERS"] = 0;
- defines["BonesPerMesh"] = 0;
- }
- }
- if (useMorphTargets) {
- var manager = mesh.morphTargetManager;
- if (manager) {
- defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
- defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
- defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
- defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
- }
- else {
- defines["MORPHTARGETS_TANGENT"] = false;
- defines["MORPHTARGETS_NORMAL"] = false;
- defines["MORPHTARGETS"] = false;
- defines["NUM_MORPH_INFLUENCERS"] = 0;
- }
- }
- return true;
- };
- MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
- if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
- if (disableLighting === void 0) { disableLighting = false; }
- if (!defines._areLightsDirty) {
- return defines._needNormals;
- }
- var lightIndex = 0;
- var needNormals = false;
- var needRebuild = false;
- var lightmapMode = false;
- var shadowEnabled = false;
- var specularEnabled = false;
- if (scene.lightsEnabled && !disableLighting) {
- for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
- var light = _a[_i];
- needNormals = true;
- if (defines["LIGHT" + lightIndex] === undefined) {
- needRebuild = true;
- }
- defines["LIGHT" + lightIndex] = true;
- defines["SPOTLIGHT" + lightIndex] = false;
- defines["HEMILIGHT" + lightIndex] = false;
- defines["POINTLIGHT" + lightIndex] = false;
- defines["DIRLIGHT" + lightIndex] = false;
- var type;
- if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
- type = "SPOTLIGHT" + lightIndex;
- }
- else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
- type = "HEMILIGHT" + lightIndex;
- }
- else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
- type = "POINTLIGHT" + lightIndex;
- }
- else {
- type = "DIRLIGHT" + lightIndex;
- }
- defines[type] = true;
- // Specular
- if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
- specularEnabled = true;
- }
- // Shadows
- defines["SHADOW" + lightIndex] = false;
- defines["SHADOWPCF" + lightIndex] = false;
- defines["SHADOWESM" + lightIndex] = false;
- defines["SHADOWCUBE" + lightIndex] = false;
- if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
- var shadowGenerator = light.getShadowGenerator();
- if (shadowGenerator) {
- shadowEnabled = true;
- shadowGenerator.prepareDefines(defines, lightIndex);
- }
- }
- if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
- lightmapMode = true;
- defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
- defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
- }
- else {
- defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
- defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
- }
- lightIndex++;
- if (lightIndex === maxSimultaneousLights)
- break;
- }
- }
- defines["SPECULARTERM"] = specularEnabled;
- defines["SHADOWS"] = shadowEnabled;
- // Resetting all other lights if any
- for (var index = lightIndex; index < maxSimultaneousLights; index++) {
- if (defines["LIGHT" + index] !== undefined) {
- defines["LIGHT" + index] = false;
- defines["HEMILIGHT" + lightIndex] = false;
- defines["POINTLIGHT" + lightIndex] = false;
- defines["DIRLIGHT" + lightIndex] = false;
- defines["SPOTLIGHT" + lightIndex] = false;
- defines["SHADOW" + lightIndex] = false;
- }
- }
- var caps = scene.getEngine().getCaps();
- if (defines["SHADOWFLOAT"] === undefined) {
- needRebuild = true;
- }
- defines["SHADOWFLOAT"] = shadowEnabled &&
- ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
- (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
- defines["LIGHTMAPEXCLUDED"] = lightmapMode;
- if (needRebuild) {
- defines.rebuild();
- }
- return needNormals;
- };
- MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
- if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
- var uniformsList;
- var uniformBuffersList = null;
- if (uniformsListOrOptions.uniformsNames) {
- var options = uniformsListOrOptions;
- uniformsList = options.uniformsNames;
- uniformBuffersList = options.uniformBuffersNames;
- samplersList = options.samplers;
- defines = options.defines;
- maxSimultaneousLights = options.maxSimultaneousLights;
- }
- else {
- uniformsList = uniformsListOrOptions;
- if (!samplersList) {
- samplersList = [];
- }
- }
- for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
- if (!defines["LIGHT" + lightIndex]) {
- break;
- }
- uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
- if (uniformBuffersList) {
- uniformBuffersList.push("Light" + lightIndex);
- }
- samplersList.push("shadowSampler" + lightIndex);
- }
- if (defines["NUM_MORPH_INFLUENCERS"]) {
- uniformsList.push("morphTargetInfluences");
- }
- };
- MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
- if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
- if (rank === void 0) { rank = 0; }
- var lightFallbackRank = 0;
- for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
- if (!defines["LIGHT" + lightIndex]) {
- break;
- }
- if (lightIndex > 0) {
- lightFallbackRank = rank + lightIndex;
- fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
- }
- if (!defines["SHADOWS"]) {
- if (defines["SHADOW" + lightIndex]) {
- fallbacks.addFallback(rank, "SHADOW" + lightIndex);
- }
- if (defines["SHADOWPCF" + lightIndex]) {
- fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
- }
- if (defines["SHADOWESM" + lightIndex]) {
- fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
- }
- }
- }
- return lightFallbackRank++;
- };
- MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
- var influencers = defines["NUM_MORPH_INFLUENCERS"];
- if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
- var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
- var manager = mesh.morphTargetManager;
- var normal = manager && manager.supportsNormals && defines["NORMAL"];
- var tangent = manager && manager.supportsTangents && defines["TANGENT"];
- for (var index = 0; index < influencers; index++) {
- attribs.push(BABYLON.VertexBuffer.PositionKind + index);
- if (normal) {
- attribs.push(BABYLON.VertexBuffer.NormalKind + index);
- }
- if (tangent) {
- attribs.push(BABYLON.VertexBuffer.TangentKind + index);
- }
- if (attribs.length > maxAttributesCount) {
- BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
- }
- }
- }
- };
- 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) {
- if (light.shadowEnabled && mesh.receiveShadows) {
- var shadowGenerator = light.getShadowGenerator();
- if (shadowGenerator) {
- shadowGenerator.bindShadowLight(lightIndex, effect);
- }
- }
- };
- MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
- light.transferToEffect(effect, lightIndex + "");
- };
- MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
- if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
- if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
- var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
- for (var i = 0; i < len; i++) {
- var light = mesh._lightSources[i];
- var iAsString = i.toString();
- var scaledIntensity = light.getScaledIntensity();
- light._uniformBuffer.bindToEffect(effect, "Light" + i);
- MaterialHelper.BindLightProperties(light, effect, i);
- light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
- light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
- if (defines["SPECULARTERM"]) {
- light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
- light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
- }
- // Shadows
- if (scene.shadowsEnabled) {
- this.BindLightShadow(light, scene, mesh, iAsString, effect);
- }
- light._uniformBuffer.update();
- }
- };
- 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 && mesh.skeleton) {
- var matrices = mesh.skeleton.getTransformMatrices(mesh);
- if (matrices && effect) {
- effect.setMatrices("mBones", matrices);
- }
- }
- };
- MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
- var manager = abstractMesh.morphTargetManager;
- if (!abstractMesh || !manager) {
- return;
- }
- effect.setFloatArray("morphTargetInfluences", manager.influences);
- };
- 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 = {}));
- //# sourceMappingURL=babylon.materialHelper.js.map
- var BABYLON;
- (function (BABYLON) {
- var PushMaterial = /** @class */ (function (_super) {
- __extends(PushMaterial, _super);
- function PushMaterial(name, scene) {
- var _this = _super.call(this, name, scene) || this;
- _this.storeEffectOnSubMeshes = true;
- return _this;
- }
- PushMaterial.prototype.getEffect = function () {
- return this._activeEffect;
- };
- PushMaterial.prototype.isReady = function (mesh, useInstances) {
- if (!mesh) {
- return false;
- }
- if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
- return true;
- }
- return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
- };
- PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
- this._activeEffect.setMatrix("world", world);
- };
- PushMaterial.prototype.bind = function (world, mesh) {
- if (!mesh) {
- return;
- }
- this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
- };
- PushMaterial.prototype._afterBind = function (mesh, effect) {
- if (effect === void 0) { effect = null; }
- _super.prototype._afterBind.call(this, mesh);
- this.getScene()._cachedEffect = effect;
- };
- PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
- if (visibility === void 0) { visibility = 1; }
- return scene.isCachedMaterialInvalid(this, effect, visibility);
- };
- return PushMaterial;
- }(BABYLON.Material));
- BABYLON.PushMaterial = PushMaterial;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.pushMaterial.js.map
- var BABYLON;
- (function (BABYLON) {
- var StandardMaterialDefines = /** @class */ (function (_super) {
- __extends(StandardMaterialDefines, _super);
- function StandardMaterialDefines() {
- var _this = _super.call(this) || this;
- _this.MAINUV1 = false;
- _this.MAINUV2 = false;
- _this.DIFFUSE = false;
- _this.DIFFUSEDIRECTUV = 0;
- _this.AMBIENT = false;
- _this.AMBIENTDIRECTUV = 0;
- _this.OPACITY = false;
- _this.OPACITYDIRECTUV = 0;
- _this.OPACITYRGB = false;
- _this.REFLECTION = false;
- _this.EMISSIVE = false;
- _this.EMISSIVEDIRECTUV = 0;
- _this.SPECULAR = false;
- _this.SPECULARDIRECTUV = 0;
- _this.BUMP = false;
- _this.BUMPDIRECTUV = 0;
- _this.PARALLAX = false;
- _this.PARALLAXOCCLUSION = false;
- _this.SPECULAROVERALPHA = false;
- _this.CLIPPLANE = false;
- _this.ALPHATEST = false;
- _this.DEPTHPREPASS = false;
- _this.ALPHAFROMDIFFUSE = false;
- _this.POINTSIZE = false;
- _this.FOG = false;
- _this.SPECULARTERM = 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.LIGHTMAPDIRECTUV = 0;
- _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.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
- _this.INVERTCUBICMAP = false;
- _this.LOGARITHMICDEPTH = false;
- _this.REFRACTION = false;
- _this.REFRACTIONMAP_3D = false;
- _this.REFLECTIONOVERALPHA = false;
- _this.TWOSIDEDLIGHTING = false;
- _this.SHADOWFLOAT = false;
- _this.MORPHTARGETS = false;
- _this.MORPHTARGETS_NORMAL = false;
- _this.MORPHTARGETS_TANGENT = false;
- _this.NUM_MORPH_INFLUENCERS = 0;
- _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
- _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
- _this.IMAGEPROCESSING = false;
- _this.VIGNETTE = false;
- _this.VIGNETTEBLENDMODEMULTIPLY = false;
- _this.VIGNETTEBLENDMODEOPAQUE = false;
- _this.TONEMAPPING = false;
- _this.CONTRAST = false;
- _this.COLORCURVES = false;
- _this.COLORGRADING = false;
- _this.COLORGRADING3D = false;
- _this.SAMPLER3DGREENDEPTH = false;
- _this.SAMPLER3DBGRMAP = false;
- _this.IMAGEPROCESSINGPOSTPROCESS = false;
- _this.EXPOSURE = false;
- _this.rebuild();
- return _this;
- }
- StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
- var modes = [
- "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
- "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
- "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
- "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
- ];
- for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
- var mode = modes_1[_i];
- this[mode] = (mode === modeToEnable);
- }
- };
- return StandardMaterialDefines;
- }(BABYLON.MaterialDefines));
- BABYLON.StandardMaterialDefines = StandardMaterialDefines;
- var StandardMaterial = /** @class */ (function (_super) {
- __extends(StandardMaterial, _super);
- function StandardMaterial(name, scene) {
- var _this = _super.call(this, name, scene) || this;
- _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._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._useReflectionFresnelFromSpecular = false;
- _this._useGlossinessFromSpecularMapAlpha = false;
- _this._maxSimultaneousLights = 4;
- /**
- * If sets to true, x component of normal map value will invert (x = 1.0 - x).
- */
- _this._invertNormalMapX = false;
- /**
- * If sets to true, y component of normal map value will invert (y = 1.0 - y).
- */
- _this._invertNormalMapY = false;
- /**
- * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
- */
- _this._twoSidedLighting = false;
- _this._renderTargets = new BABYLON.SmartArray(16);
- _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
- _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
- // Setup the default processing configuration to the scene.
- _this._attachImageProcessingConfiguration(null);
- _this.getRenderTargetTextures = function () {
- _this._renderTargets.reset();
- if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
- _this._renderTargets.push(_this._reflectionTexture);
- }
- if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
- _this._renderTargets.push(_this._refractionTexture);
- }
- return _this._renderTargets;
- };
- return _this;
- }
- ;
- ;
- ;
- ;
- ;
- ;
- ;
- ;
- ;
- ;
- ;
- ;
- ;
- ;
- ;
- ;
- ;
- Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
- /**
- * Gets the image processing configuration used either in this material.
- */
- get: function () {
- return this._imageProcessingConfiguration;
- },
- /**
- * Sets the Default image processing configuration used either in the this material.
- *
- * If sets to null, the scene one is in use.
- */
- set: function (value) {
- this._attachImageProcessingConfiguration(value);
- // Ensure the effect will be rebuilt.
- this._markAllSubMeshesAsTexturesDirty();
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Attaches a new image processing configuration to the Standard Material.
- * @param configuration
- */
- StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
- var _this = this;
- if (configuration === this._imageProcessingConfiguration) {
- return;
- }
- // Detaches observer.
- if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
- this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
- }
- // Pick the scene configuration if needed.
- if (!configuration) {
- this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
- }
- else {
- this._imageProcessingConfiguration = configuration;
- }
- // Attaches observer.
- this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
- _this._markAllSubMeshesAsImageProcessingDirty();
- });
- };
- Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
- /**
- * Gets wether the color curves effect is enabled.
- */
- get: function () {
- return this.imageProcessingConfiguration.colorCurvesEnabled;
- },
- /**
- * Sets wether the color curves effect is enabled.
- */
- set: function (value) {
- this.imageProcessingConfiguration.colorCurvesEnabled = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
- /**
- * Gets wether the color grading effect is enabled.
- */
- get: function () {
- return this.imageProcessingConfiguration.colorGradingEnabled;
- },
- /**
- * Gets wether the color grading effect is enabled.
- */
- set: function (value) {
- this.imageProcessingConfiguration.colorGradingEnabled = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
- /**
- * Gets wether tonemapping is enabled or not.
- */
- get: function () {
- return this._imageProcessingConfiguration.toneMappingEnabled;
- },
- /**
- * Sets wether tonemapping is enabled or not
- */
- set: function (value) {
- this._imageProcessingConfiguration.toneMappingEnabled = value;
- },
- enumerable: true,
- configurable: true
- });
- ;
- ;
- Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
- /**
- * 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.
- */
- get: function () {
- return this._imageProcessingConfiguration.exposure;
- },
- /**
- * 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.
- */
- set: function (value) {
- this._imageProcessingConfiguration.exposure = value;
- },
- enumerable: true,
- configurable: true
- });
- ;
- ;
- Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
- /**
- * Gets The camera contrast used on this material.
- */
- get: function () {
- return this._imageProcessingConfiguration.contrast;
- },
- /**
- * Sets The camera contrast used on this material.
- */
- set: function (value) {
- this._imageProcessingConfiguration.contrast = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
- /**
- * Gets the Color Grading 2D Lookup Texture.
- */
- get: function () {
- return this._imageProcessingConfiguration.colorGradingTexture;
- },
- /**
- * Sets the Color Grading 2D Lookup Texture.
- */
- set: function (value) {
- this._imageProcessingConfiguration.colorGradingTexture = value;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
- /**
- * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
- * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
- * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
- * corresponding to low luminance, medium luminance, and high luminance areas respectively.
- */
- get: function () {
- return this._imageProcessingConfiguration.colorCurves;
- },
- /**
- * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
- * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
- * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
- * corresponding to low luminance, medium luminance, and high luminance areas respectively.
- */
- set: function (value) {
- this._imageProcessingConfiguration.colorCurves = value;
- },
- enumerable: true,
- configurable: true
- });
- StandardMaterial.prototype.getClassName = function () {
- return "StandardMaterial";
- };
- Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
- get: function () {
- return this._useLogarithmicDepth;
- },
- set: function (value) {
- this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
- this._markAllSubMeshesAsMiscDirty();
- },
- 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;
- };
- /**
- * Child classes can use it to update shaders
- */
- StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
- if (useInstances === void 0) { useInstances = false; }
- if (subMesh.effect && this.isFrozen) {
- if (this._wasPreviouslyReady && subMesh.effect) {
- return true;
- }
- }
- if (!subMesh._materialDefines) {
- subMesh._materialDefines = new StandardMaterialDefines();
- }
- var scene = this.getScene();
- var defines = subMesh._materialDefines;
- if (!this.checkReadyOnEveryCall && subMesh.effect) {
- if (defines._renderId === scene.getRenderId()) {
- return true;
- }
- }
- var engine = scene.getEngine();
- // Lights
- defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
- // Textures
- if (defines._areTexturesDirty) {
- defines._needUVs = false;
- defines.MAINUV1 = false;
- defines.MAINUV2 = false;
- if (scene.texturesEnabled) {
- if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
- if (!this._diffuseTexture.isReadyOrNotBlocking()) {
- return false;
- }
- else {
- BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
- }
- }
- else {
- defines.DIFFUSE = false;
- }
- if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
- if (!this._ambientTexture.isReadyOrNotBlocking()) {
- return false;
- }
- else {
- BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
- }
- }
- else {
- defines.AMBIENT = false;
- }
- if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
- if (!this._opacityTexture.isReadyOrNotBlocking()) {
- return false;
- }
- else {
- BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
- defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
- }
- }
- else {
- defines.OPACITY = false;
- }
- if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
- if (!this._reflectionTexture.isReadyOrNotBlocking()) {
- return false;
- }
- else {
- defines._needNormals = true;
- defines.REFLECTION = true;
- defines.ROUGHNESS = (this._roughness > 0);
- defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
- defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
- defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
- switch (this._reflectionTexture.coordinatesMode) {
- case BABYLON.Texture.CUBIC_MODE:
- case BABYLON.Texture.INVCUBIC_MODE:
- defines.setReflectionMode("REFLECTIONMAP_CUBIC");
- break;
- case BABYLON.Texture.EXPLICIT_MODE:
- defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
- break;
- case BABYLON.Texture.PLANAR_MODE:
- defines.setReflectionMode("REFLECTIONMAP_PLANAR");
- break;
- case BABYLON.Texture.PROJECTION_MODE:
- defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
- break;
- case BABYLON.Texture.SKYBOX_MODE:
- defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
- break;
- case BABYLON.Texture.SPHERICAL_MODE:
- defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
- break;
- case BABYLON.Texture.EQUIRECTANGULAR_MODE:
- defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
- break;
- case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
- defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
- break;
- case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
- defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
- break;
- }
- }
- }
- else {
- defines.REFLECTION = false;
- }
- if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
- if (!this._emissiveTexture.isReadyOrNotBlocking()) {
- return false;
- }
- else {
- BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
- }
- }
- else {
- defines.EMISSIVE = false;
- }
- if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
- if (!this._lightmapTexture.isReadyOrNotBlocking()) {
- return false;
- }
- else {
- BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
- defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
- }
- }
- else {
- defines.LIGHTMAP = false;
- }
- if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
- if (!this._specularTexture.isReadyOrNotBlocking()) {
- return false;
- }
- else {
- BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
- defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
- }
- }
- else {
- defines.SPECULAR = false;
- }
- if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
- // Bump texure can not be not blocking.
- if (!this._bumpTexture.isReady()) {
- return false;
- }
- else {
- BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
- defines.PARALLAX = this._useParallax;
- defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
- }
- }
- else {
- defines.BUMP = false;
- }
- if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
- if (!this._refractionTexture.isReadyOrNotBlocking()) {
- return false;
- }
- else {
- defines._needUVs = true;
- defines.REFRACTION = true;
- defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
- }
- }
- else {
- defines.REFRACTION = false;
- }
- defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
- }
- else {
- defines.DIFFUSE = false;
- defines.AMBIENT = false;
- defines.OPACITY = false;
- defines.REFLECTION = false;
- defines.EMISSIVE = false;
- defines.LIGHTMAP = false;
- defines.BUMP = false;
- defines.REFRACTION = false;
- }
- defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
- defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
- defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
- defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
- defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
- }
- if (defines._areImageProcessingDirty) {
- if (!this._imageProcessingConfiguration.isReady()) {
- return false;
- }
- this._imageProcessingConfiguration.prepareDefines(defines);
- }
- if (defines._areFresnelDirty) {
- if (StandardMaterial.FresnelEnabled) {
- // Fresnel
- if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
- this._emissiveFresnelParameters || this._refractionFresnelParameters ||
- this._reflectionFresnelParameters) {
- defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
- defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
- defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
- defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
- defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
- defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
- defines._needNormals = true;
- defines.FRESNEL = true;
- }
- }
- else {
- defines.FRESNEL = false;
- }
- }
- // Misc.
- BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
- // Attribs
- BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
- // Values that need to be evaluated on every frame
- BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
- // Get correct effect
- if (defines.isDirty) {
- defines.markAsProcessed();
- scene.resetCachedMaterial();
- // Fallbacks
- var fallbacks = new BABYLON.EffectFallbacks();
- if (defines.REFLECTION) {
- fallbacks.addFallback(0, "REFLECTION");
- }
- if (defines.SPECULAR) {
- fallbacks.addFallback(0, "SPECULAR");
- }
- if (defines.BUMP) {
- fallbacks.addFallback(0, "BUMP");
- }
- if (defines.PARALLAX) {
- fallbacks.addFallback(1, "PARALLAX");
- }
- if (defines.PARALLAXOCCLUSION) {
- fallbacks.addFallback(0, "PARALLAXOCCLUSION");
- }
- if (defines.SPECULAROVERALPHA) {
- fallbacks.addFallback(0, "SPECULAROVERALPHA");
- }
- if (defines.FOG) {
- fallbacks.addFallback(1, "FOG");
- }
- if (defines.POINTSIZE) {
- fallbacks.addFallback(0, "POINTSIZE");
- }
- if (defines.LOGARITHMICDEPTH) {
- fallbacks.addFallback(0, "LOGARITHMICDEPTH");
- }
- BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
- if (defines.SPECULARTERM) {
- fallbacks.addFallback(0, "SPECULARTERM");
- }
- if (defines.DIFFUSEFRESNEL) {
- fallbacks.addFallback(1, "DIFFUSEFRESNEL");
- }
- if (defines.OPACITYFRESNEL) {
- fallbacks.addFallback(2, "OPACITYFRESNEL");
- }
- if (defines.REFLECTIONFRESNEL) {
- fallbacks.addFallback(3, "REFLECTIONFRESNEL");
- }
- if (defines.EMISSIVEFRESNEL) {
- fallbacks.addFallback(4, "EMISSIVEFRESNEL");
- }
- if (defines.FRESNEL) {
- fallbacks.addFallback(4, "FRESNEL");
- }
- //Attributes
- var attribs = [BABYLON.VertexBuffer.PositionKind];
- if (defines.NORMAL) {
- attribs.push(BABYLON.VertexBuffer.NormalKind);
- }
- if (defines.UV1) {
- attribs.push(BABYLON.VertexBuffer.UVKind);
- }
- if (defines.UV2) {
- attribs.push(BABYLON.VertexBuffer.UV2Kind);
- }
- if (defines.VERTEXCOLOR) {
- attribs.push(BABYLON.VertexBuffer.ColorKind);
- }
- BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
- BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
- BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
- var shaderName = "default";
- var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
- "vFogInfos", "vFogColor", "pointSize",
- "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
- "mBones",
- "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
- "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
- "logarithmicDepthConstant", "vTangentSpaceParams"
- ];
- var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
- var uniformBuffers = ["Material", "Scene"];
- BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
- BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
- BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
- uniformsNames: uniforms,
- uniformBuffersNames: uniformBuffers,
- samplers: samplers,
- defines: defines,
- maxSimultaneousLights: this._maxSimultaneousLights
- });
- if (this.customShaderNameResolve) {
- shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
- }
- var join = defines.toString();
- subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
- attributes: attribs,
- uniformsNames: uniforms,
- uniformBuffersNames: uniformBuffers,
- samplers: samplers,
- defines: join,
- fallbacks: fallbacks,
- onCompiled: this.onCompiled,
- onError: this.onError,
- indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
- }, engine), defines);
- this.buildUniformLayout();
- }
- if (!subMesh.effect || !subMesh.effect.isReady()) {
- return false;
- }
- defines._renderId = scene.getRenderId();
- this._wasPreviouslyReady = true;
- return true;
- };
- StandardMaterial.prototype.buildUniformLayout = function () {
- // Order is important !
- this._uniformBuffer.addUniform("diffuseLeftColor", 4);
- this._uniformBuffer.addUniform("diffuseRightColor", 4);
- this._uniformBuffer.addUniform("opacityParts", 4);
- this._uniformBuffer.addUniform("reflectionLeftColor", 4);
- this._uniformBuffer.addUniform("reflectionRightColor", 4);
- this._uniformBuffer.addUniform("refractionLeftColor", 4);
- this._uniformBuffer.addUniform("refractionRightColor", 4);
- this._uniformBuffer.addUniform("emissiveLeftColor", 4);
- this._uniformBuffer.addUniform("emissiveRightColor", 4);
- this._uniformBuffer.addUniform("vDiffuseInfos", 2);
- this._uniformBuffer.addUniform("vAmbientInfos", 2);
- this._uniformBuffer.addUniform("vOpacityInfos", 2);
- this._uniformBuffer.addUniform("vReflectionInfos", 2);
- this._uniformBuffer.addUniform("vEmissiveInfos", 2);
- this._uniformBuffer.addUniform("vLightmapInfos", 2);
- this._uniformBuffer.addUniform("vSpecularInfos", 2);
- this._uniformBuffer.addUniform("vBumpInfos", 3);
- this._uniformBuffer.addUniform("diffuseMatrix", 16);
- this._uniformBuffer.addUniform("ambientMatrix", 16);
- this._uniformBuffer.addUniform("opacityMatrix", 16);
- this._uniformBuffer.addUniform("reflectionMatrix", 16);
- this._uniformBuffer.addUniform("emissiveMatrix", 16);
- this._uniformBuffer.addUniform("lightmapMatrix", 16);
- this._uniformBuffer.addUniform("specularMatrix", 16);
- this._uniformBuffer.addUniform("bumpMatrix", 16);
- this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
- this._uniformBuffer.addUniform("refractionMatrix", 16);
- this._uniformBuffer.addUniform("vRefractionInfos", 4);
- this._uniformBuffer.addUniform("vSpecularColor", 4);
- this._uniformBuffer.addUniform("vEmissiveColor", 3);
- this._uniformBuffer.addUniform("vDiffuseColor", 4);
- this._uniformBuffer.addUniform("pointSize", 1);
- this._uniformBuffer.create();
- };
- StandardMaterial.prototype.unbind = function () {
- if (this._activeEffect) {
- if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
- this._activeEffect.setTexture("reflection2DSampler", null);
- }
- if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
- this._activeEffect.setTexture("refraction2DSampler", null);
- }
- }
- _super.prototype.unbind.call(this);
- };
- StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
- var scene = this.getScene();
- var defines = subMesh._materialDefines;
- if (!defines) {
- return;
- }
- var effect = subMesh.effect;
- if (!effect) {
- return;
- }
- this._activeEffect = effect;
- // Matrices
- this.bindOnlyWorldMatrix(world);
- var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
- // Bones
- BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
- if (mustRebind) {
- this._uniformBuffer.bindToEffect(effect, "Material");
- this.bindViewProjection(effect);
- if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
- if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
- // Fresnel
- if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
- this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
- this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
- }
- if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
- this._uniformBuffer.updateColor4("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._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
- this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
- }
- if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
- this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
- this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
- }
- if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
- this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
- this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
- }
- }
- // Textures
- if (scene.texturesEnabled) {
- if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
- this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
- BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
- }
- if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
- this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
- BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
- }
- if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
- this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
- BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
- }
- if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
- this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
- this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
- }
- if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
- this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
- BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
- }
- if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
- this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
- BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
- }
- if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
- this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
- BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
- }
- if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
- this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
- BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
- if (scene._mirroredCameraPosition) {
- this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
- }
- else {
- this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
- }
- }
- if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
- var depth = 1.0;
- if (!this._refractionTexture.isCube) {
- this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
- if (this._refractionTexture.depth) {
- depth = this._refractionTexture.depth;
- }
- }
- this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
- }
- }
- // Point size
- if (this.pointsCloud) {
- this._uniformBuffer.updateFloat("pointSize", this.pointSize);
- }
- if (defines.SPECULARTERM) {
- this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
- }
- this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
- // Diffuse
- this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
- }
- // Textures
- if (scene.texturesEnabled) {
- if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
- effect.setTexture("diffuseSampler", this._diffuseTexture);
- }
- if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
- effect.setTexture("ambientSampler", this._ambientTexture);
- }
- if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
- effect.setTexture("opacitySampler", this._opacityTexture);
- }
- if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
- if (this._reflectionTexture.isCube) {
- effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
- }
- else {
- effect.setTexture("reflection2DSampler", this._reflectionTexture);
- }
- }
- if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
- effect.setTexture("emissiveSampler", this._emissiveTexture);
- }
- if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
- effect.setTexture("lightmapSampler", this._lightmapTexture);
- }
- if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
- effect.setTexture("specularSampler", this._specularTexture);
- }
- if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
- effect.setTexture("bumpSampler", this._bumpTexture);
- }
- if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
- var depth = 1.0;
- if (this._refractionTexture.isCube) {
- effect.setTexture("refractionCubeSampler", this._refractionTexture);
- }
- else {
- effect.setTexture("refraction2DSampler", this._refractionTexture);
- }
- }
- }
- // Clip plane
- BABYLON.MaterialHelper.BindClipPlane(effect, scene);
- // Colors
- scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
- BABYLON.MaterialHelper.BindEyePosition(effect, scene);
- effect.setColor3("vAmbientColor", this._globalAmbientColor);
- }
- if (mustRebind || !this.isFrozen) {
- // Lights
- if (scene.lightsEnabled && !this._disableLighting) {
- BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
- }
- // View
- if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
- this.bindView(effect);
- }
- // Fog
- BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
- // Morph targets
- if (defines.NUM_MORPH_INFLUENCERS) {
- BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
- }
- // Log. depth
- BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
- // image processing
- if (!this._imageProcessingConfiguration.applyByPostProcess) {
- this._imageProcessingConfiguration.bind(this._activeEffect);
- }
- }
- this._uniformBuffer.update();
- this._afterBind(mesh, this._activeEffect);
- };
- 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.getActiveTextures = function () {
- var activeTextures = _super.prototype.getActiveTextures.call(this);
- if (this._diffuseTexture) {
- activeTextures.push(this._diffuseTexture);
- }
- if (this._ambientTexture) {
- activeTextures.push(this._ambientTexture);
- }
- if (this._opacityTexture) {
- activeTextures.push(this._opacityTexture);
- }
- if (this._reflectionTexture) {
- activeTextures.push(this._reflectionTexture);
- }
- if (this._emissiveTexture) {
- activeTextures.push(this._emissiveTexture);
- }
- if (this._specularTexture) {
- activeTextures.push(this._specularTexture);
- }
- if (this._bumpTexture) {
- activeTextures.push(this._bumpTexture);
- }
- if (this._lightmapTexture) {
- activeTextures.push(this._lightmapTexture);
- }
- if (this._refractionTexture) {
- activeTextures.push(this._refractionTexture);
- }
- return activeTextures;
- };
- StandardMaterial.prototype.hasTexture = function (texture) {
- if (_super.prototype.hasTexture.call(this, texture)) {
- return true;
- }
- if (this._diffuseTexture === texture) {
- return true;
- }
- if (this._ambientTexture === texture) {
- return true;
- }
- if (this._opacityTexture === texture) {
- return true;
- }
- if (this._reflectionTexture === texture) {
- return true;
- }
- if (this._emissiveTexture === texture) {
- return true;
- }
- if (this._specularTexture === texture) {
- return true;
- }
- if (this._bumpTexture === texture) {
- return true;
- }
- if (this._lightmapTexture === texture) {
- return true;
- }
- if (this._refractionTexture === texture) {
- return true;
- }
- return false;
- };
- 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();
- }
- }
- if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
- this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
- }
- _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
- };
- StandardMaterial.prototype.clone = function (name) {
- var _this = this;
- var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
- result.name = name;
- result.id = name;
- return result;
- };
- 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);
- };
- Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
- get: function () {
- return StandardMaterial._DiffuseTextureEnabled;
- },
- set: function (value) {
- if (StandardMaterial._DiffuseTextureEnabled === value) {
- return;
- }
- StandardMaterial._DiffuseTextureEnabled = value;
- BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
- get: function () {
- return StandardMaterial._AmbientTextureEnabled;
- },
- set: function (value) {
- if (StandardMaterial._AmbientTextureEnabled === value) {
- return;
- }
- StandardMaterial._AmbientTextureEnabled = value;
- BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
- get: function () {
- return StandardMaterial._OpacityTextureEnabled;
- },
- set: function (value) {
- if (StandardMaterial._OpacityTextureEnabled === value) {
- return;
- }
- StandardMaterial._OpacityTextureEnabled = value;
- BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
- get: function () {
- return StandardMaterial._ReflectionTextureEnabled;
- },
- set: function (value) {
- if (StandardMaterial._ReflectionTextureEnabled === value) {
- return;
- }
- StandardMaterial._ReflectionTextureEnabled = value;
- BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
- get: function () {
- return StandardMaterial._EmissiveTextureEnabled;
- },
- set: function (value) {
- if (StandardMaterial._EmissiveTextureEnabled === value) {
- return;
- }
- StandardMaterial._EmissiveTextureEnabled = value;
- BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
- get: function () {
- return StandardMaterial._SpecularTextureEnabled;
- },
- set: function (value) {
- if (StandardMaterial._SpecularTextureEnabled === value) {
- return;
- }
- StandardMaterial._SpecularTextureEnabled = value;
- BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
- get: function () {
- return StandardMaterial._BumpTextureEnabled;
- },
- set: function (value) {
- if (StandardMaterial._BumpTextureEnabled === value) {
- return;
- }
- StandardMaterial._BumpTextureEnabled = value;
- BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
- get: function () {
- return StandardMaterial._LightmapTextureEnabled;
- },
- set: function (value) {
- if (StandardMaterial._LightmapTextureEnabled === value) {
- return;
- }
- StandardMaterial._LightmapTextureEnabled = value;
- BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
- get: function () {
- return StandardMaterial._RefractionTextureEnabled;
- },
- set: function (value) {
- if (StandardMaterial._RefractionTextureEnabled === value) {
- return;
- }
- StandardMaterial._RefractionTextureEnabled = value;
- BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
- get: function () {
- return StandardMaterial._ColorGradingTextureEnabled;
- },
- set: function (value) {
- if (StandardMaterial._ColorGradingTextureEnabled === value) {
- return;
- }
- StandardMaterial._ColorGradingTextureEnabled = value;
- BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(StandardMaterial, "FresnelEnabled", {
- get: function () {
- return StandardMaterial._FresnelEnabled;
- },
- set: function (value) {
- if (StandardMaterial._FresnelEnabled === value) {
- return;
- }
- StandardMaterial._FresnelEnabled = value;
- BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
- },
- enumerable: true,
- configurable: true
- });
- // 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._LightmapTextureEnabled = true;
- StandardMaterial._RefractionTextureEnabled = true;
- StandardMaterial._ColorGradingTextureEnabled = true;
- StandardMaterial._FresnelEnabled = true;
- __decorate([
- BABYLON.serializeAsTexture("diffuseTexture")
- ], StandardMaterial.prototype, "_diffuseTexture", void 0);
- __decorate([
- BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
- ], StandardMaterial.prototype, "diffuseTexture", void 0);
- __decorate([
- BABYLON.serializeAsTexture("ambientTexture")
- ], StandardMaterial.prototype, "_ambientTexture", void 0);
- __decorate([
- BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
- ], StandardMaterial.prototype, "ambientTexture", void 0);
- __decorate([
- BABYLON.serializeAsTexture("opacityTexture")
- ], StandardMaterial.prototype, "_opacityTexture", void 0);
- __decorate([
- BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
- ], StandardMaterial.prototype, "opacityTexture", void 0);
- __decorate([
- BABYLON.serializeAsTexture("reflectionTexture")
- ], StandardMaterial.prototype, "_reflectionTexture", void 0);
- __decorate([
- BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
- ], StandardMaterial.prototype, "reflectionTexture", void 0);
- __decorate([
- BABYLON.serializeAsTexture("emissiveTexture")
- ], StandardMaterial.prototype, "_emissiveTexture", void 0);
- __decorate([
- BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
- ], StandardMaterial.prototype, "emissiveTexture", void 0);
- __decorate([
- BABYLON.serializeAsTexture("specularTexture")
- ], StandardMaterial.prototype, "_specularTexture", void 0);
- __decorate([
- BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
- ], StandardMaterial.prototype, "specularTexture", void 0);
- __decorate([
- BABYLON.serializeAsTexture("bumpTexture")
- ], StandardMaterial.prototype, "_bumpTexture", void 0);
- __decorate([
- BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
- ], StandardMaterial.prototype, "bumpTexture", void 0);
- __decorate([
- BABYLON.serializeAsTexture("lightmapTexture")
- ], StandardMaterial.prototype, "_lightmapTexture", void 0);
- __decorate([
- BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
- ], StandardMaterial.prototype, "lightmapTexture", void 0);
- __decorate([
- BABYLON.serializeAsTexture("refractionTexture")
- ], StandardMaterial.prototype, "_refractionTexture", void 0);
- __decorate([
- BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
- ], 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("useAlphaFromDiffuseTexture")
- ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
- __decorate([
- BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
- ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
- __decorate([
- BABYLON.serialize("useEmissiveAsIllumination")
- ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
- __decorate([
- BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
- ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
- __decorate([
- BABYLON.serialize("linkEmissiveWithDiffuse")
- ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
- __decorate([
- BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
- ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
- __decorate([
- BABYLON.serialize("useSpecularOverAlpha")
- ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
- __decorate([
- BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
- ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
- __decorate([
- BABYLON.serialize("useReflectionOverAlpha")
- ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
- __decorate([
- BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
- ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
- __decorate([
- BABYLON.serialize("disableLighting")
- ], StandardMaterial.prototype, "_disableLighting", void 0);
- __decorate([
- BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
- ], StandardMaterial.prototype, "disableLighting", void 0);
- __decorate([
- BABYLON.serialize("useParallax")
- ], StandardMaterial.prototype, "_useParallax", void 0);
- __decorate([
- BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
- ], StandardMaterial.prototype, "useParallax", void 0);
- __decorate([
- BABYLON.serialize("useParallaxOcclusion")
- ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
- __decorate([
- BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
- ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
- __decorate([
- BABYLON.serialize()
- ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
- __decorate([
- BABYLON.serialize("roughness")
- ], StandardMaterial.prototype, "_roughness", void 0);
- __decorate([
- BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
- ], StandardMaterial.prototype, "roughness", void 0);
- __decorate([
- BABYLON.serialize()
- ], StandardMaterial.prototype, "indexOfRefraction", void 0);
- __decorate([
- BABYLON.serialize()
- ], StandardMaterial.prototype, "invertRefractionY", void 0);
- __decorate([
- BABYLON.serialize("useLightmapAsShadowmap")
- ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
- __decorate([
- BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
- ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
- __decorate([
- BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
- ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
- __decorate([
- BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
- ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
- __decorate([
- BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
- ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
- __decorate([
- BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
- ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
- __decorate([
- BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
- ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
- __decorate([
- BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
- ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
- __decorate([
- BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
- ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
- __decorate([
- BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
- ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
- __decorate([
- BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
- ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
- __decorate([
- BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
- ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
- __decorate([
- BABYLON.serialize("useReflectionFresnelFromSpecular")
- ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
- __decorate([
- BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
- ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
- __decorate([
- BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
- ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
- __decorate([
- BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
- ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
- __decorate([
- BABYLON.serialize("maxSimultaneousLights")
- ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
- __decorate([
- BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
- ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
- __decorate([
- BABYLON.serialize("invertNormalMapX")
- ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
- __decorate([
- BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
- ], StandardMaterial.prototype, "invertNormalMapX", void 0);
- __decorate([
- BABYLON.serialize("invertNormalMapY")
- ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
- __decorate([
- BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
- ], StandardMaterial.prototype, "invertNormalMapY", void 0);
- __decorate([
- BABYLON.serialize("twoSidedLighting")
- ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
- __decorate([
- BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
- ], StandardMaterial.prototype, "twoSidedLighting", void 0);
- __decorate([
- BABYLON.serialize()
- ], StandardMaterial.prototype, "useLogarithmicDepth", null);
- return StandardMaterial;
- }(BABYLON.PushMaterial));
- BABYLON.StandardMaterial = StandardMaterial;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.standardMaterial.js.map
- (function() {
- var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
- globalObject["BABYLON"] = BABYLON;
- })();;
- var EffectFallbacks = BABYLON.EffectFallbacks;
- var EffectCreationOptions = BABYLON.EffectCreationOptions;
- var Effect = BABYLON.Effect;
- var KeyboardEventTypes = BABYLON.KeyboardEventTypes;
- var KeyboardInfo = BABYLON.KeyboardInfo;
- var KeyboardInfoPre = BABYLON.KeyboardInfoPre;
- var PointerEventTypes = BABYLON.PointerEventTypes;
- var PointerInfoBase = BABYLON.PointerInfoBase;
- var PointerInfoPre = BABYLON.PointerInfoPre;
- var PointerInfo = BABYLON.PointerInfo;
- var ToGammaSpace = BABYLON.ToGammaSpace;
- var ToLinearSpace = BABYLON.ToLinearSpace;
- var Epsilon = BABYLON.Epsilon;
- var Color3 = BABYLON.Color3;
- var Color4 = BABYLON.Color4;
- var Vector2 = BABYLON.Vector2;
- var Vector3 = BABYLON.Vector3;
- var Vector4 = BABYLON.Vector4;
- var Size = BABYLON.Size;
- var Quaternion = BABYLON.Quaternion;
- var Matrix = BABYLON.Matrix;
- var Plane = BABYLON.Plane;
- var Viewport = BABYLON.Viewport;
- var Frustum = BABYLON.Frustum;
- var Space = BABYLON.Space;
- var Axis = BABYLON.Axis;
- var BezierCurve = BABYLON.BezierCurve;
- var Orientation = BABYLON.Orientation;
- var Angle = BABYLON.Angle;
- var Arc2 = BABYLON.Arc2;
- var Path2 = BABYLON.Path2;
- var Path3D = BABYLON.Path3D;
- var Curve3 = BABYLON.Curve3;
- var PositionNormalVertex = BABYLON.PositionNormalVertex;
- var PositionNormalTextureVertex = BABYLON.PositionNormalTextureVertex;
- var Tmp = BABYLON.Tmp;
- var Scalar = BABYLON.Scalar;
- var expandToProperty = BABYLON.expandToProperty;
- var serialize = BABYLON.serialize;
- var serializeAsTexture = BABYLON.serializeAsTexture;
- var serializeAsColor3 = BABYLON.serializeAsColor3;
- var serializeAsFresnelParameters = BABYLON.serializeAsFresnelParameters;
- var serializeAsVector2 = BABYLON.serializeAsVector2;
- var serializeAsVector3 = BABYLON.serializeAsVector3;
- var serializeAsMeshReference = BABYLON.serializeAsMeshReference;
- var serializeAsColorCurves = BABYLON.serializeAsColorCurves;
- var serializeAsColor4 = BABYLON.serializeAsColor4;
- var serializeAsImageProcessingConfiguration = BABYLON.serializeAsImageProcessingConfiguration;
- var serializeAsQuaternion = BABYLON.serializeAsQuaternion;
- var SerializationHelper = BABYLON.SerializationHelper;
- var EventState = BABYLON.EventState;
- var Observer = BABYLON.Observer;
- var MultiObserver = BABYLON.MultiObserver;
- var Observable = BABYLON.Observable;
- var SmartArray = BABYLON.SmartArray;
- var SmartArrayNoDuplicate = BABYLON.SmartArrayNoDuplicate;
- var LoadFileError = BABYLON.LoadFileError;
- var RetryStrategy = BABYLON.RetryStrategy;
- var Tools = BABYLON.Tools;
- var PerfCounter = BABYLON.PerfCounter;
- var className = BABYLON.className;
- var AsyncLoop = BABYLON.AsyncLoop;
- var _AlphaState = BABYLON._AlphaState;
- var _DepthCullingState = BABYLON._DepthCullingState;
- var _StencilState = BABYLON._StencilState;
- var InstancingAttributeInfo = BABYLON.InstancingAttributeInfo;
- var RenderTargetCreationOptions = BABYLON.RenderTargetCreationOptions;
- var EngineCapabilities = BABYLON.EngineCapabilities;
- var Engine = BABYLON.Engine;
- var Node = BABYLON.Node;
- var BoundingSphere = BABYLON.BoundingSphere;
- var BoundingBox = BABYLON.BoundingBox;
- var BoundingInfo = BABYLON.BoundingInfo;
- var TransformNode = BABYLON.TransformNode;
- var AbstractMesh = BABYLON.AbstractMesh;
- var Light = BABYLON.Light;
- var Camera = BABYLON.Camera;
- var RenderingManager = BABYLON.RenderingManager;
- var RenderingGroup = BABYLON.RenderingGroup;
- var RenderingGroupInfo = BABYLON.RenderingGroupInfo;
- var Scene = BABYLON.Scene;
- var Buffer = BABYLON.Buffer;
- var VertexBuffer = BABYLON.VertexBuffer;
- var InternalTexture = BABYLON.InternalTexture;
- var BaseTexture = BABYLON.BaseTexture;
- var Texture = BABYLON.Texture;
- var _InstancesBatch = BABYLON._InstancesBatch;
- var Mesh = BABYLON.Mesh;
- var BaseSubMesh = BABYLON.BaseSubMesh;
- var SubMesh = BABYLON.SubMesh;
- var MaterialDefines = BABYLON.MaterialDefines;
- var Material = BABYLON.Material;
- var UniformBuffer = BABYLON.UniformBuffer;
- var VertexData = BABYLON.VertexData;
- var Geometry = BABYLON.Geometry;
- var _PrimitiveGeometry = BABYLON._PrimitiveGeometry;
- var RibbonGeometry = BABYLON.RibbonGeometry;
- var BoxGeometry = BABYLON.BoxGeometry;
- var SphereGeometry = BABYLON.SphereGeometry;
- var DiscGeometry = BABYLON.DiscGeometry;
- var CylinderGeometry = BABYLON.CylinderGeometry;
- var TorusGeometry = BABYLON.TorusGeometry;
- var GroundGeometry = BABYLON.GroundGeometry;
- var TiledGroundGeometry = BABYLON.TiledGroundGeometry;
- var PlaneGeometry = BABYLON.PlaneGeometry;
- var TorusKnotGeometry = BABYLON.TorusKnotGeometry;
- var PostProcessManager = BABYLON.PostProcessManager;
- var PerformanceMonitor = BABYLON.PerformanceMonitor;
- var RollingAverage = BABYLON.RollingAverage;
- var ImageProcessingConfiguration = BABYLON.ImageProcessingConfiguration;
- var ColorGradingTexture = BABYLON.ColorGradingTexture;
- var ColorCurves = BABYLON.ColorCurves;
- var MaterialHelper = BABYLON.MaterialHelper;
- var PushMaterial = BABYLON.PushMaterial;
- var StandardMaterialDefines = BABYLON.StandardMaterialDefines;
- var StandardMaterial = BABYLON.StandardMaterial;
- export { EffectFallbacks,EffectCreationOptions,Effect,KeyboardEventTypes,KeyboardInfo,KeyboardInfoPre,PointerEventTypes,PointerInfoBase,PointerInfoPre,PointerInfo,ToGammaSpace,ToLinearSpace,Epsilon,Color3,Color4,Vector2,Vector3,Vector4,Size,Quaternion,Matrix,Plane,Viewport,Frustum,Space,Axis,BezierCurve,Orientation,Angle,Arc2,Path2,Path3D,Curve3,PositionNormalVertex,PositionNormalTextureVertex,Tmp,Scalar,expandToProperty,serialize,serializeAsTexture,serializeAsColor3,serializeAsFresnelParameters,serializeAsVector2,serializeAsVector3,serializeAsMeshReference,serializeAsColorCurves,serializeAsColor4,serializeAsImageProcessingConfiguration,serializeAsQuaternion,SerializationHelper,EventState,Observer,MultiObserver,Observable,SmartArray,SmartArrayNoDuplicate,LoadFileError,RetryStrategy,Tools,PerfCounter,className,AsyncLoop,_AlphaState,_DepthCullingState,_StencilState,InstancingAttributeInfo,RenderTargetCreationOptions,EngineCapabilities,Engine,Node,BoundingSphere,BoundingBox,BoundingInfo,TransformNode,AbstractMesh,Light,Camera,RenderingManager,RenderingGroup,RenderingGroupInfo,Scene,Buffer,VertexBuffer,InternalTexture,BaseTexture,Texture,_InstancesBatch,Mesh,BaseSubMesh,SubMesh,MaterialDefines,Material,UniformBuffer,VertexData,Geometry,_PrimitiveGeometry,RibbonGeometry,BoxGeometry,SphereGeometry,DiscGeometry,CylinderGeometry,TorusGeometry,GroundGeometry,TiledGroundGeometry,PlaneGeometry,TorusKnotGeometry,PostProcessManager,PerformanceMonitor,RollingAverage,ImageProcessingConfiguration,ColorGradingTexture,ColorCurves,MaterialHelper,PushMaterial,StandardMaterialDefines,StandardMaterial };
|