es6.js 1.7 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399
  1. var __extends = (this && this.__extends) || (function () {
  2. var extendStatics = Object.setPrototypeOf ||
  3. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  5. return function (d, b) {
  6. extendStatics(d, b);
  7. function __() { this.constructor = d; }
  8. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  9. };
  10. })();
  11. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  12. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  13. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  14. 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;
  15. return c > 3 && r && Object.defineProperty(target, key, r), r;
  16. };
  17. var BABYLON;
  18. (function (BABYLON) {
  19. var EffectFallbacks = /** @class */ (function () {
  20. function EffectFallbacks() {
  21. this._defines = {};
  22. this._currentRank = 32;
  23. this._maxRank = -1;
  24. }
  25. EffectFallbacks.prototype.unBindMesh = function () {
  26. this._mesh = null;
  27. };
  28. EffectFallbacks.prototype.addFallback = function (rank, define) {
  29. if (!this._defines[rank]) {
  30. if (rank < this._currentRank) {
  31. this._currentRank = rank;
  32. }
  33. if (rank > this._maxRank) {
  34. this._maxRank = rank;
  35. }
  36. this._defines[rank] = new Array();
  37. }
  38. this._defines[rank].push(define);
  39. };
  40. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  41. this._mesh = mesh;
  42. if (rank < this._currentRank) {
  43. this._currentRank = rank;
  44. }
  45. if (rank > this._maxRank) {
  46. this._maxRank = rank;
  47. }
  48. };
  49. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  50. get: function () {
  51. return this._currentRank <= this._maxRank;
  52. },
  53. enumerable: true,
  54. configurable: true
  55. });
  56. EffectFallbacks.prototype.reduce = function (currentDefines) {
  57. // First we try to switch to CPU skinning
  58. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  59. this._mesh.computeBonesUsingShaders = false;
  60. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  61. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  62. var scene = this._mesh.getScene();
  63. for (var index = 0; index < scene.meshes.length; index++) {
  64. var otherMesh = scene.meshes[index];
  65. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  66. otherMesh.computeBonesUsingShaders = false;
  67. }
  68. }
  69. }
  70. else {
  71. var currentFallbacks = this._defines[this._currentRank];
  72. if (currentFallbacks) {
  73. for (var index = 0; index < currentFallbacks.length; index++) {
  74. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  75. }
  76. }
  77. this._currentRank++;
  78. }
  79. return currentDefines;
  80. };
  81. return EffectFallbacks;
  82. }());
  83. BABYLON.EffectFallbacks = EffectFallbacks;
  84. var EffectCreationOptions = /** @class */ (function () {
  85. function EffectCreationOptions() {
  86. }
  87. return EffectCreationOptions;
  88. }());
  89. BABYLON.EffectCreationOptions = EffectCreationOptions;
  90. var Effect = /** @class */ (function () {
  91. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  92. if (samplers === void 0) { samplers = null; }
  93. if (defines === void 0) { defines = null; }
  94. if (fallbacks === void 0) { fallbacks = null; }
  95. if (onCompiled === void 0) { onCompiled = null; }
  96. if (onError === void 0) { onError = null; }
  97. var _this = this;
  98. this.uniqueId = 0;
  99. this.onCompileObservable = new BABYLON.Observable();
  100. this.onErrorObservable = new BABYLON.Observable();
  101. this.onBindObservable = new BABYLON.Observable();
  102. this._uniformBuffersNames = {};
  103. this._isReady = false;
  104. this._compilationError = "";
  105. this.name = baseName;
  106. if (attributesNamesOrOptions.attributes) {
  107. var options = attributesNamesOrOptions;
  108. this._engine = uniformsNamesOrEngine;
  109. this._attributesNames = options.attributes;
  110. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  111. this._samplers = options.samplers;
  112. this.defines = options.defines;
  113. this.onError = options.onError;
  114. this.onCompiled = options.onCompiled;
  115. this._fallbacks = options.fallbacks;
  116. this._indexParameters = options.indexParameters;
  117. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  118. if (options.uniformBuffersNames) {
  119. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  120. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  121. }
  122. }
  123. }
  124. else {
  125. this._engine = engine;
  126. this.defines = defines;
  127. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  128. this._samplers = samplers;
  129. this._attributesNames = attributesNamesOrOptions;
  130. this.onError = onError;
  131. this.onCompiled = onCompiled;
  132. this._indexParameters = indexParameters;
  133. this._fallbacks = fallbacks;
  134. }
  135. this.uniqueId = Effect._uniqueIdSeed++;
  136. var vertexSource;
  137. var fragmentSource;
  138. if (baseName.vertexElement) {
  139. vertexSource = document.getElementById(baseName.vertexElement);
  140. if (!vertexSource) {
  141. vertexSource = baseName.vertexElement;
  142. }
  143. }
  144. else {
  145. vertexSource = baseName.vertex || baseName;
  146. }
  147. if (baseName.fragmentElement) {
  148. fragmentSource = document.getElementById(baseName.fragmentElement);
  149. if (!fragmentSource) {
  150. fragmentSource = baseName.fragmentElement;
  151. }
  152. }
  153. else {
  154. fragmentSource = baseName.fragment || baseName;
  155. }
  156. this._loadVertexShader(vertexSource, function (vertexCode) {
  157. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  158. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  159. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  160. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  161. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  162. if (baseName) {
  163. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  164. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  165. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  166. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  167. }
  168. else {
  169. _this._vertexSourceCode = migratedVertexCode;
  170. _this._fragmentSourceCode = migratedFragmentCode;
  171. }
  172. _this._prepareEffect();
  173. });
  174. });
  175. });
  176. });
  177. });
  178. });
  179. }
  180. Object.defineProperty(Effect.prototype, "key", {
  181. get: function () {
  182. return this._key;
  183. },
  184. enumerable: true,
  185. configurable: true
  186. });
  187. // Properties
  188. Effect.prototype.isReady = function () {
  189. return this._isReady;
  190. };
  191. Effect.prototype.getEngine = function () {
  192. return this._engine;
  193. };
  194. Effect.prototype.getProgram = function () {
  195. return this._program;
  196. };
  197. Effect.prototype.getAttributesNames = function () {
  198. return this._attributesNames;
  199. };
  200. Effect.prototype.getAttributeLocation = function (index) {
  201. return this._attributes[index];
  202. };
  203. Effect.prototype.getAttributeLocationByName = function (name) {
  204. var index = this._attributesNames.indexOf(name);
  205. return this._attributes[index];
  206. };
  207. Effect.prototype.getAttributesCount = function () {
  208. return this._attributes.length;
  209. };
  210. Effect.prototype.getUniformIndex = function (uniformName) {
  211. return this._uniformsNames.indexOf(uniformName);
  212. };
  213. Effect.prototype.getUniform = function (uniformName) {
  214. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  215. };
  216. Effect.prototype.getSamplers = function () {
  217. return this._samplers;
  218. };
  219. Effect.prototype.getCompilationError = function () {
  220. return this._compilationError;
  221. };
  222. // Methods
  223. Effect.prototype.executeWhenCompiled = function (func) {
  224. if (this.isReady()) {
  225. func(this);
  226. return;
  227. }
  228. this.onCompileObservable.add(function (effect) {
  229. func(effect);
  230. });
  231. };
  232. Effect.prototype._loadVertexShader = function (vertex, callback) {
  233. if (BABYLON.Tools.IsWindowObjectExist()) {
  234. // DOM element ?
  235. if (vertex instanceof HTMLElement) {
  236. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  237. callback(vertexCode);
  238. return;
  239. }
  240. }
  241. // Base64 encoded ?
  242. if (vertex.substr(0, 7) === "base64:") {
  243. var vertexBinary = window.atob(vertex.substr(7));
  244. callback(vertexBinary);
  245. return;
  246. }
  247. // Is in local store ?
  248. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  249. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  250. return;
  251. }
  252. var vertexShaderUrl;
  253. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  254. vertexShaderUrl = vertex;
  255. }
  256. else {
  257. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  258. }
  259. // Vertex shader
  260. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  261. };
  262. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  263. if (BABYLON.Tools.IsWindowObjectExist()) {
  264. // DOM element ?
  265. if (fragment instanceof HTMLElement) {
  266. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  267. callback(fragmentCode);
  268. return;
  269. }
  270. }
  271. // Base64 encoded ?
  272. if (fragment.substr(0, 7) === "base64:") {
  273. var fragmentBinary = window.atob(fragment.substr(7));
  274. callback(fragmentBinary);
  275. return;
  276. }
  277. // Is in local store ?
  278. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  279. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  280. return;
  281. }
  282. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  283. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  284. return;
  285. }
  286. var fragmentShaderUrl;
  287. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  288. fragmentShaderUrl = fragment;
  289. }
  290. else {
  291. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  292. }
  293. // Fragment shader
  294. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  295. };
  296. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  297. // Rebuild shaders source code
  298. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  299. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  300. vertexCode = prefix + vertexCode;
  301. fragmentCode = prefix + fragmentCode;
  302. // Number lines of shaders source code
  303. var i = 2;
  304. var regex = /\n/gm;
  305. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  306. i = 2;
  307. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  308. // Dump shaders name and formatted source code
  309. if (this.name.vertexElement) {
  310. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  311. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  312. }
  313. else if (this.name.vertex) {
  314. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  315. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  316. }
  317. else {
  318. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  319. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  320. }
  321. };
  322. ;
  323. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  324. var preparedSourceCode = this._processPrecision(sourceCode);
  325. if (this._engine.webGLVersion == 1) {
  326. callback(preparedSourceCode);
  327. return;
  328. }
  329. // Already converted
  330. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  331. callback(preparedSourceCode.replace("#version 300 es", ""));
  332. return;
  333. }
  334. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  335. // Remove extensions
  336. // #extension GL_OES_standard_derivatives : enable
  337. // #extension GL_EXT_shader_texture_lod : enable
  338. // #extension GL_EXT_frag_depth : enable
  339. // #extension GL_EXT_draw_buffers : require
  340. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  341. var result = preparedSourceCode.replace(regex, "");
  342. // Migrate to GLSL v300
  343. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  344. result = result.replace(/attribute[ \t]/g, "in ");
  345. result = result.replace(/[ \t]attribute/g, " in");
  346. if (isFragment) {
  347. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  348. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  349. result = result.replace(/texture2D\s*\(/g, "texture(");
  350. result = result.replace(/textureCube\s*\(/g, "texture(");
  351. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  352. result = result.replace(/gl_FragColor/g, "glFragColor");
  353. result = result.replace(/gl_FragData/g, "glFragData");
  354. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  355. }
  356. callback(result);
  357. };
  358. Effect.prototype._processIncludes = function (sourceCode, callback) {
  359. var _this = this;
  360. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  361. var match = regex.exec(sourceCode);
  362. var returnValue = new String(sourceCode);
  363. while (match != null) {
  364. var includeFile = match[1];
  365. // Uniform declaration
  366. if (includeFile.indexOf("__decl__") !== -1) {
  367. includeFile = includeFile.replace(/__decl__/, "");
  368. if (this._engine.supportsUniformBuffers) {
  369. includeFile = includeFile.replace(/Vertex/, "Ubo");
  370. includeFile = includeFile.replace(/Fragment/, "Ubo");
  371. }
  372. includeFile = includeFile + "Declaration";
  373. }
  374. if (Effect.IncludesShadersStore[includeFile]) {
  375. // Substitution
  376. var includeContent = Effect.IncludesShadersStore[includeFile];
  377. if (match[2]) {
  378. var splits = match[3].split(",");
  379. for (var index = 0; index < splits.length; index += 2) {
  380. var source = new RegExp(splits[index], "g");
  381. var dest = splits[index + 1];
  382. includeContent = includeContent.replace(source, dest);
  383. }
  384. }
  385. if (match[4]) {
  386. var indexString = match[5];
  387. if (indexString.indexOf("..") !== -1) {
  388. var indexSplits = indexString.split("..");
  389. var minIndex = parseInt(indexSplits[0]);
  390. var maxIndex = parseInt(indexSplits[1]);
  391. var sourceIncludeContent = includeContent.slice(0);
  392. includeContent = "";
  393. if (isNaN(maxIndex)) {
  394. maxIndex = this._indexParameters[indexSplits[1]];
  395. }
  396. for (var i = minIndex; i < maxIndex; i++) {
  397. if (!this._engine.supportsUniformBuffers) {
  398. // Ubo replacement
  399. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  400. return p1 + "{X}";
  401. });
  402. }
  403. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  404. }
  405. }
  406. else {
  407. if (!this._engine.supportsUniformBuffers) {
  408. // Ubo replacement
  409. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  410. return p1 + "{X}";
  411. });
  412. }
  413. includeContent = includeContent.replace(/\{X\}/g, indexString);
  414. }
  415. }
  416. // Replace
  417. returnValue = returnValue.replace(match[0], includeContent);
  418. }
  419. else {
  420. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  421. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  422. Effect.IncludesShadersStore[includeFile] = fileContent;
  423. _this._processIncludes(returnValue, callback);
  424. });
  425. return;
  426. }
  427. match = regex.exec(sourceCode);
  428. }
  429. callback(returnValue);
  430. };
  431. Effect.prototype._processPrecision = function (source) {
  432. if (source.indexOf("precision highp float") === -1) {
  433. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  434. source = "precision mediump float;\n" + source;
  435. }
  436. else {
  437. source = "precision highp float;\n" + source;
  438. }
  439. }
  440. else {
  441. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  442. source = source.replace("precision highp float", "precision mediump float");
  443. }
  444. }
  445. return source;
  446. };
  447. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  448. var _this = this;
  449. this._isReady = false;
  450. this._vertexSourceCodeOverride = vertexSourceCode;
  451. this._fragmentSourceCodeOverride = fragmentSourceCode;
  452. this.onError = function (effect, error) {
  453. if (onError) {
  454. onError(error);
  455. }
  456. };
  457. this.onCompiled = function () {
  458. var scenes = _this.getEngine().scenes;
  459. for (var i = 0; i < scenes.length; i++) {
  460. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  461. }
  462. if (onCompiled) {
  463. onCompiled(_this._program);
  464. }
  465. };
  466. this._fallbacks = null;
  467. this._prepareEffect();
  468. };
  469. Effect.prototype.getSpecificUniformLocations = function (names) {
  470. var engine = this._engine;
  471. return engine.getUniforms(this._program, names);
  472. };
  473. Effect.prototype._prepareEffect = function () {
  474. var attributesNames = this._attributesNames;
  475. var defines = this.defines;
  476. var fallbacks = this._fallbacks;
  477. this._valueCache = {};
  478. var previousProgram = this._program;
  479. try {
  480. var engine = this._engine;
  481. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  482. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  483. }
  484. else {
  485. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  486. }
  487. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  488. if (engine.supportsUniformBuffers) {
  489. for (var name in this._uniformBuffersNames) {
  490. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  491. }
  492. }
  493. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  494. this._attributes = engine.getAttributes(this._program, attributesNames);
  495. var index;
  496. for (index = 0; index < this._samplers.length; index++) {
  497. var sampler = this.getUniform(this._samplers[index]);
  498. if (sampler == null) {
  499. this._samplers.splice(index, 1);
  500. index--;
  501. }
  502. }
  503. engine.bindSamplers(this);
  504. this._compilationError = "";
  505. this._isReady = true;
  506. if (this.onCompiled) {
  507. this.onCompiled(this);
  508. }
  509. this.onCompileObservable.notifyObservers(this);
  510. this.onCompileObservable.clear();
  511. // Unbind mesh reference in fallbacks
  512. if (this._fallbacks) {
  513. this._fallbacks.unBindMesh();
  514. }
  515. if (previousProgram) {
  516. this.getEngine()._deleteProgram(previousProgram);
  517. }
  518. }
  519. catch (e) {
  520. this._compilationError = e.message;
  521. // Let's go through fallbacks then
  522. BABYLON.Tools.Error("Unable to compile effect:");
  523. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  524. return " " + uniform;
  525. }));
  526. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  527. return " " + attribute;
  528. }));
  529. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  530. BABYLON.Tools.Error("Error: " + this._compilationError);
  531. if (previousProgram) {
  532. this._program = previousProgram;
  533. this._isReady = true;
  534. if (this.onError) {
  535. this.onError(this, this._compilationError);
  536. }
  537. this.onErrorObservable.notifyObservers(this);
  538. }
  539. if (fallbacks && fallbacks.isMoreFallbacks) {
  540. BABYLON.Tools.Error("Trying next fallback.");
  541. this.defines = fallbacks.reduce(this.defines);
  542. this._prepareEffect();
  543. }
  544. else {
  545. if (this.onError) {
  546. this.onError(this, this._compilationError);
  547. }
  548. this.onErrorObservable.notifyObservers(this);
  549. this.onErrorObservable.clear();
  550. // Unbind mesh reference in fallbacks
  551. if (this._fallbacks) {
  552. this._fallbacks.unBindMesh();
  553. }
  554. }
  555. }
  556. };
  557. Object.defineProperty(Effect.prototype, "isSupported", {
  558. get: function () {
  559. return this._compilationError === "";
  560. },
  561. enumerable: true,
  562. configurable: true
  563. });
  564. Effect.prototype._bindTexture = function (channel, texture) {
  565. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  566. };
  567. Effect.prototype.setTexture = function (channel, texture) {
  568. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  569. };
  570. Effect.prototype.setTextureArray = function (channel, textures) {
  571. if (this._samplers.indexOf(channel + "Ex") === -1) {
  572. var initialPos = this._samplers.indexOf(channel);
  573. for (var index = 1; index < textures.length; index++) {
  574. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  575. }
  576. }
  577. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  578. };
  579. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  580. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  581. };
  582. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  583. var cache = this._valueCache[uniformName];
  584. var flag = matrix.updateFlag;
  585. if (cache !== undefined && cache === flag) {
  586. return false;
  587. }
  588. this._valueCache[uniformName] = flag;
  589. return true;
  590. };
  591. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  592. var cache = this._valueCache[uniformName];
  593. if (!cache) {
  594. cache = [x, y];
  595. this._valueCache[uniformName] = cache;
  596. return true;
  597. }
  598. var changed = false;
  599. if (cache[0] !== x) {
  600. cache[0] = x;
  601. changed = true;
  602. }
  603. if (cache[1] !== y) {
  604. cache[1] = y;
  605. changed = true;
  606. }
  607. return changed;
  608. };
  609. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  610. var cache = this._valueCache[uniformName];
  611. if (!cache) {
  612. cache = [x, y, z];
  613. this._valueCache[uniformName] = cache;
  614. return true;
  615. }
  616. var changed = false;
  617. if (cache[0] !== x) {
  618. cache[0] = x;
  619. changed = true;
  620. }
  621. if (cache[1] !== y) {
  622. cache[1] = y;
  623. changed = true;
  624. }
  625. if (cache[2] !== z) {
  626. cache[2] = z;
  627. changed = true;
  628. }
  629. return changed;
  630. };
  631. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  632. var cache = this._valueCache[uniformName];
  633. if (!cache) {
  634. cache = [x, y, z, w];
  635. this._valueCache[uniformName] = cache;
  636. return true;
  637. }
  638. var changed = false;
  639. if (cache[0] !== x) {
  640. cache[0] = x;
  641. changed = true;
  642. }
  643. if (cache[1] !== y) {
  644. cache[1] = y;
  645. changed = true;
  646. }
  647. if (cache[2] !== z) {
  648. cache[2] = z;
  649. changed = true;
  650. }
  651. if (cache[3] !== w) {
  652. cache[3] = w;
  653. changed = true;
  654. }
  655. return changed;
  656. };
  657. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  658. var bufferName = this._uniformBuffersNames[name];
  659. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  660. return;
  661. }
  662. Effect._baseCache[bufferName] = buffer;
  663. this._engine.bindUniformBufferBase(buffer, bufferName);
  664. };
  665. Effect.prototype.bindUniformBlock = function (blockName, index) {
  666. this._engine.bindUniformBlock(this._program, blockName, index);
  667. };
  668. Effect.prototype.setInt = function (uniformName, value) {
  669. var cache = this._valueCache[uniformName];
  670. if (cache !== undefined && cache === value)
  671. return this;
  672. this._valueCache[uniformName] = value;
  673. this._engine.setInt(this.getUniform(uniformName), value);
  674. return this;
  675. };
  676. Effect.prototype.setIntArray = function (uniformName, array) {
  677. this._valueCache[uniformName] = null;
  678. this._engine.setIntArray(this.getUniform(uniformName), array);
  679. return this;
  680. };
  681. Effect.prototype.setIntArray2 = function (uniformName, array) {
  682. this._valueCache[uniformName] = null;
  683. this._engine.setIntArray2(this.getUniform(uniformName), array);
  684. return this;
  685. };
  686. Effect.prototype.setIntArray3 = function (uniformName, array) {
  687. this._valueCache[uniformName] = null;
  688. this._engine.setIntArray3(this.getUniform(uniformName), array);
  689. return this;
  690. };
  691. Effect.prototype.setIntArray4 = function (uniformName, array) {
  692. this._valueCache[uniformName] = null;
  693. this._engine.setIntArray4(this.getUniform(uniformName), array);
  694. return this;
  695. };
  696. Effect.prototype.setFloatArray = function (uniformName, array) {
  697. this._valueCache[uniformName] = null;
  698. this._engine.setFloatArray(this.getUniform(uniformName), array);
  699. return this;
  700. };
  701. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  702. this._valueCache[uniformName] = null;
  703. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  704. return this;
  705. };
  706. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  707. this._valueCache[uniformName] = null;
  708. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  709. return this;
  710. };
  711. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  712. this._valueCache[uniformName] = null;
  713. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  714. return this;
  715. };
  716. Effect.prototype.setArray = function (uniformName, array) {
  717. this._valueCache[uniformName] = null;
  718. this._engine.setArray(this.getUniform(uniformName), array);
  719. return this;
  720. };
  721. Effect.prototype.setArray2 = function (uniformName, array) {
  722. this._valueCache[uniformName] = null;
  723. this._engine.setArray2(this.getUniform(uniformName), array);
  724. return this;
  725. };
  726. Effect.prototype.setArray3 = function (uniformName, array) {
  727. this._valueCache[uniformName] = null;
  728. this._engine.setArray3(this.getUniform(uniformName), array);
  729. return this;
  730. };
  731. Effect.prototype.setArray4 = function (uniformName, array) {
  732. this._valueCache[uniformName] = null;
  733. this._engine.setArray4(this.getUniform(uniformName), array);
  734. return this;
  735. };
  736. Effect.prototype.setMatrices = function (uniformName, matrices) {
  737. if (!matrices) {
  738. return this;
  739. }
  740. this._valueCache[uniformName] = null;
  741. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  742. return this;
  743. };
  744. Effect.prototype.setMatrix = function (uniformName, matrix) {
  745. if (this._cacheMatrix(uniformName, matrix)) {
  746. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  747. }
  748. return this;
  749. };
  750. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  751. this._valueCache[uniformName] = null;
  752. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  753. return this;
  754. };
  755. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  756. this._valueCache[uniformName] = null;
  757. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  758. return this;
  759. };
  760. Effect.prototype.setFloat = function (uniformName, value) {
  761. var cache = this._valueCache[uniformName];
  762. if (cache !== undefined && cache === value)
  763. return this;
  764. this._valueCache[uniformName] = value;
  765. this._engine.setFloat(this.getUniform(uniformName), value);
  766. return this;
  767. };
  768. Effect.prototype.setBool = function (uniformName, bool) {
  769. var cache = this._valueCache[uniformName];
  770. if (cache !== undefined && cache === bool)
  771. return this;
  772. this._valueCache[uniformName] = bool;
  773. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  774. return this;
  775. };
  776. Effect.prototype.setVector2 = function (uniformName, vector2) {
  777. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  778. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  779. }
  780. return this;
  781. };
  782. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  783. if (this._cacheFloat2(uniformName, x, y)) {
  784. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  785. }
  786. return this;
  787. };
  788. Effect.prototype.setVector3 = function (uniformName, vector3) {
  789. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  790. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  791. }
  792. return this;
  793. };
  794. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  795. if (this._cacheFloat3(uniformName, x, y, z)) {
  796. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  797. }
  798. return this;
  799. };
  800. Effect.prototype.setVector4 = function (uniformName, vector4) {
  801. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  802. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  803. }
  804. return this;
  805. };
  806. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  807. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  808. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  809. }
  810. return this;
  811. };
  812. Effect.prototype.setColor3 = function (uniformName, color3) {
  813. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  814. this._engine.setColor3(this.getUniform(uniformName), color3);
  815. }
  816. return this;
  817. };
  818. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  819. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  820. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  821. }
  822. return this;
  823. };
  824. Effect.ResetCache = function () {
  825. Effect._baseCache = {};
  826. };
  827. Effect._uniqueIdSeed = 0;
  828. Effect._baseCache = {};
  829. // Statics
  830. Effect.ShadersStore = {};
  831. Effect.IncludesShadersStore = {};
  832. return Effect;
  833. }());
  834. BABYLON.Effect = Effect;
  835. })(BABYLON || (BABYLON = {}));
  836. //# sourceMappingURL=babylon.effect.js.map
  837. //# sourceMappingURL=babylon.types.js.map
  838. 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}";
  839. 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}";
  840. var BABYLON;
  841. (function (BABYLON) {
  842. var KeyboardEventTypes = /** @class */ (function () {
  843. function KeyboardEventTypes() {
  844. }
  845. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  846. get: function () {
  847. return KeyboardEventTypes._KEYDOWN;
  848. },
  849. enumerable: true,
  850. configurable: true
  851. });
  852. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  853. get: function () {
  854. return KeyboardEventTypes._KEYUP;
  855. },
  856. enumerable: true,
  857. configurable: true
  858. });
  859. KeyboardEventTypes._KEYDOWN = 0x01;
  860. KeyboardEventTypes._KEYUP = 0x02;
  861. return KeyboardEventTypes;
  862. }());
  863. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  864. var KeyboardInfo = /** @class */ (function () {
  865. function KeyboardInfo(type, event) {
  866. this.type = type;
  867. this.event = event;
  868. }
  869. return KeyboardInfo;
  870. }());
  871. BABYLON.KeyboardInfo = KeyboardInfo;
  872. /**
  873. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  874. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  875. */
  876. var KeyboardInfoPre = /** @class */ (function (_super) {
  877. __extends(KeyboardInfoPre, _super);
  878. function KeyboardInfoPre(type, event) {
  879. var _this = _super.call(this, type, event) || this;
  880. _this.skipOnPointerObservable = false;
  881. return _this;
  882. }
  883. return KeyboardInfoPre;
  884. }(KeyboardInfo));
  885. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  886. })(BABYLON || (BABYLON = {}));
  887. //# sourceMappingURL=babylon.keyboardEvents.js.map
  888. var BABYLON;
  889. (function (BABYLON) {
  890. var PointerEventTypes = /** @class */ (function () {
  891. function PointerEventTypes() {
  892. }
  893. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  894. get: function () {
  895. return PointerEventTypes._POINTERDOWN;
  896. },
  897. enumerable: true,
  898. configurable: true
  899. });
  900. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  901. get: function () {
  902. return PointerEventTypes._POINTERUP;
  903. },
  904. enumerable: true,
  905. configurable: true
  906. });
  907. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  908. get: function () {
  909. return PointerEventTypes._POINTERMOVE;
  910. },
  911. enumerable: true,
  912. configurable: true
  913. });
  914. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  915. get: function () {
  916. return PointerEventTypes._POINTERWHEEL;
  917. },
  918. enumerable: true,
  919. configurable: true
  920. });
  921. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  922. get: function () {
  923. return PointerEventTypes._POINTERPICK;
  924. },
  925. enumerable: true,
  926. configurable: true
  927. });
  928. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  929. get: function () {
  930. return PointerEventTypes._POINTERTAP;
  931. },
  932. enumerable: true,
  933. configurable: true
  934. });
  935. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  936. get: function () {
  937. return PointerEventTypes._POINTERDOUBLETAP;
  938. },
  939. enumerable: true,
  940. configurable: true
  941. });
  942. PointerEventTypes._POINTERDOWN = 0x01;
  943. PointerEventTypes._POINTERUP = 0x02;
  944. PointerEventTypes._POINTERMOVE = 0x04;
  945. PointerEventTypes._POINTERWHEEL = 0x08;
  946. PointerEventTypes._POINTERPICK = 0x10;
  947. PointerEventTypes._POINTERTAP = 0x20;
  948. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  949. return PointerEventTypes;
  950. }());
  951. BABYLON.PointerEventTypes = PointerEventTypes;
  952. var PointerInfoBase = /** @class */ (function () {
  953. function PointerInfoBase(type, event) {
  954. this.type = type;
  955. this.event = event;
  956. }
  957. return PointerInfoBase;
  958. }());
  959. BABYLON.PointerInfoBase = PointerInfoBase;
  960. /**
  961. * This class is used to store pointer related info for the onPrePointerObservable event.
  962. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  963. */
  964. var PointerInfoPre = /** @class */ (function (_super) {
  965. __extends(PointerInfoPre, _super);
  966. function PointerInfoPre(type, event, localX, localY) {
  967. var _this = _super.call(this, type, event) || this;
  968. _this.skipOnPointerObservable = false;
  969. _this.localPosition = new BABYLON.Vector2(localX, localY);
  970. return _this;
  971. }
  972. return PointerInfoPre;
  973. }(PointerInfoBase));
  974. BABYLON.PointerInfoPre = PointerInfoPre;
  975. /**
  976. * This type contains all the data related to a pointer event in Babylon.js.
  977. * 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.
  978. */
  979. var PointerInfo = /** @class */ (function (_super) {
  980. __extends(PointerInfo, _super);
  981. function PointerInfo(type, event, pickInfo) {
  982. var _this = _super.call(this, type, event) || this;
  983. _this.pickInfo = pickInfo;
  984. return _this;
  985. }
  986. return PointerInfo;
  987. }(PointerInfoBase));
  988. BABYLON.PointerInfo = PointerInfo;
  989. })(BABYLON || (BABYLON = {}));
  990. //# sourceMappingURL=babylon.pointerEvents.js.map
  991. var BABYLON;
  992. (function (BABYLON) {
  993. BABYLON.ToGammaSpace = 1 / 2.2;
  994. BABYLON.ToLinearSpace = 2.2;
  995. BABYLON.Epsilon = 0.001;
  996. var Color3 = /** @class */ (function () {
  997. /**
  998. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  999. */
  1000. function Color3(r, g, b) {
  1001. if (r === void 0) { r = 0; }
  1002. if (g === void 0) { g = 0; }
  1003. if (b === void 0) { b = 0; }
  1004. this.r = r;
  1005. this.g = g;
  1006. this.b = b;
  1007. }
  1008. /**
  1009. * Returns a string with the Color3 current values.
  1010. */
  1011. Color3.prototype.toString = function () {
  1012. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1013. };
  1014. /**
  1015. * Returns the string "Color3".
  1016. */
  1017. Color3.prototype.getClassName = function () {
  1018. return "Color3";
  1019. };
  1020. /**
  1021. * Returns the Color3 hash code.
  1022. */
  1023. Color3.prototype.getHashCode = function () {
  1024. var hash = this.r || 0;
  1025. hash = (hash * 397) ^ (this.g || 0);
  1026. hash = (hash * 397) ^ (this.b || 0);
  1027. return hash;
  1028. };
  1029. // Operators
  1030. /**
  1031. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  1032. * Returns the Color3.
  1033. */
  1034. Color3.prototype.toArray = function (array, index) {
  1035. if (index === undefined) {
  1036. index = 0;
  1037. }
  1038. array[index] = this.r;
  1039. array[index + 1] = this.g;
  1040. array[index + 2] = this.b;
  1041. return this;
  1042. };
  1043. /**
  1044. * Returns a new Color4 object from the current Color3 and the passed alpha.
  1045. */
  1046. Color3.prototype.toColor4 = function (alpha) {
  1047. if (alpha === void 0) { alpha = 1; }
  1048. return new Color4(this.r, this.g, this.b, alpha);
  1049. };
  1050. /**
  1051. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  1052. */
  1053. Color3.prototype.asArray = function () {
  1054. var result = new Array();
  1055. this.toArray(result, 0);
  1056. return result;
  1057. };
  1058. /**
  1059. * Returns the luminance value (float).
  1060. */
  1061. Color3.prototype.toLuminance = function () {
  1062. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1063. };
  1064. /**
  1065. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  1066. * Returns this new object.
  1067. */
  1068. Color3.prototype.multiply = function (otherColor) {
  1069. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1070. };
  1071. /**
  1072. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  1073. * Returns the current Color3.
  1074. */
  1075. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1076. result.r = this.r * otherColor.r;
  1077. result.g = this.g * otherColor.g;
  1078. result.b = this.b * otherColor.b;
  1079. return this;
  1080. };
  1081. /**
  1082. * Boolean : True if the rgb values are equal to the passed ones.
  1083. */
  1084. Color3.prototype.equals = function (otherColor) {
  1085. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1086. };
  1087. /**
  1088. * Boolean : True if the rgb values are equal to the passed ones.
  1089. */
  1090. Color3.prototype.equalsFloats = function (r, g, b) {
  1091. return this.r === r && this.g === g && this.b === b;
  1092. };
  1093. /**
  1094. * Multiplies in place each rgb value by scale.
  1095. * Returns the updated Color3.
  1096. */
  1097. Color3.prototype.scale = function (scale) {
  1098. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1099. };
  1100. /**
  1101. * Multiplies the rgb values by scale and stores the result into "result".
  1102. * Returns the unmodified current Color3.
  1103. */
  1104. Color3.prototype.scaleToRef = function (scale, result) {
  1105. result.r = this.r * scale;
  1106. result.g = this.g * scale;
  1107. result.b = this.b * scale;
  1108. return this;
  1109. };
  1110. /**
  1111. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  1112. */
  1113. Color3.prototype.add = function (otherColor) {
  1114. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1115. };
  1116. /**
  1117. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  1118. * Returns the unmodified current Color3.
  1119. */
  1120. Color3.prototype.addToRef = function (otherColor, result) {
  1121. result.r = this.r + otherColor.r;
  1122. result.g = this.g + otherColor.g;
  1123. result.b = this.b + otherColor.b;
  1124. return this;
  1125. };
  1126. /**
  1127. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  1128. */
  1129. Color3.prototype.subtract = function (otherColor) {
  1130. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1131. };
  1132. /**
  1133. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  1134. * Returns the unmodified current Color3.
  1135. */
  1136. Color3.prototype.subtractToRef = function (otherColor, result) {
  1137. result.r = this.r - otherColor.r;
  1138. result.g = this.g - otherColor.g;
  1139. result.b = this.b - otherColor.b;
  1140. return this;
  1141. };
  1142. /**
  1143. * Returns a new Color3 copied the current one.
  1144. */
  1145. Color3.prototype.clone = function () {
  1146. return new Color3(this.r, this.g, this.b);
  1147. };
  1148. /**
  1149. * Copies the rgb values from the source in the current Color3.
  1150. * Returns the updated Color3.
  1151. */
  1152. Color3.prototype.copyFrom = function (source) {
  1153. this.r = source.r;
  1154. this.g = source.g;
  1155. this.b = source.b;
  1156. return this;
  1157. };
  1158. /**
  1159. * Updates the Color3 rgb values from the passed floats.
  1160. * Returns the Color3.
  1161. */
  1162. Color3.prototype.copyFromFloats = function (r, g, b) {
  1163. this.r = r;
  1164. this.g = g;
  1165. this.b = b;
  1166. return this;
  1167. };
  1168. /**
  1169. * Updates the Color3 rgb values from the passed floats.
  1170. * Returns the Color3.
  1171. */
  1172. Color3.prototype.set = function (r, g, b) {
  1173. return this.copyFromFloats(r, g, b);
  1174. };
  1175. /**
  1176. * Returns the Color3 hexadecimal code as a string.
  1177. */
  1178. Color3.prototype.toHexString = function () {
  1179. var intR = (this.r * 255) | 0;
  1180. var intG = (this.g * 255) | 0;
  1181. var intB = (this.b * 255) | 0;
  1182. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1183. };
  1184. /**
  1185. * Returns a new Color3 converted to linear space.
  1186. */
  1187. Color3.prototype.toLinearSpace = function () {
  1188. var convertedColor = new Color3();
  1189. this.toLinearSpaceToRef(convertedColor);
  1190. return convertedColor;
  1191. };
  1192. /**
  1193. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  1194. * Returns the unmodified Color3.
  1195. */
  1196. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1197. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1198. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1199. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1200. return this;
  1201. };
  1202. /**
  1203. * Returns a new Color3 converted to gamma space.
  1204. */
  1205. Color3.prototype.toGammaSpace = function () {
  1206. var convertedColor = new Color3();
  1207. this.toGammaSpaceToRef(convertedColor);
  1208. return convertedColor;
  1209. };
  1210. /**
  1211. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  1212. * Returns the unmodified Color3.
  1213. */
  1214. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1215. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1216. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1217. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1218. return this;
  1219. };
  1220. // Statics
  1221. /**
  1222. * Creates a new Color3 from the string containing valid hexadecimal values.
  1223. */
  1224. Color3.FromHexString = function (hex) {
  1225. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1226. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1227. return new Color3(0, 0, 0);
  1228. }
  1229. var r = parseInt(hex.substring(1, 3), 16);
  1230. var g = parseInt(hex.substring(3, 5), 16);
  1231. var b = parseInt(hex.substring(5, 7), 16);
  1232. return Color3.FromInts(r, g, b);
  1233. };
  1234. /**
  1235. * Creates a new Vector3 from the startind index of the passed array.
  1236. */
  1237. Color3.FromArray = function (array, offset) {
  1238. if (offset === void 0) { offset = 0; }
  1239. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1240. };
  1241. /**
  1242. * Creates a new Color3 from integer values ( < 256).
  1243. */
  1244. Color3.FromInts = function (r, g, b) {
  1245. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1246. };
  1247. /**
  1248. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  1249. */
  1250. Color3.Lerp = function (start, end, amount) {
  1251. var r = start.r + ((end.r - start.r) * amount);
  1252. var g = start.g + ((end.g - start.g) * amount);
  1253. var b = start.b + ((end.b - start.b) * amount);
  1254. return new Color3(r, g, b);
  1255. };
  1256. Color3.Red = function () { return new Color3(1, 0, 0); };
  1257. Color3.Green = function () { return new Color3(0, 1, 0); };
  1258. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1259. Color3.Black = function () { return new Color3(0, 0, 0); };
  1260. Color3.White = function () { return new Color3(1, 1, 1); };
  1261. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1262. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1263. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1264. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1265. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1266. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1267. return Color3;
  1268. }());
  1269. BABYLON.Color3 = Color3;
  1270. var Color4 = /** @class */ (function () {
  1271. /**
  1272. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  1273. */
  1274. function Color4(r, g, b, a) {
  1275. if (r === void 0) { r = 0; }
  1276. if (g === void 0) { g = 0; }
  1277. if (b === void 0) { b = 0; }
  1278. if (a === void 0) { a = 1; }
  1279. this.r = r;
  1280. this.g = g;
  1281. this.b = b;
  1282. this.a = a;
  1283. }
  1284. // Operators
  1285. /**
  1286. * Adds in place the passed Color4 values to the current Color4.
  1287. * Returns the updated Color4.
  1288. */
  1289. Color4.prototype.addInPlace = function (right) {
  1290. this.r += right.r;
  1291. this.g += right.g;
  1292. this.b += right.b;
  1293. this.a += right.a;
  1294. return this;
  1295. };
  1296. /**
  1297. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  1298. */
  1299. Color4.prototype.asArray = function () {
  1300. var result = new Array();
  1301. this.toArray(result, 0);
  1302. return result;
  1303. };
  1304. /**
  1305. * Stores from the starting index in the passed array the Color4 successive values.
  1306. * Returns the Color4.
  1307. */
  1308. Color4.prototype.toArray = function (array, index) {
  1309. if (index === undefined) {
  1310. index = 0;
  1311. }
  1312. array[index] = this.r;
  1313. array[index + 1] = this.g;
  1314. array[index + 2] = this.b;
  1315. array[index + 3] = this.a;
  1316. return this;
  1317. };
  1318. /**
  1319. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  1320. */
  1321. Color4.prototype.add = function (right) {
  1322. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1323. };
  1324. /**
  1325. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  1326. */
  1327. Color4.prototype.subtract = function (right) {
  1328. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1329. };
  1330. /**
  1331. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  1332. * Returns the Color4.
  1333. */
  1334. Color4.prototype.subtractToRef = function (right, result) {
  1335. result.r = this.r - right.r;
  1336. result.g = this.g - right.g;
  1337. result.b = this.b - right.b;
  1338. result.a = this.a - right.a;
  1339. return this;
  1340. };
  1341. /**
  1342. * Creates a new Color4 with the current Color4 values multiplied by scale.
  1343. */
  1344. Color4.prototype.scale = function (scale) {
  1345. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1346. };
  1347. /**
  1348. * Multiplies the current Color4 values by scale and stores the result in "result".
  1349. * Returns the Color4.
  1350. */
  1351. Color4.prototype.scaleToRef = function (scale, result) {
  1352. result.r = this.r * scale;
  1353. result.g = this.g * scale;
  1354. result.b = this.b * scale;
  1355. result.a = this.a * scale;
  1356. return this;
  1357. };
  1358. /**
  1359. * Multipy an RGBA Color4 value by another and return a new Color4 object
  1360. * @param color The Color4 (RGBA) value to multiply by
  1361. * @returns A new Color4.
  1362. */
  1363. Color4.prototype.multiply = function (color) {
  1364. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1365. };
  1366. /**
  1367. * Multipy an RGBA Color4 value by another and push the result in a reference value
  1368. * @param color The Color4 (RGBA) value to multiply by
  1369. * @param result The Color4 (RGBA) to fill the result in
  1370. * @returns the result Color4.
  1371. */
  1372. Color4.prototype.multiplyToRef = function (color, result) {
  1373. result.r = this.r * color.r;
  1374. result.g = this.g * color.g;
  1375. result.b = this.b * color.b;
  1376. result.a = this.a * color.a;
  1377. return result;
  1378. };
  1379. /**
  1380. * Returns a string with the Color4 values.
  1381. */
  1382. Color4.prototype.toString = function () {
  1383. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1384. };
  1385. /**
  1386. * Returns the string "Color4"
  1387. */
  1388. Color4.prototype.getClassName = function () {
  1389. return "Color4";
  1390. };
  1391. /**
  1392. * Return the Color4 hash code as a number.
  1393. */
  1394. Color4.prototype.getHashCode = function () {
  1395. var hash = this.r || 0;
  1396. hash = (hash * 397) ^ (this.g || 0);
  1397. hash = (hash * 397) ^ (this.b || 0);
  1398. hash = (hash * 397) ^ (this.a || 0);
  1399. return hash;
  1400. };
  1401. /**
  1402. * Creates a new Color4 copied from the current one.
  1403. */
  1404. Color4.prototype.clone = function () {
  1405. return new Color4(this.r, this.g, this.b, this.a);
  1406. };
  1407. /**
  1408. * Copies the passed Color4 values into the current one.
  1409. * Returns the updated Color4.
  1410. */
  1411. Color4.prototype.copyFrom = function (source) {
  1412. this.r = source.r;
  1413. this.g = source.g;
  1414. this.b = source.b;
  1415. this.a = source.a;
  1416. return this;
  1417. };
  1418. /**
  1419. * Copies the passed float values into the current one.
  1420. * Returns the updated Color4.
  1421. */
  1422. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1423. this.r = r;
  1424. this.g = g;
  1425. this.b = b;
  1426. this.a = a;
  1427. return this;
  1428. };
  1429. /**
  1430. * Copies the passed float values into the current one.
  1431. * Returns the updated Color4.
  1432. */
  1433. Color4.prototype.set = function (r, g, b, a) {
  1434. return this.copyFromFloats(r, g, b, a);
  1435. };
  1436. /**
  1437. * Returns a string containing the hexadecimal Color4 code.
  1438. */
  1439. Color4.prototype.toHexString = function () {
  1440. var intR = (this.r * 255) | 0;
  1441. var intG = (this.g * 255) | 0;
  1442. var intB = (this.b * 255) | 0;
  1443. var intA = (this.a * 255) | 0;
  1444. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1445. };
  1446. /**
  1447. * Returns a new Color4 converted to linear space.
  1448. */
  1449. Color4.prototype.toLinearSpace = function () {
  1450. var convertedColor = new Color4();
  1451. this.toLinearSpaceToRef(convertedColor);
  1452. return convertedColor;
  1453. };
  1454. /**
  1455. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  1456. * Returns the unmodified Color4.
  1457. */
  1458. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  1459. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1460. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1461. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1462. convertedColor.a = this.a;
  1463. return this;
  1464. };
  1465. /**
  1466. * Returns a new Color4 converted to gamma space.
  1467. */
  1468. Color4.prototype.toGammaSpace = function () {
  1469. var convertedColor = new Color4();
  1470. this.toGammaSpaceToRef(convertedColor);
  1471. return convertedColor;
  1472. };
  1473. /**
  1474. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  1475. * Returns the unmodified Color4.
  1476. */
  1477. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  1478. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1479. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1480. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1481. convertedColor.a = this.a;
  1482. return this;
  1483. };
  1484. // Statics
  1485. /**
  1486. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  1487. */
  1488. Color4.FromHexString = function (hex) {
  1489. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  1490. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  1491. return new Color4(0.0, 0.0, 0.0, 0.0);
  1492. }
  1493. var r = parseInt(hex.substring(1, 3), 16);
  1494. var g = parseInt(hex.substring(3, 5), 16);
  1495. var b = parseInt(hex.substring(5, 7), 16);
  1496. var a = parseInt(hex.substring(7, 9), 16);
  1497. return Color4.FromInts(r, g, b, a);
  1498. };
  1499. /**
  1500. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  1501. */
  1502. Color4.Lerp = function (left, right, amount) {
  1503. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  1504. Color4.LerpToRef(left, right, amount, result);
  1505. return result;
  1506. };
  1507. /**
  1508. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  1509. */
  1510. Color4.LerpToRef = function (left, right, amount, result) {
  1511. result.r = left.r + (right.r - left.r) * amount;
  1512. result.g = left.g + (right.g - left.g) * amount;
  1513. result.b = left.b + (right.b - left.b) * amount;
  1514. result.a = left.a + (right.a - left.a) * amount;
  1515. };
  1516. /**
  1517. * Creates a new Color4 from the starting index element of the passed array.
  1518. */
  1519. Color4.FromArray = function (array, offset) {
  1520. if (offset === void 0) { offset = 0; }
  1521. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1522. };
  1523. /**
  1524. * Creates a new Color4 from the passed integers ( < 256 ).
  1525. */
  1526. Color4.FromInts = function (r, g, b, a) {
  1527. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  1528. };
  1529. Color4.CheckColors4 = function (colors, count) {
  1530. // Check if color3 was used
  1531. if (colors.length === count * 3) {
  1532. var colors4 = [];
  1533. for (var index = 0; index < colors.length; index += 3) {
  1534. var newIndex = (index / 3) * 4;
  1535. colors4[newIndex] = colors[index];
  1536. colors4[newIndex + 1] = colors[index + 1];
  1537. colors4[newIndex + 2] = colors[index + 2];
  1538. colors4[newIndex + 3] = 1.0;
  1539. }
  1540. return colors4;
  1541. }
  1542. return colors;
  1543. };
  1544. return Color4;
  1545. }());
  1546. BABYLON.Color4 = Color4;
  1547. var Vector2 = /** @class */ (function () {
  1548. /**
  1549. * Creates a new Vector2 from the passed x and y coordinates.
  1550. */
  1551. function Vector2(x, y) {
  1552. this.x = x;
  1553. this.y = y;
  1554. }
  1555. /**
  1556. * Returns a string with the Vector2 coordinates.
  1557. */
  1558. Vector2.prototype.toString = function () {
  1559. return "{X: " + this.x + " Y:" + this.y + "}";
  1560. };
  1561. /**
  1562. * Returns the string "Vector2"
  1563. */
  1564. Vector2.prototype.getClassName = function () {
  1565. return "Vector2";
  1566. };
  1567. /**
  1568. * Returns the Vector2 hash code as a number.
  1569. */
  1570. Vector2.prototype.getHashCode = function () {
  1571. var hash = this.x || 0;
  1572. hash = (hash * 397) ^ (this.y || 0);
  1573. return hash;
  1574. };
  1575. // Operators
  1576. /**
  1577. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  1578. * Returns the Vector2.
  1579. */
  1580. Vector2.prototype.toArray = function (array, index) {
  1581. if (index === void 0) { index = 0; }
  1582. array[index] = this.x;
  1583. array[index + 1] = this.y;
  1584. return this;
  1585. };
  1586. /**
  1587. * Returns a new array with 2 elements : the Vector2 coordinates.
  1588. */
  1589. Vector2.prototype.asArray = function () {
  1590. var result = new Array();
  1591. this.toArray(result, 0);
  1592. return result;
  1593. };
  1594. /**
  1595. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  1596. * Returns the updated Vector2.
  1597. */
  1598. Vector2.prototype.copyFrom = function (source) {
  1599. this.x = source.x;
  1600. this.y = source.y;
  1601. return this;
  1602. };
  1603. /**
  1604. * Sets the Vector2 coordinates with the passed floats.
  1605. * Returns the updated Vector2.
  1606. */
  1607. Vector2.prototype.copyFromFloats = function (x, y) {
  1608. this.x = x;
  1609. this.y = y;
  1610. return this;
  1611. };
  1612. /**
  1613. * Sets the Vector2 coordinates with the passed floats.
  1614. * Returns the updated Vector2.
  1615. */
  1616. Vector2.prototype.set = function (x, y) {
  1617. return this.copyFromFloats(x, y);
  1618. };
  1619. /**
  1620. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  1621. */
  1622. Vector2.prototype.add = function (otherVector) {
  1623. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1624. };
  1625. /**
  1626. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  1627. * Returns the Vector2.
  1628. */
  1629. Vector2.prototype.addToRef = function (otherVector, result) {
  1630. result.x = this.x + otherVector.x;
  1631. result.y = this.y + otherVector.y;
  1632. return this;
  1633. };
  1634. /**
  1635. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  1636. * Returns the updated Vector2.
  1637. */
  1638. Vector2.prototype.addInPlace = function (otherVector) {
  1639. this.x += otherVector.x;
  1640. this.y += otherVector.y;
  1641. return this;
  1642. };
  1643. /**
  1644. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  1645. */
  1646. Vector2.prototype.addVector3 = function (otherVector) {
  1647. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1648. };
  1649. /**
  1650. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  1651. */
  1652. Vector2.prototype.subtract = function (otherVector) {
  1653. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  1654. };
  1655. /**
  1656. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  1657. * Returns the Vector2.
  1658. */
  1659. Vector2.prototype.subtractToRef = function (otherVector, result) {
  1660. result.x = this.x - otherVector.x;
  1661. result.y = this.y - otherVector.y;
  1662. return this;
  1663. };
  1664. /**
  1665. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  1666. * Returns the updated Vector2.
  1667. */
  1668. Vector2.prototype.subtractInPlace = function (otherVector) {
  1669. this.x -= otherVector.x;
  1670. this.y -= otherVector.y;
  1671. return this;
  1672. };
  1673. /**
  1674. * Multiplies in place the current Vector2 coordinates by the passed ones.
  1675. * Returns the updated Vector2.
  1676. */
  1677. Vector2.prototype.multiplyInPlace = function (otherVector) {
  1678. this.x *= otherVector.x;
  1679. this.y *= otherVector.y;
  1680. return this;
  1681. };
  1682. /**
  1683. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  1684. */
  1685. Vector2.prototype.multiply = function (otherVector) {
  1686. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  1687. };
  1688. /**
  1689. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  1690. * Returns the Vector2.
  1691. */
  1692. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  1693. result.x = this.x * otherVector.x;
  1694. result.y = this.y * otherVector.y;
  1695. return this;
  1696. };
  1697. /**
  1698. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  1699. */
  1700. Vector2.prototype.multiplyByFloats = function (x, y) {
  1701. return new Vector2(this.x * x, this.y * y);
  1702. };
  1703. /**
  1704. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  1705. */
  1706. Vector2.prototype.divide = function (otherVector) {
  1707. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  1708. };
  1709. /**
  1710. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  1711. * Returns the Vector2.
  1712. */
  1713. Vector2.prototype.divideToRef = function (otherVector, result) {
  1714. result.x = this.x / otherVector.x;
  1715. result.y = this.y / otherVector.y;
  1716. return this;
  1717. };
  1718. /**
  1719. * Returns a new Vector2 with current Vector2 negated coordinates.
  1720. */
  1721. Vector2.prototype.negate = function () {
  1722. return new Vector2(-this.x, -this.y);
  1723. };
  1724. /**
  1725. * Multiply the Vector2 coordinates by scale.
  1726. * Returns the updated Vector2.
  1727. */
  1728. Vector2.prototype.scaleInPlace = function (scale) {
  1729. this.x *= scale;
  1730. this.y *= scale;
  1731. return this;
  1732. };
  1733. /**
  1734. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  1735. */
  1736. Vector2.prototype.scale = function (scale) {
  1737. return new Vector2(this.x * scale, this.y * scale);
  1738. };
  1739. /**
  1740. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  1741. */
  1742. Vector2.prototype.equals = function (otherVector) {
  1743. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  1744. };
  1745. /**
  1746. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  1747. */
  1748. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1749. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1750. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  1751. };
  1752. // Properties
  1753. /**
  1754. * Returns the vector length (float).
  1755. */
  1756. Vector2.prototype.length = function () {
  1757. return Math.sqrt(this.x * this.x + this.y * this.y);
  1758. };
  1759. /**
  1760. * Returns the vector squared length (float);
  1761. */
  1762. Vector2.prototype.lengthSquared = function () {
  1763. return (this.x * this.x + this.y * this.y);
  1764. };
  1765. // Methods
  1766. /**
  1767. * Normalize the vector.
  1768. * Returns the updated Vector2.
  1769. */
  1770. Vector2.prototype.normalize = function () {
  1771. var len = this.length();
  1772. if (len === 0)
  1773. return this;
  1774. var num = 1.0 / len;
  1775. this.x *= num;
  1776. this.y *= num;
  1777. return this;
  1778. };
  1779. /**
  1780. * Returns a new Vector2 copied from the Vector2.
  1781. */
  1782. Vector2.prototype.clone = function () {
  1783. return new Vector2(this.x, this.y);
  1784. };
  1785. // Statics
  1786. /**
  1787. * Returns a new Vector2(0, 0)
  1788. */
  1789. Vector2.Zero = function () {
  1790. return new Vector2(0, 0);
  1791. };
  1792. /**
  1793. * Returns a new Vector2(1, 1)
  1794. */
  1795. Vector2.One = function () {
  1796. return new Vector2(1, 1);
  1797. };
  1798. /**
  1799. * Returns a new Vector2 set from the passed index element of the passed array.
  1800. */
  1801. Vector2.FromArray = function (array, offset) {
  1802. if (offset === void 0) { offset = 0; }
  1803. return new Vector2(array[offset], array[offset + 1]);
  1804. };
  1805. /**
  1806. * Sets "result" from the passed index element of the passed array.
  1807. */
  1808. Vector2.FromArrayToRef = function (array, offset, result) {
  1809. result.x = array[offset];
  1810. result.y = array[offset + 1];
  1811. };
  1812. /**
  1813. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  1814. */
  1815. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  1816. var squared = amount * amount;
  1817. var cubed = amount * squared;
  1818. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1819. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1820. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1821. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1822. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1823. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1824. return new Vector2(x, y);
  1825. };
  1826. /**
  1827. * 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".
  1828. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1829. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1830. */
  1831. Vector2.Clamp = function (value, min, max) {
  1832. var x = value.x;
  1833. x = (x > max.x) ? max.x : x;
  1834. x = (x < min.x) ? min.x : x;
  1835. var y = value.y;
  1836. y = (y > max.y) ? max.y : y;
  1837. y = (y < min.y) ? min.y : y;
  1838. return new Vector2(x, y);
  1839. };
  1840. /**
  1841. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1842. */
  1843. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1844. var squared = amount * amount;
  1845. var cubed = amount * squared;
  1846. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1847. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1848. var part3 = (cubed - (2.0 * squared)) + amount;
  1849. var part4 = cubed - squared;
  1850. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1851. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1852. return new Vector2(x, y);
  1853. };
  1854. /**
  1855. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1856. */
  1857. Vector2.Lerp = function (start, end, amount) {
  1858. var x = start.x + ((end.x - start.x) * amount);
  1859. var y = start.y + ((end.y - start.y) * amount);
  1860. return new Vector2(x, y);
  1861. };
  1862. /**
  1863. * Returns the dot product (float) of the vector "left" and the vector "right".
  1864. */
  1865. Vector2.Dot = function (left, right) {
  1866. return left.x * right.x + left.y * right.y;
  1867. };
  1868. /**
  1869. * Returns a new Vector2 equal to the normalized passed vector.
  1870. */
  1871. Vector2.Normalize = function (vector) {
  1872. var newVector = vector.clone();
  1873. newVector.normalize();
  1874. return newVector;
  1875. };
  1876. /**
  1877. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1878. */
  1879. Vector2.Minimize = function (left, right) {
  1880. var x = (left.x < right.x) ? left.x : right.x;
  1881. var y = (left.y < right.y) ? left.y : right.y;
  1882. return new Vector2(x, y);
  1883. };
  1884. /**
  1885. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1886. */
  1887. Vector2.Maximize = function (left, right) {
  1888. var x = (left.x > right.x) ? left.x : right.x;
  1889. var y = (left.y > right.y) ? left.y : right.y;
  1890. return new Vector2(x, y);
  1891. };
  1892. /**
  1893. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1894. */
  1895. Vector2.Transform = function (vector, transformation) {
  1896. var r = Vector2.Zero();
  1897. Vector2.TransformToRef(vector, transformation, r);
  1898. return r;
  1899. };
  1900. /**
  1901. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1902. */
  1903. Vector2.TransformToRef = function (vector, transformation, result) {
  1904. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1905. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1906. result.x = x;
  1907. result.y = y;
  1908. };
  1909. /**
  1910. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1911. */
  1912. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1913. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1914. var sign = a < 0 ? -1 : 1;
  1915. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1916. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1917. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1918. };
  1919. /**
  1920. * Returns the distance (float) between the vectors "value1" and "value2".
  1921. */
  1922. Vector2.Distance = function (value1, value2) {
  1923. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1924. };
  1925. /**
  1926. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1927. */
  1928. Vector2.DistanceSquared = function (value1, value2) {
  1929. var x = value1.x - value2.x;
  1930. var y = value1.y - value2.y;
  1931. return (x * x) + (y * y);
  1932. };
  1933. /**
  1934. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1935. */
  1936. Vector2.Center = function (value1, value2) {
  1937. var center = value1.add(value2);
  1938. center.scaleInPlace(0.5);
  1939. return center;
  1940. };
  1941. /**
  1942. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1943. */
  1944. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1945. var l2 = Vector2.DistanceSquared(segA, segB);
  1946. if (l2 === 0.0) {
  1947. return Vector2.Distance(p, segA);
  1948. }
  1949. var v = segB.subtract(segA);
  1950. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1951. var proj = segA.add(v.multiplyByFloats(t, t));
  1952. return Vector2.Distance(p, proj);
  1953. };
  1954. return Vector2;
  1955. }());
  1956. BABYLON.Vector2 = Vector2;
  1957. var Vector3 = /** @class */ (function () {
  1958. /**
  1959. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1960. * A Vector3 is the main object used in 3D geometry.
  1961. * It can represent etiher the coordinates of a point the space, either a direction.
  1962. */
  1963. function Vector3(x, y, z) {
  1964. this.x = x;
  1965. this.y = y;
  1966. this.z = z;
  1967. }
  1968. /**
  1969. * Returns a string with the Vector3 coordinates.
  1970. */
  1971. Vector3.prototype.toString = function () {
  1972. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1973. };
  1974. /**
  1975. * Returns the string "Vector3"
  1976. */
  1977. Vector3.prototype.getClassName = function () {
  1978. return "Vector3";
  1979. };
  1980. /**
  1981. * Returns the Vector hash code.
  1982. */
  1983. Vector3.prototype.getHashCode = function () {
  1984. var hash = this.x || 0;
  1985. hash = (hash * 397) ^ (this.y || 0);
  1986. hash = (hash * 397) ^ (this.z || 0);
  1987. return hash;
  1988. };
  1989. // Operators
  1990. /**
  1991. * Returns a new array with three elements : the coordinates the Vector3.
  1992. */
  1993. Vector3.prototype.asArray = function () {
  1994. var result = [];
  1995. this.toArray(result, 0);
  1996. return result;
  1997. };
  1998. /**
  1999. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  2000. * Returns the Vector3.
  2001. */
  2002. Vector3.prototype.toArray = function (array, index) {
  2003. if (index === void 0) { index = 0; }
  2004. array[index] = this.x;
  2005. array[index + 1] = this.y;
  2006. array[index + 2] = this.z;
  2007. return this;
  2008. };
  2009. /**
  2010. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  2011. */
  2012. Vector3.prototype.toQuaternion = function () {
  2013. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2014. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2015. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2016. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2017. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2018. var cosy = Math.cos(this.y * 0.5);
  2019. var siny = Math.sin(this.y * 0.5);
  2020. result.x = coszMinusx * siny;
  2021. result.y = -sinzMinusx * siny;
  2022. result.z = sinxPlusz * cosy;
  2023. result.w = cosxPlusz * cosy;
  2024. return result;
  2025. };
  2026. /**
  2027. * Adds the passed vector to the current Vector3.
  2028. * Returns the updated Vector3.
  2029. */
  2030. Vector3.prototype.addInPlace = function (otherVector) {
  2031. this.x += otherVector.x;
  2032. this.y += otherVector.y;
  2033. this.z += otherVector.z;
  2034. return this;
  2035. };
  2036. /**
  2037. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  2038. */
  2039. Vector3.prototype.add = function (otherVector) {
  2040. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2041. };
  2042. /**
  2043. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  2044. * Returns the current Vector3.
  2045. */
  2046. Vector3.prototype.addToRef = function (otherVector, result) {
  2047. result.x = this.x + otherVector.x;
  2048. result.y = this.y + otherVector.y;
  2049. result.z = this.z + otherVector.z;
  2050. return this;
  2051. };
  2052. /**
  2053. * Subtract the passed vector from the current Vector3.
  2054. * Returns the updated Vector3.
  2055. */
  2056. Vector3.prototype.subtractInPlace = function (otherVector) {
  2057. this.x -= otherVector.x;
  2058. this.y -= otherVector.y;
  2059. this.z -= otherVector.z;
  2060. return this;
  2061. };
  2062. /**
  2063. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  2064. */
  2065. Vector3.prototype.subtract = function (otherVector) {
  2066. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2067. };
  2068. /**
  2069. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2070. * Returns the current Vector3.
  2071. */
  2072. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2073. result.x = this.x - otherVector.x;
  2074. result.y = this.y - otherVector.y;
  2075. result.z = this.z - otherVector.z;
  2076. return this;
  2077. };
  2078. /**
  2079. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  2080. */
  2081. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2082. return new Vector3(this.x - x, this.y - y, this.z - z);
  2083. };
  2084. /**
  2085. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  2086. * Returns the current Vector3.
  2087. */
  2088. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2089. result.x = this.x - x;
  2090. result.y = this.y - y;
  2091. result.z = this.z - z;
  2092. return this;
  2093. };
  2094. /**
  2095. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  2096. */
  2097. Vector3.prototype.negate = function () {
  2098. return new Vector3(-this.x, -this.y, -this.z);
  2099. };
  2100. /**
  2101. * Multiplies the Vector3 coordinates by the float "scale".
  2102. * Returns the updated Vector3.
  2103. */
  2104. Vector3.prototype.scaleInPlace = function (scale) {
  2105. this.x *= scale;
  2106. this.y *= scale;
  2107. this.z *= scale;
  2108. return this;
  2109. };
  2110. /**
  2111. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  2112. */
  2113. Vector3.prototype.scale = function (scale) {
  2114. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2115. };
  2116. /**
  2117. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  2118. * Returns the current Vector3.
  2119. */
  2120. Vector3.prototype.scaleToRef = function (scale, result) {
  2121. result.x = this.x * scale;
  2122. result.y = this.y * scale;
  2123. result.z = this.z * scale;
  2124. return this;
  2125. };
  2126. /**
  2127. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  2128. */
  2129. Vector3.prototype.equals = function (otherVector) {
  2130. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2131. };
  2132. /**
  2133. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  2134. */
  2135. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2136. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2137. 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);
  2138. };
  2139. /**
  2140. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  2141. */
  2142. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2143. return this.x === x && this.y === y && this.z === z;
  2144. };
  2145. /**
  2146. * Muliplies the current Vector3 coordinates by the passed ones.
  2147. * Returns the updated Vector3.
  2148. */
  2149. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2150. this.x *= otherVector.x;
  2151. this.y *= otherVector.y;
  2152. this.z *= otherVector.z;
  2153. return this;
  2154. };
  2155. /**
  2156. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  2157. */
  2158. Vector3.prototype.multiply = function (otherVector) {
  2159. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2160. };
  2161. /**
  2162. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  2163. * Returns the current Vector3.
  2164. */
  2165. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2166. result.x = this.x * otherVector.x;
  2167. result.y = this.y * otherVector.y;
  2168. result.z = this.z * otherVector.z;
  2169. return this;
  2170. };
  2171. /**
  2172. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  2173. */
  2174. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2175. return new Vector3(this.x * x, this.y * y, this.z * z);
  2176. };
  2177. /**
  2178. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  2179. */
  2180. Vector3.prototype.divide = function (otherVector) {
  2181. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2182. };
  2183. /**
  2184. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  2185. * Returns the current Vector3.
  2186. */
  2187. Vector3.prototype.divideToRef = function (otherVector, result) {
  2188. result.x = this.x / otherVector.x;
  2189. result.y = this.y / otherVector.y;
  2190. result.z = this.z / otherVector.z;
  2191. return this;
  2192. };
  2193. /**
  2194. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  2195. * Returns the updated Vector3.
  2196. */
  2197. Vector3.prototype.MinimizeInPlace = function (other) {
  2198. if (other.x < this.x)
  2199. this.x = other.x;
  2200. if (other.y < this.y)
  2201. this.y = other.y;
  2202. if (other.z < this.z)
  2203. this.z = other.z;
  2204. return this;
  2205. };
  2206. /**
  2207. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2208. * Returns the updated Vector3.
  2209. */
  2210. Vector3.prototype.MaximizeInPlace = function (other) {
  2211. if (other.x > this.x)
  2212. this.x = other.x;
  2213. if (other.y > this.y)
  2214. this.y = other.y;
  2215. if (other.z > this.z)
  2216. this.z = other.z;
  2217. return this;
  2218. };
  2219. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2220. /**
  2221. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  2222. */
  2223. get: function () {
  2224. var absX = Math.abs(this.x);
  2225. var absY = Math.abs(this.y);
  2226. if (absX !== absY) {
  2227. return true;
  2228. }
  2229. var absZ = Math.abs(this.z);
  2230. if (absX !== absZ) {
  2231. return true;
  2232. }
  2233. if (absY !== absZ) {
  2234. return true;
  2235. }
  2236. return false;
  2237. },
  2238. enumerable: true,
  2239. configurable: true
  2240. });
  2241. // Properties
  2242. /**
  2243. * Returns the length of the Vector3 (float).
  2244. */
  2245. Vector3.prototype.length = function () {
  2246. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2247. };
  2248. /**
  2249. * Returns the squared length of the Vector3 (float).
  2250. */
  2251. Vector3.prototype.lengthSquared = function () {
  2252. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2253. };
  2254. /**
  2255. * Normalize the current Vector3.
  2256. * Returns the updated Vector3.
  2257. * /!\ In place operation.
  2258. */
  2259. Vector3.prototype.normalize = function () {
  2260. var len = this.length();
  2261. if (len === 0 || len === 1.0)
  2262. return this;
  2263. var num = 1.0 / len;
  2264. this.x *= num;
  2265. this.y *= num;
  2266. this.z *= num;
  2267. return this;
  2268. };
  2269. /**
  2270. * Normalize the current Vector3 to a new vector.
  2271. * @returns the new Vector3.
  2272. */
  2273. Vector3.prototype.normalizeToNew = function () {
  2274. var normalized = new Vector3(0, 0, 0);
  2275. this.normalizeToRef(normalized);
  2276. return normalized;
  2277. };
  2278. /**
  2279. * Normalize the current Vector3 to the reference.
  2280. * @param the reference to update.
  2281. * @returns the updated Vector3.
  2282. */
  2283. Vector3.prototype.normalizeToRef = function (reference) {
  2284. var len = this.length();
  2285. if (len === 0 || len === 1.0) {
  2286. reference.set(this.x, this.y, this.z);
  2287. return reference;
  2288. }
  2289. var scale = 1.0 / len;
  2290. this.scaleToRef(scale, reference);
  2291. return reference;
  2292. };
  2293. /**
  2294. * Returns a new Vector3 copied from the current Vector3.
  2295. */
  2296. Vector3.prototype.clone = function () {
  2297. return new Vector3(this.x, this.y, this.z);
  2298. };
  2299. /**
  2300. * Copies the passed vector coordinates to the current Vector3 ones.
  2301. * Returns the updated Vector3.
  2302. */
  2303. Vector3.prototype.copyFrom = function (source) {
  2304. this.x = source.x;
  2305. this.y = source.y;
  2306. this.z = source.z;
  2307. return this;
  2308. };
  2309. /**
  2310. * Copies the passed floats to the current Vector3 coordinates.
  2311. * Returns the updated Vector3.
  2312. */
  2313. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2314. this.x = x;
  2315. this.y = y;
  2316. this.z = z;
  2317. return this;
  2318. };
  2319. /**
  2320. * Copies the passed floats to the current Vector3 coordinates.
  2321. * Returns the updated Vector3.
  2322. */
  2323. Vector3.prototype.set = function (x, y, z) {
  2324. return this.copyFromFloats(x, y, z);
  2325. };
  2326. // Statics
  2327. /**
  2328. *
  2329. */
  2330. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  2331. var d0 = Vector3.Dot(vector0, axis) - size;
  2332. var d1 = Vector3.Dot(vector1, axis) - size;
  2333. var s = d0 / (d0 - d1);
  2334. return s;
  2335. };
  2336. /**
  2337. * Returns a new Vector3 set from the index "offset" of the passed array.
  2338. */
  2339. Vector3.FromArray = function (array, offset) {
  2340. if (!offset) {
  2341. offset = 0;
  2342. }
  2343. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  2344. };
  2345. /**
  2346. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  2347. * This function is deprecated. Use FromArray instead.
  2348. */
  2349. Vector3.FromFloatArray = function (array, offset) {
  2350. return Vector3.FromArray(array, offset);
  2351. };
  2352. /**
  2353. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  2354. */
  2355. Vector3.FromArrayToRef = function (array, offset, result) {
  2356. result.x = array[offset];
  2357. result.y = array[offset + 1];
  2358. result.z = array[offset + 2];
  2359. };
  2360. /**
  2361. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  2362. * This function is deprecated. Use FromArrayToRef instead.
  2363. */
  2364. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  2365. return Vector3.FromArrayToRef(array, offset, result);
  2366. };
  2367. /**
  2368. * Sets the passed vector "result" with the passed floats.
  2369. */
  2370. Vector3.FromFloatsToRef = function (x, y, z, result) {
  2371. result.x = x;
  2372. result.y = y;
  2373. result.z = z;
  2374. };
  2375. /**
  2376. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  2377. */
  2378. Vector3.Zero = function () {
  2379. return new Vector3(0.0, 0.0, 0.0);
  2380. };
  2381. /**
  2382. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  2383. */
  2384. Vector3.One = function () {
  2385. return new Vector3(1.0, 1.0, 1.0);
  2386. };
  2387. /**
  2388. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  2389. */
  2390. Vector3.Up = function () {
  2391. return new Vector3(0.0, 1.0, 0.0);
  2392. };
  2393. /**
  2394. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  2395. */
  2396. Vector3.Forward = function () {
  2397. return new Vector3(0.0, 0.0, 1.0);
  2398. };
  2399. /**
  2400. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  2401. */
  2402. Vector3.Right = function () {
  2403. return new Vector3(1.0, 0.0, 0.0);
  2404. };
  2405. /**
  2406. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  2407. */
  2408. Vector3.Left = function () {
  2409. return new Vector3(-1.0, 0.0, 0.0);
  2410. };
  2411. /**
  2412. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  2413. * This method computes tranformed coordinates only, not transformed direction vectors.
  2414. */
  2415. Vector3.TransformCoordinates = function (vector, transformation) {
  2416. var result = Vector3.Zero();
  2417. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  2418. return result;
  2419. };
  2420. /**
  2421. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  2422. * This method computes tranformed coordinates only, not transformed direction vectors.
  2423. */
  2424. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  2425. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  2426. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  2427. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  2428. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  2429. result.x = x / w;
  2430. result.y = y / w;
  2431. result.z = z / w;
  2432. };
  2433. /**
  2434. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  2435. * This method computes tranformed coordinates only, not transformed direction vectors.
  2436. */
  2437. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  2438. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  2439. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  2440. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  2441. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  2442. result.x = rx / rw;
  2443. result.y = ry / rw;
  2444. result.z = rz / rw;
  2445. };
  2446. /**
  2447. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  2448. * This methods computes transformed normalized direction vectors only.
  2449. */
  2450. Vector3.TransformNormal = function (vector, transformation) {
  2451. var result = Vector3.Zero();
  2452. Vector3.TransformNormalToRef(vector, transformation, result);
  2453. return result;
  2454. };
  2455. /**
  2456. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2457. * This methods computes transformed normalized direction vectors only.
  2458. */
  2459. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  2460. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2461. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2462. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2463. result.x = x;
  2464. result.y = y;
  2465. result.z = z;
  2466. };
  2467. /**
  2468. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  2469. * This methods computes transformed normalized direction vectors only.
  2470. */
  2471. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  2472. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2473. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2474. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2475. };
  2476. /**
  2477. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  2478. */
  2479. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  2480. var squared = amount * amount;
  2481. var cubed = amount * squared;
  2482. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2483. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2484. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2485. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2486. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2487. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2488. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  2489. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  2490. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  2491. return new Vector3(x, y, z);
  2492. };
  2493. /**
  2494. * 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".
  2495. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  2496. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  2497. */
  2498. Vector3.Clamp = function (value, min, max) {
  2499. var x = value.x;
  2500. x = (x > max.x) ? max.x : x;
  2501. x = (x < min.x) ? min.x : x;
  2502. var y = value.y;
  2503. y = (y > max.y) ? max.y : y;
  2504. y = (y < min.y) ? min.y : y;
  2505. var z = value.z;
  2506. z = (z > max.z) ? max.z : z;
  2507. z = (z < min.z) ? min.z : z;
  2508. return new Vector3(x, y, z);
  2509. };
  2510. /**
  2511. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2512. */
  2513. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2514. var squared = amount * amount;
  2515. var cubed = amount * squared;
  2516. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2517. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2518. var part3 = (cubed - (2.0 * squared)) + amount;
  2519. var part4 = cubed - squared;
  2520. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2521. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2522. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2523. return new Vector3(x, y, z);
  2524. };
  2525. /**
  2526. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  2527. */
  2528. Vector3.Lerp = function (start, end, amount) {
  2529. var result = new Vector3(0, 0, 0);
  2530. Vector3.LerpToRef(start, end, amount, result);
  2531. return result;
  2532. };
  2533. /**
  2534. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  2535. */
  2536. Vector3.LerpToRef = function (start, end, amount, result) {
  2537. result.x = start.x + ((end.x - start.x) * amount);
  2538. result.y = start.y + ((end.y - start.y) * amount);
  2539. result.z = start.z + ((end.z - start.z) * amount);
  2540. };
  2541. /**
  2542. * Returns the dot product (float) between the vectors "left" and "right".
  2543. */
  2544. Vector3.Dot = function (left, right) {
  2545. return (left.x * right.x + left.y * right.y + left.z * right.z);
  2546. };
  2547. /**
  2548. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  2549. * The cross product is then orthogonal to both "left" and "right".
  2550. */
  2551. Vector3.Cross = function (left, right) {
  2552. var result = Vector3.Zero();
  2553. Vector3.CrossToRef(left, right, result);
  2554. return result;
  2555. };
  2556. /**
  2557. * Sets the passed vector "result" with the cross product of "left" and "right".
  2558. * The cross product is then orthogonal to both "left" and "right".
  2559. */
  2560. Vector3.CrossToRef = function (left, right, result) {
  2561. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  2562. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  2563. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  2564. result.copyFrom(MathTmp.Vector3[0]);
  2565. };
  2566. /**
  2567. * Returns a new Vector3 as the normalization of the passed vector.
  2568. */
  2569. Vector3.Normalize = function (vector) {
  2570. var result = Vector3.Zero();
  2571. Vector3.NormalizeToRef(vector, result);
  2572. return result;
  2573. };
  2574. /**
  2575. * Sets the passed vector "result" with the normalization of the passed first vector.
  2576. */
  2577. Vector3.NormalizeToRef = function (vector, result) {
  2578. result.copyFrom(vector);
  2579. result.normalize();
  2580. };
  2581. Vector3.Project = function (vector, world, transform, viewport) {
  2582. var cw = viewport.width;
  2583. var ch = viewport.height;
  2584. var cx = viewport.x;
  2585. var cy = viewport.y;
  2586. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  2587. 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);
  2588. var matrix = MathTmp.Matrix[0];
  2589. world.multiplyToRef(transform, matrix);
  2590. matrix.multiplyToRef(viewportMatrix, matrix);
  2591. return Vector3.TransformCoordinates(vector, matrix);
  2592. };
  2593. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  2594. var matrix = MathTmp.Matrix[0];
  2595. world.multiplyToRef(transform, matrix);
  2596. matrix.invert();
  2597. source.x = source.x / viewportWidth * 2 - 1;
  2598. source.y = -(source.y / viewportHeight * 2 - 1);
  2599. var vector = Vector3.TransformCoordinates(source, matrix);
  2600. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  2601. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2602. vector = vector.scale(1.0 / num);
  2603. }
  2604. return vector;
  2605. };
  2606. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  2607. var result = Vector3.Zero();
  2608. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  2609. return result;
  2610. };
  2611. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  2612. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  2613. };
  2614. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  2615. var matrix = MathTmp.Matrix[0];
  2616. world.multiplyToRef(view, matrix);
  2617. matrix.multiplyToRef(projection, matrix);
  2618. matrix.invert();
  2619. var screenSource = MathTmp.Vector3[0];
  2620. screenSource.x = sourceX / viewportWidth * 2 - 1;
  2621. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  2622. screenSource.z = 2 * sourceZ - 1.0;
  2623. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  2624. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  2625. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2626. result.scaleInPlace(1.0 / num);
  2627. }
  2628. };
  2629. Vector3.Minimize = function (left, right) {
  2630. var min = left.clone();
  2631. min.MinimizeInPlace(right);
  2632. return min;
  2633. };
  2634. Vector3.Maximize = function (left, right) {
  2635. var max = left.clone();
  2636. max.MaximizeInPlace(right);
  2637. return max;
  2638. };
  2639. /**
  2640. * Returns the distance (float) between the vectors "value1" and "value2".
  2641. */
  2642. Vector3.Distance = function (value1, value2) {
  2643. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  2644. };
  2645. /**
  2646. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2647. */
  2648. Vector3.DistanceSquared = function (value1, value2) {
  2649. var x = value1.x - value2.x;
  2650. var y = value1.y - value2.y;
  2651. var z = value1.z - value2.z;
  2652. return (x * x) + (y * y) + (z * z);
  2653. };
  2654. /**
  2655. * Returns a new Vector3 located at the center between "value1" and "value2".
  2656. */
  2657. Vector3.Center = function (value1, value2) {
  2658. var center = value1.add(value2);
  2659. center.scaleInPlace(0.5);
  2660. return center;
  2661. };
  2662. /**
  2663. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  2664. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  2665. * to something in order to rotate it from its local system to the given target system.
  2666. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2667. * Returns a new Vector3.
  2668. */
  2669. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  2670. var rotation = Vector3.Zero();
  2671. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  2672. return rotation;
  2673. };
  2674. /**
  2675. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  2676. */
  2677. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2678. var quat = MathTmp.Quaternion[0];
  2679. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2680. quat.toEulerAnglesToRef(ref);
  2681. };
  2682. return Vector3;
  2683. }());
  2684. BABYLON.Vector3 = Vector3;
  2685. //Vector4 class created for EulerAngle class conversion to Quaternion
  2686. var Vector4 = /** @class */ (function () {
  2687. /**
  2688. * Creates a Vector4 object from the passed floats.
  2689. */
  2690. function Vector4(x, y, z, w) {
  2691. this.x = x;
  2692. this.y = y;
  2693. this.z = z;
  2694. this.w = w;
  2695. }
  2696. /**
  2697. * Returns the string with the Vector4 coordinates.
  2698. */
  2699. Vector4.prototype.toString = function () {
  2700. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2701. };
  2702. /**
  2703. * Returns the string "Vector4".
  2704. */
  2705. Vector4.prototype.getClassName = function () {
  2706. return "Vector4";
  2707. };
  2708. /**
  2709. * Returns the Vector4 hash code.
  2710. */
  2711. Vector4.prototype.getHashCode = function () {
  2712. var hash = this.x || 0;
  2713. hash = (hash * 397) ^ (this.y || 0);
  2714. hash = (hash * 397) ^ (this.z || 0);
  2715. hash = (hash * 397) ^ (this.w || 0);
  2716. return hash;
  2717. };
  2718. // Operators
  2719. /**
  2720. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  2721. */
  2722. Vector4.prototype.asArray = function () {
  2723. var result = new Array();
  2724. this.toArray(result, 0);
  2725. return result;
  2726. };
  2727. /**
  2728. * Populates the passed array from the passed index with the Vector4 coordinates.
  2729. * Returns the Vector4.
  2730. */
  2731. Vector4.prototype.toArray = function (array, index) {
  2732. if (index === undefined) {
  2733. index = 0;
  2734. }
  2735. array[index] = this.x;
  2736. array[index + 1] = this.y;
  2737. array[index + 2] = this.z;
  2738. array[index + 3] = this.w;
  2739. return this;
  2740. };
  2741. /**
  2742. * Adds the passed vector to the current Vector4.
  2743. * Returns the updated Vector4.
  2744. */
  2745. Vector4.prototype.addInPlace = function (otherVector) {
  2746. this.x += otherVector.x;
  2747. this.y += otherVector.y;
  2748. this.z += otherVector.z;
  2749. this.w += otherVector.w;
  2750. return this;
  2751. };
  2752. /**
  2753. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  2754. */
  2755. Vector4.prototype.add = function (otherVector) {
  2756. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  2757. };
  2758. /**
  2759. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  2760. * Returns the current Vector4.
  2761. */
  2762. Vector4.prototype.addToRef = function (otherVector, result) {
  2763. result.x = this.x + otherVector.x;
  2764. result.y = this.y + otherVector.y;
  2765. result.z = this.z + otherVector.z;
  2766. result.w = this.w + otherVector.w;
  2767. return this;
  2768. };
  2769. /**
  2770. * Subtract in place the passed vector from the current Vector4.
  2771. * Returns the updated Vector4.
  2772. */
  2773. Vector4.prototype.subtractInPlace = function (otherVector) {
  2774. this.x -= otherVector.x;
  2775. this.y -= otherVector.y;
  2776. this.z -= otherVector.z;
  2777. this.w -= otherVector.w;
  2778. return this;
  2779. };
  2780. /**
  2781. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  2782. */
  2783. Vector4.prototype.subtract = function (otherVector) {
  2784. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  2785. };
  2786. /**
  2787. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  2788. * Returns the current Vector4.
  2789. */
  2790. Vector4.prototype.subtractToRef = function (otherVector, result) {
  2791. result.x = this.x - otherVector.x;
  2792. result.y = this.y - otherVector.y;
  2793. result.z = this.z - otherVector.z;
  2794. result.w = this.w - otherVector.w;
  2795. return this;
  2796. };
  2797. /**
  2798. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2799. */
  2800. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  2801. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  2802. };
  2803. /**
  2804. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2805. * Returns the current Vector4.
  2806. */
  2807. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  2808. result.x = this.x - x;
  2809. result.y = this.y - y;
  2810. result.z = this.z - z;
  2811. result.w = this.w - w;
  2812. return this;
  2813. };
  2814. /**
  2815. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  2816. */
  2817. Vector4.prototype.negate = function () {
  2818. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  2819. };
  2820. /**
  2821. * Multiplies the current Vector4 coordinates by scale (float).
  2822. * Returns the updated Vector4.
  2823. */
  2824. Vector4.prototype.scaleInPlace = function (scale) {
  2825. this.x *= scale;
  2826. this.y *= scale;
  2827. this.z *= scale;
  2828. this.w *= scale;
  2829. return this;
  2830. };
  2831. /**
  2832. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  2833. */
  2834. Vector4.prototype.scale = function (scale) {
  2835. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  2836. };
  2837. /**
  2838. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  2839. * Returns the current Vector4.
  2840. */
  2841. Vector4.prototype.scaleToRef = function (scale, result) {
  2842. result.x = this.x * scale;
  2843. result.y = this.y * scale;
  2844. result.z = this.z * scale;
  2845. result.w = this.w * scale;
  2846. return this;
  2847. };
  2848. /**
  2849. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  2850. */
  2851. Vector4.prototype.equals = function (otherVector) {
  2852. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  2853. };
  2854. /**
  2855. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  2856. */
  2857. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2858. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2859. return otherVector
  2860. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  2861. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  2862. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  2863. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  2864. };
  2865. /**
  2866. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  2867. */
  2868. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  2869. return this.x === x && this.y === y && this.z === z && this.w === w;
  2870. };
  2871. /**
  2872. * Multiplies in place the current Vector4 by the passed one.
  2873. * Returns the updated Vector4.
  2874. */
  2875. Vector4.prototype.multiplyInPlace = function (otherVector) {
  2876. this.x *= otherVector.x;
  2877. this.y *= otherVector.y;
  2878. this.z *= otherVector.z;
  2879. this.w *= otherVector.w;
  2880. return this;
  2881. };
  2882. /**
  2883. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2884. */
  2885. Vector4.prototype.multiply = function (otherVector) {
  2886. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2887. };
  2888. /**
  2889. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2890. * Returns the current Vector4.
  2891. */
  2892. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2893. result.x = this.x * otherVector.x;
  2894. result.y = this.y * otherVector.y;
  2895. result.z = this.z * otherVector.z;
  2896. result.w = this.w * otherVector.w;
  2897. return this;
  2898. };
  2899. /**
  2900. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2901. */
  2902. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2903. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2904. };
  2905. /**
  2906. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2907. */
  2908. Vector4.prototype.divide = function (otherVector) {
  2909. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2910. };
  2911. /**
  2912. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2913. * Returns the current Vector4.
  2914. */
  2915. Vector4.prototype.divideToRef = function (otherVector, result) {
  2916. result.x = this.x / otherVector.x;
  2917. result.y = this.y / otherVector.y;
  2918. result.z = this.z / otherVector.z;
  2919. result.w = this.w / otherVector.w;
  2920. return this;
  2921. };
  2922. /**
  2923. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2924. */
  2925. Vector4.prototype.MinimizeInPlace = function (other) {
  2926. if (other.x < this.x)
  2927. this.x = other.x;
  2928. if (other.y < this.y)
  2929. this.y = other.y;
  2930. if (other.z < this.z)
  2931. this.z = other.z;
  2932. if (other.w < this.w)
  2933. this.w = other.w;
  2934. return this;
  2935. };
  2936. /**
  2937. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2938. */
  2939. Vector4.prototype.MaximizeInPlace = function (other) {
  2940. if (other.x > this.x)
  2941. this.x = other.x;
  2942. if (other.y > this.y)
  2943. this.y = other.y;
  2944. if (other.z > this.z)
  2945. this.z = other.z;
  2946. if (other.w > this.w)
  2947. this.w = other.w;
  2948. return this;
  2949. };
  2950. // Properties
  2951. /**
  2952. * Returns the Vector4 length (float).
  2953. */
  2954. Vector4.prototype.length = function () {
  2955. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2956. };
  2957. /**
  2958. * Returns the Vector4 squared length (float).
  2959. */
  2960. Vector4.prototype.lengthSquared = function () {
  2961. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2962. };
  2963. // Methods
  2964. /**
  2965. * Normalizes in place the Vector4.
  2966. * Returns the updated Vector4.
  2967. */
  2968. Vector4.prototype.normalize = function () {
  2969. var len = this.length();
  2970. if (len === 0)
  2971. return this;
  2972. var num = 1.0 / len;
  2973. this.x *= num;
  2974. this.y *= num;
  2975. this.z *= num;
  2976. this.w *= num;
  2977. return this;
  2978. };
  2979. /**
  2980. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  2981. */
  2982. Vector4.prototype.toVector3 = function () {
  2983. return new Vector3(this.x, this.y, this.z);
  2984. };
  2985. /**
  2986. * Returns a new Vector4 copied from the current one.
  2987. */
  2988. Vector4.prototype.clone = function () {
  2989. return new Vector4(this.x, this.y, this.z, this.w);
  2990. };
  2991. /**
  2992. * Updates the current Vector4 with the passed one coordinates.
  2993. * Returns the updated Vector4.
  2994. */
  2995. Vector4.prototype.copyFrom = function (source) {
  2996. this.x = source.x;
  2997. this.y = source.y;
  2998. this.z = source.z;
  2999. this.w = source.w;
  3000. return this;
  3001. };
  3002. /**
  3003. * Updates the current Vector4 coordinates with the passed floats.
  3004. * Returns the updated Vector4.
  3005. */
  3006. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3007. this.x = x;
  3008. this.y = y;
  3009. this.z = z;
  3010. this.w = w;
  3011. return this;
  3012. };
  3013. /**
  3014. * Updates the current Vector4 coordinates with the passed floats.
  3015. * Returns the updated Vector4.
  3016. */
  3017. Vector4.prototype.set = function (x, y, z, w) {
  3018. return this.copyFromFloats(x, y, z, w);
  3019. };
  3020. // Statics
  3021. /**
  3022. * Returns a new Vector4 set from the starting index of the passed array.
  3023. */
  3024. Vector4.FromArray = function (array, offset) {
  3025. if (!offset) {
  3026. offset = 0;
  3027. }
  3028. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3029. };
  3030. /**
  3031. * Updates the passed vector "result" from the starting index of the passed array.
  3032. */
  3033. Vector4.FromArrayToRef = function (array, offset, result) {
  3034. result.x = array[offset];
  3035. result.y = array[offset + 1];
  3036. result.z = array[offset + 2];
  3037. result.w = array[offset + 3];
  3038. };
  3039. /**
  3040. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3041. */
  3042. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3043. Vector4.FromArrayToRef(array, offset, result);
  3044. };
  3045. /**
  3046. * Updates the passed vector "result" coordinates from the passed floats.
  3047. */
  3048. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3049. result.x = x;
  3050. result.y = y;
  3051. result.z = z;
  3052. result.w = w;
  3053. };
  3054. /**
  3055. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3056. */
  3057. Vector4.Zero = function () {
  3058. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3059. };
  3060. /**
  3061. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3062. */
  3063. Vector4.One = function () {
  3064. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3065. };
  3066. /**
  3067. * Returns a new normalized Vector4 from the passed one.
  3068. */
  3069. Vector4.Normalize = function (vector) {
  3070. var result = Vector4.Zero();
  3071. Vector4.NormalizeToRef(vector, result);
  3072. return result;
  3073. };
  3074. /**
  3075. * Updates the passed vector "result" from the normalization of the passed one.
  3076. */
  3077. Vector4.NormalizeToRef = function (vector, result) {
  3078. result.copyFrom(vector);
  3079. result.normalize();
  3080. };
  3081. Vector4.Minimize = function (left, right) {
  3082. var min = left.clone();
  3083. min.MinimizeInPlace(right);
  3084. return min;
  3085. };
  3086. Vector4.Maximize = function (left, right) {
  3087. var max = left.clone();
  3088. max.MaximizeInPlace(right);
  3089. return max;
  3090. };
  3091. /**
  3092. * Returns the distance (float) between the vectors "value1" and "value2".
  3093. */
  3094. Vector4.Distance = function (value1, value2) {
  3095. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3096. };
  3097. /**
  3098. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3099. */
  3100. Vector4.DistanceSquared = function (value1, value2) {
  3101. var x = value1.x - value2.x;
  3102. var y = value1.y - value2.y;
  3103. var z = value1.z - value2.z;
  3104. var w = value1.w - value2.w;
  3105. return (x * x) + (y * y) + (z * z) + (w * w);
  3106. };
  3107. /**
  3108. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3109. */
  3110. Vector4.Center = function (value1, value2) {
  3111. var center = value1.add(value2);
  3112. center.scaleInPlace(0.5);
  3113. return center;
  3114. };
  3115. /**
  3116. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3117. * This methods computes transformed normalized direction vectors only.
  3118. */
  3119. Vector4.TransformNormal = function (vector, transformation) {
  3120. var result = Vector4.Zero();
  3121. Vector4.TransformNormalToRef(vector, transformation, result);
  3122. return result;
  3123. };
  3124. /**
  3125. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3126. * This methods computes transformed normalized direction vectors only.
  3127. */
  3128. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  3129. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3130. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3131. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3132. result.x = x;
  3133. result.y = y;
  3134. result.z = z;
  3135. result.w = vector.w;
  3136. };
  3137. /**
  3138. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  3139. * This methods computes transformed normalized direction vectors only.
  3140. */
  3141. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  3142. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3143. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3144. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3145. result.w = w;
  3146. };
  3147. return Vector4;
  3148. }());
  3149. BABYLON.Vector4 = Vector4;
  3150. var Size = /** @class */ (function () {
  3151. /**
  3152. * Creates a Size object from the passed width and height (floats).
  3153. */
  3154. function Size(width, height) {
  3155. this.width = width;
  3156. this.height = height;
  3157. }
  3158. // Returns a string with the Size width and height.
  3159. Size.prototype.toString = function () {
  3160. return "{W: " + this.width + ", H: " + this.height + "}";
  3161. };
  3162. /**
  3163. * Returns the string "Size"
  3164. */
  3165. Size.prototype.getClassName = function () {
  3166. return "Size";
  3167. };
  3168. /**
  3169. * Returns the Size hash code.
  3170. */
  3171. Size.prototype.getHashCode = function () {
  3172. var hash = this.width || 0;
  3173. hash = (hash * 397) ^ (this.height || 0);
  3174. return hash;
  3175. };
  3176. /**
  3177. * Updates the current size from the passed one.
  3178. * Returns the updated Size.
  3179. */
  3180. Size.prototype.copyFrom = function (src) {
  3181. this.width = src.width;
  3182. this.height = src.height;
  3183. };
  3184. /**
  3185. * Updates in place the current Size from the passed floats.
  3186. * Returns the updated Size.
  3187. */
  3188. Size.prototype.copyFromFloats = function (width, height) {
  3189. this.width = width;
  3190. this.height = height;
  3191. return this;
  3192. };
  3193. /**
  3194. * Updates in place the current Size from the passed floats.
  3195. * Returns the updated Size.
  3196. */
  3197. Size.prototype.set = function (width, height) {
  3198. return this.copyFromFloats(width, height);
  3199. };
  3200. /**
  3201. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  3202. */
  3203. Size.prototype.multiplyByFloats = function (w, h) {
  3204. return new Size(this.width * w, this.height * h);
  3205. };
  3206. /**
  3207. * Returns a new Size copied from the passed one.
  3208. */
  3209. Size.prototype.clone = function () {
  3210. return new Size(this.width, this.height);
  3211. };
  3212. /**
  3213. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  3214. */
  3215. Size.prototype.equals = function (other) {
  3216. if (!other) {
  3217. return false;
  3218. }
  3219. return (this.width === other.width) && (this.height === other.height);
  3220. };
  3221. Object.defineProperty(Size.prototype, "surface", {
  3222. /**
  3223. * Returns the surface of the Size : width * height (float).
  3224. */
  3225. get: function () {
  3226. return this.width * this.height;
  3227. },
  3228. enumerable: true,
  3229. configurable: true
  3230. });
  3231. /**
  3232. * Returns a new Size set to (0.0, 0.0)
  3233. */
  3234. Size.Zero = function () {
  3235. return new Size(0.0, 0.0);
  3236. };
  3237. /**
  3238. * Returns a new Size set as the addition result of the current Size and the passed one.
  3239. */
  3240. Size.prototype.add = function (otherSize) {
  3241. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  3242. return r;
  3243. };
  3244. /**
  3245. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  3246. */
  3247. Size.prototype.subtract = function (otherSize) {
  3248. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  3249. return r;
  3250. };
  3251. /**
  3252. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  3253. */
  3254. Size.Lerp = function (start, end, amount) {
  3255. var w = start.width + ((end.width - start.width) * amount);
  3256. var h = start.height + ((end.height - start.height) * amount);
  3257. return new Size(w, h);
  3258. };
  3259. return Size;
  3260. }());
  3261. BABYLON.Size = Size;
  3262. var Quaternion = /** @class */ (function () {
  3263. /**
  3264. * Creates a new Quaternion from the passed floats.
  3265. */
  3266. function Quaternion(x, y, z, w) {
  3267. if (x === void 0) { x = 0.0; }
  3268. if (y === void 0) { y = 0.0; }
  3269. if (z === void 0) { z = 0.0; }
  3270. if (w === void 0) { w = 1.0; }
  3271. this.x = x;
  3272. this.y = y;
  3273. this.z = z;
  3274. this.w = w;
  3275. }
  3276. /**
  3277. * Returns a string with the Quaternion coordinates.
  3278. */
  3279. Quaternion.prototype.toString = function () {
  3280. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3281. };
  3282. /**
  3283. * Returns the string "Quaternion".
  3284. */
  3285. Quaternion.prototype.getClassName = function () {
  3286. return "Quaternion";
  3287. };
  3288. /**
  3289. * Returns the Quaternion hash code.
  3290. */
  3291. Quaternion.prototype.getHashCode = function () {
  3292. var hash = this.x || 0;
  3293. hash = (hash * 397) ^ (this.y || 0);
  3294. hash = (hash * 397) ^ (this.z || 0);
  3295. hash = (hash * 397) ^ (this.w || 0);
  3296. return hash;
  3297. };
  3298. /**
  3299. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  3300. */
  3301. Quaternion.prototype.asArray = function () {
  3302. return [this.x, this.y, this.z, this.w];
  3303. };
  3304. /**
  3305. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  3306. */
  3307. Quaternion.prototype.equals = function (otherQuaternion) {
  3308. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  3309. };
  3310. /**
  3311. * Returns a new Quaternion copied from the current one.
  3312. */
  3313. Quaternion.prototype.clone = function () {
  3314. return new Quaternion(this.x, this.y, this.z, this.w);
  3315. };
  3316. /**
  3317. * Updates the current Quaternion from the passed one coordinates.
  3318. * Returns the updated Quaterion.
  3319. */
  3320. Quaternion.prototype.copyFrom = function (other) {
  3321. this.x = other.x;
  3322. this.y = other.y;
  3323. this.z = other.z;
  3324. this.w = other.w;
  3325. return this;
  3326. };
  3327. /**
  3328. * Updates the current Quaternion from the passed float coordinates.
  3329. * Returns the updated Quaterion.
  3330. */
  3331. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  3332. this.x = x;
  3333. this.y = y;
  3334. this.z = z;
  3335. this.w = w;
  3336. return this;
  3337. };
  3338. /**
  3339. * Updates the current Quaternion from the passed float coordinates.
  3340. * Returns the updated Quaterion.
  3341. */
  3342. Quaternion.prototype.set = function (x, y, z, w) {
  3343. return this.copyFromFloats(x, y, z, w);
  3344. };
  3345. /**
  3346. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  3347. */
  3348. Quaternion.prototype.add = function (other) {
  3349. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  3350. };
  3351. /**
  3352. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  3353. */
  3354. Quaternion.prototype.subtract = function (other) {
  3355. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  3356. };
  3357. /**
  3358. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  3359. */
  3360. Quaternion.prototype.scale = function (value) {
  3361. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  3362. };
  3363. /**
  3364. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  3365. */
  3366. Quaternion.prototype.multiply = function (q1) {
  3367. var result = new Quaternion(0, 0, 0, 1.0);
  3368. this.multiplyToRef(q1, result);
  3369. return result;
  3370. };
  3371. /**
  3372. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  3373. * Returns the current Quaternion.
  3374. */
  3375. Quaternion.prototype.multiplyToRef = function (q1, result) {
  3376. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  3377. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  3378. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  3379. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  3380. result.copyFromFloats(x, y, z, w);
  3381. return this;
  3382. };
  3383. /**
  3384. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  3385. * Returns the updated Quaternion.
  3386. */
  3387. Quaternion.prototype.multiplyInPlace = function (q1) {
  3388. this.multiplyToRef(q1, this);
  3389. return this;
  3390. };
  3391. /**
  3392. * Sets the passed "ref" with the conjugation of the current Quaternion.
  3393. * Returns the current Quaternion.
  3394. */
  3395. Quaternion.prototype.conjugateToRef = function (ref) {
  3396. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  3397. return this;
  3398. };
  3399. /**
  3400. * Conjugates in place the current Quaternion.
  3401. * Returns the updated Quaternion.
  3402. */
  3403. Quaternion.prototype.conjugateInPlace = function () {
  3404. this.x *= -1;
  3405. this.y *= -1;
  3406. this.z *= -1;
  3407. return this;
  3408. };
  3409. /**
  3410. * Returns a new Quaternion as the conjugate of the current Quaternion.
  3411. */
  3412. Quaternion.prototype.conjugate = function () {
  3413. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  3414. return result;
  3415. };
  3416. /**
  3417. * Returns the Quaternion length (float).
  3418. */
  3419. Quaternion.prototype.length = function () {
  3420. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  3421. };
  3422. /**
  3423. * Normalize in place the current Quaternion.
  3424. * Returns the updated Quaternion.
  3425. */
  3426. Quaternion.prototype.normalize = function () {
  3427. var length = 1.0 / this.length();
  3428. this.x *= length;
  3429. this.y *= length;
  3430. this.z *= length;
  3431. this.w *= length;
  3432. return this;
  3433. };
  3434. /**
  3435. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  3436. */
  3437. Quaternion.prototype.toEulerAngles = function (order) {
  3438. if (order === void 0) { order = "YZX"; }
  3439. var result = Vector3.Zero();
  3440. this.toEulerAnglesToRef(result, order);
  3441. return result;
  3442. };
  3443. /**
  3444. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  3445. * Returns the current Quaternion.
  3446. */
  3447. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  3448. if (order === void 0) { order = "YZX"; }
  3449. var qz = this.z;
  3450. var qx = this.x;
  3451. var qy = this.y;
  3452. var qw = this.w;
  3453. var sqw = qw * qw;
  3454. var sqz = qz * qz;
  3455. var sqx = qx * qx;
  3456. var sqy = qy * qy;
  3457. var zAxisY = qy * qz - qx * qw;
  3458. var limit = .4999999;
  3459. if (zAxisY < -limit) {
  3460. result.y = 2 * Math.atan2(qy, qw);
  3461. result.x = Math.PI / 2;
  3462. result.z = 0;
  3463. }
  3464. else if (zAxisY > limit) {
  3465. result.y = 2 * Math.atan2(qy, qw);
  3466. result.x = -Math.PI / 2;
  3467. result.z = 0;
  3468. }
  3469. else {
  3470. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  3471. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  3472. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  3473. }
  3474. return this;
  3475. };
  3476. /**
  3477. * Updates the passed rotation matrix with the current Quaternion values.
  3478. * Returns the current Quaternion.
  3479. */
  3480. Quaternion.prototype.toRotationMatrix = function (result) {
  3481. var xx = this.x * this.x;
  3482. var yy = this.y * this.y;
  3483. var zz = this.z * this.z;
  3484. var xy = this.x * this.y;
  3485. var zw = this.z * this.w;
  3486. var zx = this.z * this.x;
  3487. var yw = this.y * this.w;
  3488. var yz = this.y * this.z;
  3489. var xw = this.x * this.w;
  3490. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3491. result.m[1] = 2.0 * (xy + zw);
  3492. result.m[2] = 2.0 * (zx - yw);
  3493. result.m[3] = 0;
  3494. result.m[4] = 2.0 * (xy - zw);
  3495. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3496. result.m[6] = 2.0 * (yz + xw);
  3497. result.m[7] = 0;
  3498. result.m[8] = 2.0 * (zx + yw);
  3499. result.m[9] = 2.0 * (yz - xw);
  3500. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3501. result.m[11] = 0;
  3502. result.m[12] = 0;
  3503. result.m[13] = 0;
  3504. result.m[14] = 0;
  3505. result.m[15] = 1.0;
  3506. result._markAsUpdated();
  3507. return this;
  3508. };
  3509. /**
  3510. * Updates the current Quaternion from the passed rotation matrix values.
  3511. * Returns the updated Quaternion.
  3512. */
  3513. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  3514. Quaternion.FromRotationMatrixToRef(matrix, this);
  3515. return this;
  3516. };
  3517. // Statics
  3518. /**
  3519. * Returns a new Quaternion set from the passed rotation matrix values.
  3520. */
  3521. Quaternion.FromRotationMatrix = function (matrix) {
  3522. var result = new Quaternion();
  3523. Quaternion.FromRotationMatrixToRef(matrix, result);
  3524. return result;
  3525. };
  3526. /**
  3527. * Updates the passed quaternion "result" with the passed rotation matrix values.
  3528. */
  3529. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  3530. var data = matrix.m;
  3531. var m11 = data[0], m12 = data[4], m13 = data[8];
  3532. var m21 = data[1], m22 = data[5], m23 = data[9];
  3533. var m31 = data[2], m32 = data[6], m33 = data[10];
  3534. var trace = m11 + m22 + m33;
  3535. var s;
  3536. if (trace > 0) {
  3537. s = 0.5 / Math.sqrt(trace + 1.0);
  3538. result.w = 0.25 / s;
  3539. result.x = (m32 - m23) * s;
  3540. result.y = (m13 - m31) * s;
  3541. result.z = (m21 - m12) * s;
  3542. }
  3543. else if (m11 > m22 && m11 > m33) {
  3544. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  3545. result.w = (m32 - m23) / s;
  3546. result.x = 0.25 * s;
  3547. result.y = (m12 + m21) / s;
  3548. result.z = (m13 + m31) / s;
  3549. }
  3550. else if (m22 > m33) {
  3551. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  3552. result.w = (m13 - m31) / s;
  3553. result.x = (m12 + m21) / s;
  3554. result.y = 0.25 * s;
  3555. result.z = (m23 + m32) / s;
  3556. }
  3557. else {
  3558. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  3559. result.w = (m21 - m12) / s;
  3560. result.x = (m13 + m31) / s;
  3561. result.y = (m23 + m32) / s;
  3562. result.z = 0.25 * s;
  3563. }
  3564. };
  3565. /**
  3566. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  3567. */
  3568. Quaternion.Zero = function () {
  3569. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  3570. };
  3571. /**
  3572. * Returns a new Quaternion as the inverted current Quaternion.
  3573. */
  3574. Quaternion.Inverse = function (q) {
  3575. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  3576. };
  3577. /**
  3578. * Returns the identity Quaternion.
  3579. */
  3580. Quaternion.Identity = function () {
  3581. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  3582. };
  3583. Quaternion.IsIdentity = function (quaternion) {
  3584. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  3585. };
  3586. /**
  3587. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  3588. */
  3589. Quaternion.RotationAxis = function (axis, angle) {
  3590. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  3591. };
  3592. /**
  3593. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  3594. */
  3595. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  3596. var sin = Math.sin(angle / 2);
  3597. axis.normalize();
  3598. result.w = Math.cos(angle / 2);
  3599. result.x = axis.x * sin;
  3600. result.y = axis.y * sin;
  3601. result.z = axis.z * sin;
  3602. return result;
  3603. };
  3604. /**
  3605. * Retuns a new Quaternion set from the starting index of the passed array.
  3606. */
  3607. Quaternion.FromArray = function (array, offset) {
  3608. if (!offset) {
  3609. offset = 0;
  3610. }
  3611. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3612. };
  3613. /**
  3614. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  3615. */
  3616. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3617. var q = new Quaternion();
  3618. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  3619. return q;
  3620. };
  3621. /**
  3622. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  3623. */
  3624. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3625. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  3626. var halfRoll = roll * 0.5;
  3627. var halfPitch = pitch * 0.5;
  3628. var halfYaw = yaw * 0.5;
  3629. var sinRoll = Math.sin(halfRoll);
  3630. var cosRoll = Math.cos(halfRoll);
  3631. var sinPitch = Math.sin(halfPitch);
  3632. var cosPitch = Math.cos(halfPitch);
  3633. var sinYaw = Math.sin(halfYaw);
  3634. var cosYaw = Math.cos(halfYaw);
  3635. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  3636. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  3637. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  3638. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  3639. };
  3640. /**
  3641. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  3642. */
  3643. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  3644. var result = new Quaternion();
  3645. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  3646. return result;
  3647. };
  3648. /**
  3649. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  3650. */
  3651. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  3652. // Produces a quaternion from Euler angles in the z-x-z orientation
  3653. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  3654. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  3655. var halfBeta = beta * 0.5;
  3656. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3657. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3658. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3659. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3660. };
  3661. /**
  3662. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3663. * cf to Vector3.RotationFromAxis() documentation.
  3664. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3665. */
  3666. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  3667. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  3668. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3669. return quat;
  3670. };
  3671. /**
  3672. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3673. * cf to Vector3.RotationFromAxis() documentation.
  3674. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3675. */
  3676. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3677. var rotMat = MathTmp.Matrix[0];
  3678. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  3679. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  3680. };
  3681. Quaternion.Slerp = function (left, right, amount) {
  3682. var result = Quaternion.Identity();
  3683. Quaternion.SlerpToRef(left, right, amount, result);
  3684. return result;
  3685. };
  3686. Quaternion.SlerpToRef = function (left, right, amount, result) {
  3687. var num2;
  3688. var num3;
  3689. var num = amount;
  3690. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  3691. var flag = false;
  3692. if (num4 < 0) {
  3693. flag = true;
  3694. num4 = -num4;
  3695. }
  3696. if (num4 > 0.999999) {
  3697. num3 = 1 - num;
  3698. num2 = flag ? -num : num;
  3699. }
  3700. else {
  3701. var num5 = Math.acos(num4);
  3702. var num6 = (1.0 / Math.sin(num5));
  3703. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  3704. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  3705. }
  3706. result.x = (num3 * left.x) + (num2 * right.x);
  3707. result.y = (num3 * left.y) + (num2 * right.y);
  3708. result.z = (num3 * left.z) + (num2 * right.z);
  3709. result.w = (num3 * left.w) + (num2 * right.w);
  3710. };
  3711. /**
  3712. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  3713. */
  3714. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3715. var squared = amount * amount;
  3716. var cubed = amount * squared;
  3717. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3718. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3719. var part3 = (cubed - (2.0 * squared)) + amount;
  3720. var part4 = cubed - squared;
  3721. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3722. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3723. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3724. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  3725. return new Quaternion(x, y, z, w);
  3726. };
  3727. return Quaternion;
  3728. }());
  3729. BABYLON.Quaternion = Quaternion;
  3730. var Matrix = /** @class */ (function () {
  3731. function Matrix() {
  3732. this._isIdentity = false;
  3733. this._isIdentityDirty = true;
  3734. this.m = new Float32Array(16);
  3735. this._markAsUpdated();
  3736. }
  3737. Matrix.prototype._markAsUpdated = function () {
  3738. this.updateFlag = Matrix._updateFlagSeed++;
  3739. this._isIdentityDirty = true;
  3740. };
  3741. // Properties
  3742. /**
  3743. * Boolean : True is the matrix is the identity matrix
  3744. */
  3745. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  3746. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  3747. if (this._isIdentityDirty) {
  3748. this._isIdentityDirty = false;
  3749. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  3750. this._isIdentity = false;
  3751. }
  3752. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  3753. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  3754. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  3755. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  3756. this._isIdentity = false;
  3757. }
  3758. else {
  3759. this._isIdentity = true;
  3760. }
  3761. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  3762. this._isIdentity = false;
  3763. }
  3764. }
  3765. return this._isIdentity;
  3766. };
  3767. /**
  3768. * Returns the matrix determinant (float).
  3769. */
  3770. Matrix.prototype.determinant = function () {
  3771. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  3772. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  3773. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  3774. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  3775. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  3776. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  3777. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  3778. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  3779. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  3780. };
  3781. // Methods
  3782. /**
  3783. * Returns the matrix underlying array.
  3784. */
  3785. Matrix.prototype.toArray = function () {
  3786. return this.m;
  3787. };
  3788. /**
  3789. * Returns the matrix underlying array.
  3790. */
  3791. Matrix.prototype.asArray = function () {
  3792. return this.toArray();
  3793. };
  3794. /**
  3795. * Inverts in place the Matrix.
  3796. * Returns the Matrix inverted.
  3797. */
  3798. Matrix.prototype.invert = function () {
  3799. this.invertToRef(this);
  3800. return this;
  3801. };
  3802. /**
  3803. * Sets all the matrix elements to zero.
  3804. * Returns the Matrix.
  3805. */
  3806. Matrix.prototype.reset = function () {
  3807. for (var index = 0; index < 16; index++) {
  3808. this.m[index] = 0.0;
  3809. }
  3810. this._markAsUpdated();
  3811. return this;
  3812. };
  3813. /**
  3814. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  3815. */
  3816. Matrix.prototype.add = function (other) {
  3817. var result = new Matrix();
  3818. this.addToRef(other, result);
  3819. return result;
  3820. };
  3821. /**
  3822. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  3823. * Returns the Matrix.
  3824. */
  3825. Matrix.prototype.addToRef = function (other, result) {
  3826. for (var index = 0; index < 16; index++) {
  3827. result.m[index] = this.m[index] + other.m[index];
  3828. }
  3829. result._markAsUpdated();
  3830. return this;
  3831. };
  3832. /**
  3833. * Adds in place the passed matrix to the current Matrix.
  3834. * Returns the updated Matrix.
  3835. */
  3836. Matrix.prototype.addToSelf = function (other) {
  3837. for (var index = 0; index < 16; index++) {
  3838. this.m[index] += other.m[index];
  3839. }
  3840. this._markAsUpdated();
  3841. return this;
  3842. };
  3843. /**
  3844. * Sets the passed matrix with the current inverted Matrix.
  3845. * Returns the unmodified current Matrix.
  3846. */
  3847. Matrix.prototype.invertToRef = function (other) {
  3848. var l1 = this.m[0];
  3849. var l2 = this.m[1];
  3850. var l3 = this.m[2];
  3851. var l4 = this.m[3];
  3852. var l5 = this.m[4];
  3853. var l6 = this.m[5];
  3854. var l7 = this.m[6];
  3855. var l8 = this.m[7];
  3856. var l9 = this.m[8];
  3857. var l10 = this.m[9];
  3858. var l11 = this.m[10];
  3859. var l12 = this.m[11];
  3860. var l13 = this.m[12];
  3861. var l14 = this.m[13];
  3862. var l15 = this.m[14];
  3863. var l16 = this.m[15];
  3864. var l17 = (l11 * l16) - (l12 * l15);
  3865. var l18 = (l10 * l16) - (l12 * l14);
  3866. var l19 = (l10 * l15) - (l11 * l14);
  3867. var l20 = (l9 * l16) - (l12 * l13);
  3868. var l21 = (l9 * l15) - (l11 * l13);
  3869. var l22 = (l9 * l14) - (l10 * l13);
  3870. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  3871. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  3872. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  3873. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  3874. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  3875. var l28 = (l7 * l16) - (l8 * l15);
  3876. var l29 = (l6 * l16) - (l8 * l14);
  3877. var l30 = (l6 * l15) - (l7 * l14);
  3878. var l31 = (l5 * l16) - (l8 * l13);
  3879. var l32 = (l5 * l15) - (l7 * l13);
  3880. var l33 = (l5 * l14) - (l6 * l13);
  3881. var l34 = (l7 * l12) - (l8 * l11);
  3882. var l35 = (l6 * l12) - (l8 * l10);
  3883. var l36 = (l6 * l11) - (l7 * l10);
  3884. var l37 = (l5 * l12) - (l8 * l9);
  3885. var l38 = (l5 * l11) - (l7 * l9);
  3886. var l39 = (l5 * l10) - (l6 * l9);
  3887. other.m[0] = l23 * l27;
  3888. other.m[4] = l24 * l27;
  3889. other.m[8] = l25 * l27;
  3890. other.m[12] = l26 * l27;
  3891. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3892. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3893. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3894. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3895. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3896. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3897. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3898. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3899. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3900. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3901. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3902. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3903. other._markAsUpdated();
  3904. return this;
  3905. };
  3906. /**
  3907. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3908. * Returns the updated Matrix.
  3909. */
  3910. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3911. this.m[12] = x;
  3912. this.m[13] = y;
  3913. this.m[14] = z;
  3914. this._markAsUpdated();
  3915. return this;
  3916. };
  3917. /**
  3918. * Inserts the translation vector in the current Matrix.
  3919. * Returns the updated Matrix.
  3920. */
  3921. Matrix.prototype.setTranslation = function (vector3) {
  3922. this.m[12] = vector3.x;
  3923. this.m[13] = vector3.y;
  3924. this.m[14] = vector3.z;
  3925. this._markAsUpdated();
  3926. return this;
  3927. };
  3928. /**
  3929. * Returns a new Vector3 as the extracted translation from the Matrix.
  3930. */
  3931. Matrix.prototype.getTranslation = function () {
  3932. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3933. };
  3934. /**
  3935. * Fill a Vector3 with the extracted translation from the Matrix.
  3936. */
  3937. Matrix.prototype.getTranslationToRef = function (result) {
  3938. result.x = this.m[12];
  3939. result.y = this.m[13];
  3940. result.z = this.m[14];
  3941. return this;
  3942. };
  3943. /**
  3944. * Remove rotation and scaling part from the Matrix.
  3945. * Returns the updated Matrix.
  3946. */
  3947. Matrix.prototype.removeRotationAndScaling = function () {
  3948. this.setRowFromFloats(0, 1, 0, 0, 0);
  3949. this.setRowFromFloats(1, 0, 1, 0, 0);
  3950. this.setRowFromFloats(2, 0, 0, 1, 0);
  3951. return this;
  3952. };
  3953. /**
  3954. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  3955. */
  3956. Matrix.prototype.multiply = function (other) {
  3957. var result = new Matrix();
  3958. this.multiplyToRef(other, result);
  3959. return result;
  3960. };
  3961. /**
  3962. * Updates the current Matrix from the passed one values.
  3963. * Returns the updated Matrix.
  3964. */
  3965. Matrix.prototype.copyFrom = function (other) {
  3966. for (var index = 0; index < 16; index++) {
  3967. this.m[index] = other.m[index];
  3968. }
  3969. this._markAsUpdated();
  3970. return this;
  3971. };
  3972. /**
  3973. * Populates the passed array from the starting index with the Matrix values.
  3974. * Returns the Matrix.
  3975. */
  3976. Matrix.prototype.copyToArray = function (array, offset) {
  3977. if (offset === void 0) { offset = 0; }
  3978. for (var index = 0; index < 16; index++) {
  3979. array[offset + index] = this.m[index];
  3980. }
  3981. return this;
  3982. };
  3983. /**
  3984. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  3985. */
  3986. Matrix.prototype.multiplyToRef = function (other, result) {
  3987. this.multiplyToArray(other, result.m, 0);
  3988. result._markAsUpdated();
  3989. return this;
  3990. };
  3991. /**
  3992. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  3993. */
  3994. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  3995. var tm0 = this.m[0];
  3996. var tm1 = this.m[1];
  3997. var tm2 = this.m[2];
  3998. var tm3 = this.m[3];
  3999. var tm4 = this.m[4];
  4000. var tm5 = this.m[5];
  4001. var tm6 = this.m[6];
  4002. var tm7 = this.m[7];
  4003. var tm8 = this.m[8];
  4004. var tm9 = this.m[9];
  4005. var tm10 = this.m[10];
  4006. var tm11 = this.m[11];
  4007. var tm12 = this.m[12];
  4008. var tm13 = this.m[13];
  4009. var tm14 = this.m[14];
  4010. var tm15 = this.m[15];
  4011. var om0 = other.m[0];
  4012. var om1 = other.m[1];
  4013. var om2 = other.m[2];
  4014. var om3 = other.m[3];
  4015. var om4 = other.m[4];
  4016. var om5 = other.m[5];
  4017. var om6 = other.m[6];
  4018. var om7 = other.m[7];
  4019. var om8 = other.m[8];
  4020. var om9 = other.m[9];
  4021. var om10 = other.m[10];
  4022. var om11 = other.m[11];
  4023. var om12 = other.m[12];
  4024. var om13 = other.m[13];
  4025. var om14 = other.m[14];
  4026. var om15 = other.m[15];
  4027. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4028. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4029. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4030. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4031. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4032. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4033. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4034. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4035. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4036. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4037. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4038. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4039. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4040. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4041. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4042. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4043. return this;
  4044. };
  4045. /**
  4046. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4047. */
  4048. Matrix.prototype.equals = function (value) {
  4049. return value &&
  4050. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4051. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4052. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4053. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4054. };
  4055. /**
  4056. * Returns a new Matrix from the current Matrix.
  4057. */
  4058. Matrix.prototype.clone = function () {
  4059. 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]);
  4060. };
  4061. /**
  4062. * Returns the string "Matrix"
  4063. */
  4064. Matrix.prototype.getClassName = function () {
  4065. return "Matrix";
  4066. };
  4067. /**
  4068. * Returns the Matrix hash code.
  4069. */
  4070. Matrix.prototype.getHashCode = function () {
  4071. var hash = this.m[0] || 0;
  4072. for (var i = 1; i < 16; i++) {
  4073. hash = (hash * 397) ^ (this.m[i] || 0);
  4074. }
  4075. return hash;
  4076. };
  4077. /**
  4078. * Decomposes the current Matrix into :
  4079. * - a scale vector3 passed as a reference to update,
  4080. * - a rotation quaternion passed as a reference to update,
  4081. * - a translation vector3 passed as a reference to update.
  4082. * Returns the boolean `true`.
  4083. */
  4084. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4085. translation.x = this.m[12];
  4086. translation.y = this.m[13];
  4087. translation.z = this.m[14];
  4088. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4089. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4090. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4091. if (this.determinant() <= 0) {
  4092. scale.y *= -1;
  4093. }
  4094. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4095. rotation.x = 0;
  4096. rotation.y = 0;
  4097. rotation.z = 0;
  4098. rotation.w = 1;
  4099. return false;
  4100. }
  4101. 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]);
  4102. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4103. return true;
  4104. };
  4105. /**
  4106. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4107. */
  4108. Matrix.prototype.getRotationMatrix = function () {
  4109. var result = Matrix.Identity();
  4110. this.getRotationMatrixToRef(result);
  4111. return result;
  4112. };
  4113. /**
  4114. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4115. * Returns the current Matrix.
  4116. */
  4117. Matrix.prototype.getRotationMatrixToRef = function (result) {
  4118. var m = this.m;
  4119. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  4120. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  4121. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  4122. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  4123. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  4124. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  4125. 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);
  4126. return this;
  4127. };
  4128. // Statics
  4129. /**
  4130. * Returns a new Matrix set from the starting index of the passed array.
  4131. */
  4132. Matrix.FromArray = function (array, offset) {
  4133. var result = new Matrix();
  4134. if (!offset) {
  4135. offset = 0;
  4136. }
  4137. Matrix.FromArrayToRef(array, offset, result);
  4138. return result;
  4139. };
  4140. /**
  4141. * Sets the passed "result" matrix from the starting index of the passed array.
  4142. */
  4143. Matrix.FromArrayToRef = function (array, offset, result) {
  4144. for (var index = 0; index < 16; index++) {
  4145. result.m[index] = array[index + offset];
  4146. }
  4147. result._markAsUpdated();
  4148. };
  4149. /**
  4150. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  4151. */
  4152. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  4153. for (var index = 0; index < 16; index++) {
  4154. result.m[index] = array[index + offset] * scale;
  4155. }
  4156. result._markAsUpdated();
  4157. };
  4158. /**
  4159. * Sets the passed matrix "result" with the 16 passed floats.
  4160. */
  4161. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  4162. result.m[0] = initialM11;
  4163. result.m[1] = initialM12;
  4164. result.m[2] = initialM13;
  4165. result.m[3] = initialM14;
  4166. result.m[4] = initialM21;
  4167. result.m[5] = initialM22;
  4168. result.m[6] = initialM23;
  4169. result.m[7] = initialM24;
  4170. result.m[8] = initialM31;
  4171. result.m[9] = initialM32;
  4172. result.m[10] = initialM33;
  4173. result.m[11] = initialM34;
  4174. result.m[12] = initialM41;
  4175. result.m[13] = initialM42;
  4176. result.m[14] = initialM43;
  4177. result.m[15] = initialM44;
  4178. result._markAsUpdated();
  4179. };
  4180. /**
  4181. * Returns the index-th row of the current matrix as a new Vector4.
  4182. */
  4183. Matrix.prototype.getRow = function (index) {
  4184. if (index < 0 || index > 3) {
  4185. return null;
  4186. }
  4187. var i = index * 4;
  4188. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  4189. };
  4190. /**
  4191. * Sets the index-th row of the current matrix with the passed Vector4 values.
  4192. * Returns the updated Matrix.
  4193. */
  4194. Matrix.prototype.setRow = function (index, row) {
  4195. if (index < 0 || index > 3) {
  4196. return this;
  4197. }
  4198. var i = index * 4;
  4199. this.m[i + 0] = row.x;
  4200. this.m[i + 1] = row.y;
  4201. this.m[i + 2] = row.z;
  4202. this.m[i + 3] = row.w;
  4203. this._markAsUpdated();
  4204. return this;
  4205. };
  4206. /**
  4207. * Compute the transpose of the matrix.
  4208. * Returns a new Matrix.
  4209. */
  4210. Matrix.prototype.transpose = function () {
  4211. return Matrix.Transpose(this);
  4212. };
  4213. /**
  4214. * Compute the transpose of the matrix.
  4215. * Returns the current matrix.
  4216. */
  4217. Matrix.prototype.transposeToRef = function (result) {
  4218. Matrix.TransposeToRef(this, result);
  4219. return this;
  4220. };
  4221. /**
  4222. * Sets the index-th row of the current matrix with the passed 4 x float values.
  4223. * Returns the updated Matrix.
  4224. */
  4225. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  4226. if (index < 0 || index > 3) {
  4227. return this;
  4228. }
  4229. var i = index * 4;
  4230. this.m[i + 0] = x;
  4231. this.m[i + 1] = y;
  4232. this.m[i + 2] = z;
  4233. this.m[i + 3] = w;
  4234. this._markAsUpdated();
  4235. return this;
  4236. };
  4237. Object.defineProperty(Matrix, "IdentityReadOnly", {
  4238. /**
  4239. * Static identity matrix to be used as readonly matrix
  4240. * Must not be updated.
  4241. */
  4242. get: function () {
  4243. return Matrix._identityReadOnly;
  4244. },
  4245. enumerable: true,
  4246. configurable: true
  4247. });
  4248. /**
  4249. * Returns a new Matrix set from the 16 passed floats.
  4250. */
  4251. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  4252. var result = new Matrix();
  4253. result.m[0] = initialM11;
  4254. result.m[1] = initialM12;
  4255. result.m[2] = initialM13;
  4256. result.m[3] = initialM14;
  4257. result.m[4] = initialM21;
  4258. result.m[5] = initialM22;
  4259. result.m[6] = initialM23;
  4260. result.m[7] = initialM24;
  4261. result.m[8] = initialM31;
  4262. result.m[9] = initialM32;
  4263. result.m[10] = initialM33;
  4264. result.m[11] = initialM34;
  4265. result.m[12] = initialM41;
  4266. result.m[13] = initialM42;
  4267. result.m[14] = initialM43;
  4268. result.m[15] = initialM44;
  4269. return result;
  4270. };
  4271. /**
  4272. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4273. */
  4274. Matrix.Compose = function (scale, rotation, translation) {
  4275. var result = Matrix.Identity();
  4276. Matrix.ComposeToRef(scale, rotation, translation, result);
  4277. return result;
  4278. };
  4279. /**
  4280. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4281. */
  4282. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  4283. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  4284. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  4285. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  4286. result.setTranslation(translation);
  4287. };
  4288. /**
  4289. * Returns a new indentity Matrix.
  4290. */
  4291. Matrix.Identity = function () {
  4292. 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);
  4293. };
  4294. /**
  4295. * Sets the passed "result" as an identity matrix.
  4296. */
  4297. Matrix.IdentityToRef = function (result) {
  4298. 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);
  4299. };
  4300. /**
  4301. * Returns a new zero Matrix.
  4302. */
  4303. Matrix.Zero = function () {
  4304. 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);
  4305. };
  4306. /**
  4307. * Returns a new rotation matrix for "angle" radians around the X axis.
  4308. */
  4309. Matrix.RotationX = function (angle) {
  4310. var result = new Matrix();
  4311. Matrix.RotationXToRef(angle, result);
  4312. return result;
  4313. };
  4314. /**
  4315. * Returns a new Matrix as the passed inverted one.
  4316. */
  4317. Matrix.Invert = function (source) {
  4318. var result = new Matrix();
  4319. source.invertToRef(result);
  4320. return result;
  4321. };
  4322. /**
  4323. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  4324. */
  4325. Matrix.RotationXToRef = function (angle, result) {
  4326. var s = Math.sin(angle);
  4327. var c = Math.cos(angle);
  4328. result.m[0] = 1.0;
  4329. result.m[15] = 1.0;
  4330. result.m[5] = c;
  4331. result.m[10] = c;
  4332. result.m[9] = -s;
  4333. result.m[6] = s;
  4334. result.m[1] = 0.0;
  4335. result.m[2] = 0.0;
  4336. result.m[3] = 0.0;
  4337. result.m[4] = 0.0;
  4338. result.m[7] = 0.0;
  4339. result.m[8] = 0.0;
  4340. result.m[11] = 0.0;
  4341. result.m[12] = 0.0;
  4342. result.m[13] = 0.0;
  4343. result.m[14] = 0.0;
  4344. result._markAsUpdated();
  4345. };
  4346. /**
  4347. * Returns a new rotation matrix for "angle" radians around the Y axis.
  4348. */
  4349. Matrix.RotationY = function (angle) {
  4350. var result = new Matrix();
  4351. Matrix.RotationYToRef(angle, result);
  4352. return result;
  4353. };
  4354. /**
  4355. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  4356. */
  4357. Matrix.RotationYToRef = function (angle, result) {
  4358. var s = Math.sin(angle);
  4359. var c = Math.cos(angle);
  4360. result.m[5] = 1.0;
  4361. result.m[15] = 1.0;
  4362. result.m[0] = c;
  4363. result.m[2] = -s;
  4364. result.m[8] = s;
  4365. result.m[10] = c;
  4366. result.m[1] = 0.0;
  4367. result.m[3] = 0.0;
  4368. result.m[4] = 0.0;
  4369. result.m[6] = 0.0;
  4370. result.m[7] = 0.0;
  4371. result.m[9] = 0.0;
  4372. result.m[11] = 0.0;
  4373. result.m[12] = 0.0;
  4374. result.m[13] = 0.0;
  4375. result.m[14] = 0.0;
  4376. result._markAsUpdated();
  4377. };
  4378. /**
  4379. * Returns a new rotation matrix for "angle" radians around the Z axis.
  4380. */
  4381. Matrix.RotationZ = function (angle) {
  4382. var result = new Matrix();
  4383. Matrix.RotationZToRef(angle, result);
  4384. return result;
  4385. };
  4386. /**
  4387. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  4388. */
  4389. Matrix.RotationZToRef = function (angle, result) {
  4390. var s = Math.sin(angle);
  4391. var c = Math.cos(angle);
  4392. result.m[10] = 1.0;
  4393. result.m[15] = 1.0;
  4394. result.m[0] = c;
  4395. result.m[1] = s;
  4396. result.m[4] = -s;
  4397. result.m[5] = c;
  4398. result.m[2] = 0.0;
  4399. result.m[3] = 0.0;
  4400. result.m[6] = 0.0;
  4401. result.m[7] = 0.0;
  4402. result.m[8] = 0.0;
  4403. result.m[9] = 0.0;
  4404. result.m[11] = 0.0;
  4405. result.m[12] = 0.0;
  4406. result.m[13] = 0.0;
  4407. result.m[14] = 0.0;
  4408. result._markAsUpdated();
  4409. };
  4410. /**
  4411. * Returns a new rotation matrix for "angle" radians around the passed axis.
  4412. */
  4413. Matrix.RotationAxis = function (axis, angle) {
  4414. var result = Matrix.Zero();
  4415. Matrix.RotationAxisToRef(axis, angle, result);
  4416. return result;
  4417. };
  4418. /**
  4419. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  4420. */
  4421. Matrix.RotationAxisToRef = function (axis, angle, result) {
  4422. var s = Math.sin(-angle);
  4423. var c = Math.cos(-angle);
  4424. var c1 = 1 - c;
  4425. axis.normalize();
  4426. result.m[0] = (axis.x * axis.x) * c1 + c;
  4427. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  4428. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  4429. result.m[3] = 0.0;
  4430. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  4431. result.m[5] = (axis.y * axis.y) * c1 + c;
  4432. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  4433. result.m[7] = 0.0;
  4434. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  4435. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  4436. result.m[10] = (axis.z * axis.z) * c1 + c;
  4437. result.m[11] = 0.0;
  4438. result.m[15] = 1.0;
  4439. result._markAsUpdated();
  4440. };
  4441. /**
  4442. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  4443. */
  4444. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4445. var result = new Matrix();
  4446. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  4447. return result;
  4448. };
  4449. /**
  4450. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  4451. */
  4452. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4453. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  4454. this._tempQuaternion.toRotationMatrix(result);
  4455. };
  4456. /**
  4457. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  4458. */
  4459. Matrix.Scaling = function (x, y, z) {
  4460. var result = Matrix.Zero();
  4461. Matrix.ScalingToRef(x, y, z, result);
  4462. return result;
  4463. };
  4464. /**
  4465. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  4466. */
  4467. Matrix.ScalingToRef = function (x, y, z, result) {
  4468. result.m[0] = x;
  4469. result.m[1] = 0.0;
  4470. result.m[2] = 0.0;
  4471. result.m[3] = 0.0;
  4472. result.m[4] = 0.0;
  4473. result.m[5] = y;
  4474. result.m[6] = 0.0;
  4475. result.m[7] = 0.0;
  4476. result.m[8] = 0.0;
  4477. result.m[9] = 0.0;
  4478. result.m[10] = z;
  4479. result.m[11] = 0.0;
  4480. result.m[12] = 0.0;
  4481. result.m[13] = 0.0;
  4482. result.m[14] = 0.0;
  4483. result.m[15] = 1.0;
  4484. result._markAsUpdated();
  4485. };
  4486. /**
  4487. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  4488. */
  4489. Matrix.Translation = function (x, y, z) {
  4490. var result = Matrix.Identity();
  4491. Matrix.TranslationToRef(x, y, z, result);
  4492. return result;
  4493. };
  4494. /**
  4495. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  4496. */
  4497. Matrix.TranslationToRef = function (x, y, z, result) {
  4498. 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);
  4499. };
  4500. /**
  4501. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  4502. */
  4503. Matrix.Lerp = function (startValue, endValue, gradient) {
  4504. var result = Matrix.Zero();
  4505. for (var index = 0; index < 16; index++) {
  4506. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  4507. }
  4508. result._markAsUpdated();
  4509. return result;
  4510. };
  4511. /**
  4512. * Returns a new Matrix whose values are computed by :
  4513. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  4514. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  4515. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  4516. */
  4517. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  4518. var startScale = new Vector3(0, 0, 0);
  4519. var startRotation = new Quaternion();
  4520. var startTranslation = new Vector3(0, 0, 0);
  4521. startValue.decompose(startScale, startRotation, startTranslation);
  4522. var endScale = new Vector3(0, 0, 0);
  4523. var endRotation = new Quaternion();
  4524. var endTranslation = new Vector3(0, 0, 0);
  4525. endValue.decompose(endScale, endRotation, endTranslation);
  4526. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  4527. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  4528. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  4529. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  4530. };
  4531. /**
  4532. * 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".
  4533. * This methods works for a Left-Handed system.
  4534. */
  4535. Matrix.LookAtLH = function (eye, target, up) {
  4536. var result = Matrix.Zero();
  4537. Matrix.LookAtLHToRef(eye, target, up, result);
  4538. return result;
  4539. };
  4540. /**
  4541. * 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".
  4542. * This methods works for a Left-Handed system.
  4543. */
  4544. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  4545. // Z axis
  4546. target.subtractToRef(eye, this._zAxis);
  4547. this._zAxis.normalize();
  4548. // X axis
  4549. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4550. if (this._xAxis.lengthSquared() === 0) {
  4551. this._xAxis.x = 1.0;
  4552. }
  4553. else {
  4554. this._xAxis.normalize();
  4555. }
  4556. // Y axis
  4557. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4558. this._yAxis.normalize();
  4559. // Eye angles
  4560. var ex = -Vector3.Dot(this._xAxis, eye);
  4561. var ey = -Vector3.Dot(this._yAxis, eye);
  4562. var ez = -Vector3.Dot(this._zAxis, eye);
  4563. 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);
  4564. };
  4565. /**
  4566. * 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".
  4567. * This methods works for a Right-Handed system.
  4568. */
  4569. Matrix.LookAtRH = function (eye, target, up) {
  4570. var result = Matrix.Zero();
  4571. Matrix.LookAtRHToRef(eye, target, up, result);
  4572. return result;
  4573. };
  4574. /**
  4575. * 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".
  4576. * This methods works for a Left-Handed system.
  4577. */
  4578. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  4579. // Z axis
  4580. eye.subtractToRef(target, this._zAxis);
  4581. this._zAxis.normalize();
  4582. // X axis
  4583. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4584. if (this._xAxis.lengthSquared() === 0) {
  4585. this._xAxis.x = 1.0;
  4586. }
  4587. else {
  4588. this._xAxis.normalize();
  4589. }
  4590. // Y axis
  4591. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4592. this._yAxis.normalize();
  4593. // Eye angles
  4594. var ex = -Vector3.Dot(this._xAxis, eye);
  4595. var ey = -Vector3.Dot(this._yAxis, eye);
  4596. var ez = -Vector3.Dot(this._zAxis, eye);
  4597. 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);
  4598. };
  4599. /**
  4600. * 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.
  4601. */
  4602. Matrix.OrthoLH = function (width, height, znear, zfar) {
  4603. var matrix = Matrix.Zero();
  4604. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  4605. return matrix;
  4606. };
  4607. /**
  4608. * 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.
  4609. */
  4610. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  4611. var n = znear;
  4612. var f = zfar;
  4613. var a = 2.0 / width;
  4614. var b = 2.0 / height;
  4615. var c = 2.0 / (f - n);
  4616. var d = -(f + n) / (f - n);
  4617. 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);
  4618. };
  4619. /**
  4620. * 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.
  4621. */
  4622. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  4623. var matrix = Matrix.Zero();
  4624. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  4625. return matrix;
  4626. };
  4627. /**
  4628. * 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.
  4629. */
  4630. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4631. var n = znear;
  4632. var f = zfar;
  4633. var a = 2.0 / (right - left);
  4634. var b = 2.0 / (top - bottom);
  4635. var c = 2.0 / (f - n);
  4636. var d = -(f + n) / (f - n);
  4637. var i0 = (left + right) / (left - right);
  4638. var i1 = (top + bottom) / (bottom - top);
  4639. 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);
  4640. };
  4641. /**
  4642. * 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.
  4643. */
  4644. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  4645. var matrix = Matrix.Zero();
  4646. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  4647. return matrix;
  4648. };
  4649. /**
  4650. * 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.
  4651. */
  4652. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4653. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  4654. result.m[10] *= -1.0;
  4655. };
  4656. /**
  4657. * 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.
  4658. */
  4659. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  4660. var matrix = Matrix.Zero();
  4661. var n = znear;
  4662. var f = zfar;
  4663. var a = 2.0 * n / width;
  4664. var b = 2.0 * n / height;
  4665. var c = (f + n) / (f - n);
  4666. var d = -2.0 * f * n / (f - n);
  4667. 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);
  4668. return matrix;
  4669. };
  4670. /**
  4671. * 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.
  4672. */
  4673. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  4674. var matrix = Matrix.Zero();
  4675. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  4676. return matrix;
  4677. };
  4678. /**
  4679. * 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.
  4680. */
  4681. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4682. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4683. var n = znear;
  4684. var f = zfar;
  4685. var t = 1.0 / (Math.tan(fov * 0.5));
  4686. var a = isVerticalFovFixed ? (t / aspect) : t;
  4687. var b = isVerticalFovFixed ? t : (t * aspect);
  4688. var c = (f + n) / (f - n);
  4689. var d = -2.0 * f * n / (f - n);
  4690. 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);
  4691. };
  4692. /**
  4693. * 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.
  4694. */
  4695. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  4696. var matrix = Matrix.Zero();
  4697. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  4698. return matrix;
  4699. };
  4700. /**
  4701. * 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.
  4702. */
  4703. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4704. //alternatively this could be expressed as:
  4705. // m = PerspectiveFovLHToRef
  4706. // m[10] *= -1.0;
  4707. // m[11] *= -1.0;
  4708. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4709. var n = znear;
  4710. var f = zfar;
  4711. var t = 1.0 / (Math.tan(fov * 0.5));
  4712. var a = isVerticalFovFixed ? (t / aspect) : t;
  4713. var b = isVerticalFovFixed ? t : (t * aspect);
  4714. var c = -(f + n) / (f - n);
  4715. var d = -2 * f * n / (f - n);
  4716. 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);
  4717. };
  4718. /**
  4719. * 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.
  4720. */
  4721. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  4722. if (rightHanded === void 0) { rightHanded = false; }
  4723. var rightHandedFactor = rightHanded ? -1 : 1;
  4724. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  4725. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  4726. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  4727. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  4728. var xScale = 2.0 / (leftTan + rightTan);
  4729. var yScale = 2.0 / (upTan + downTan);
  4730. result.m[0] = xScale;
  4731. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  4732. result.m[5] = yScale;
  4733. result.m[6] = result.m[7] = 0.0;
  4734. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  4735. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  4736. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  4737. result.m[10] = -zfar / (znear - zfar);
  4738. result.m[11] = 1.0 * rightHandedFactor;
  4739. result.m[12] = result.m[13] = result.m[15] = 0.0;
  4740. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  4741. // result.m[14] = (znear * zfar) / (znear - zfar);
  4742. result._markAsUpdated();
  4743. };
  4744. /**
  4745. * Returns the final transformation matrix : world * view * projection * viewport
  4746. */
  4747. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  4748. var cw = viewport.width;
  4749. var ch = viewport.height;
  4750. var cx = viewport.x;
  4751. var cy = viewport.y;
  4752. 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);
  4753. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  4754. };
  4755. /**
  4756. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  4757. */
  4758. Matrix.GetAsMatrix2x2 = function (matrix) {
  4759. return new Float32Array([
  4760. matrix.m[0], matrix.m[1],
  4761. matrix.m[4], matrix.m[5]
  4762. ]);
  4763. };
  4764. /**
  4765. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  4766. */
  4767. Matrix.GetAsMatrix3x3 = function (matrix) {
  4768. return new Float32Array([
  4769. matrix.m[0], matrix.m[1], matrix.m[2],
  4770. matrix.m[4], matrix.m[5], matrix.m[6],
  4771. matrix.m[8], matrix.m[9], matrix.m[10]
  4772. ]);
  4773. };
  4774. /**
  4775. * Compute the transpose of the passed Matrix.
  4776. * Returns a new Matrix.
  4777. */
  4778. Matrix.Transpose = function (matrix) {
  4779. var result = new Matrix();
  4780. Matrix.TransposeToRef(matrix, result);
  4781. return result;
  4782. };
  4783. /**
  4784. * Compute the transpose of the passed Matrix and store it in the result matrix.
  4785. */
  4786. Matrix.TransposeToRef = function (matrix, result) {
  4787. result.m[0] = matrix.m[0];
  4788. result.m[1] = matrix.m[4];
  4789. result.m[2] = matrix.m[8];
  4790. result.m[3] = matrix.m[12];
  4791. result.m[4] = matrix.m[1];
  4792. result.m[5] = matrix.m[5];
  4793. result.m[6] = matrix.m[9];
  4794. result.m[7] = matrix.m[13];
  4795. result.m[8] = matrix.m[2];
  4796. result.m[9] = matrix.m[6];
  4797. result.m[10] = matrix.m[10];
  4798. result.m[11] = matrix.m[14];
  4799. result.m[12] = matrix.m[3];
  4800. result.m[13] = matrix.m[7];
  4801. result.m[14] = matrix.m[11];
  4802. result.m[15] = matrix.m[15];
  4803. };
  4804. /**
  4805. * Returns a new Matrix as the reflection matrix across the passed plane.
  4806. */
  4807. Matrix.Reflection = function (plane) {
  4808. var matrix = new Matrix();
  4809. Matrix.ReflectionToRef(plane, matrix);
  4810. return matrix;
  4811. };
  4812. /**
  4813. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  4814. */
  4815. Matrix.ReflectionToRef = function (plane, result) {
  4816. plane.normalize();
  4817. var x = plane.normal.x;
  4818. var y = plane.normal.y;
  4819. var z = plane.normal.z;
  4820. var temp = -2 * x;
  4821. var temp2 = -2 * y;
  4822. var temp3 = -2 * z;
  4823. result.m[0] = (temp * x) + 1;
  4824. result.m[1] = temp2 * x;
  4825. result.m[2] = temp3 * x;
  4826. result.m[3] = 0.0;
  4827. result.m[4] = temp * y;
  4828. result.m[5] = (temp2 * y) + 1;
  4829. result.m[6] = temp3 * y;
  4830. result.m[7] = 0.0;
  4831. result.m[8] = temp * z;
  4832. result.m[9] = temp2 * z;
  4833. result.m[10] = (temp3 * z) + 1;
  4834. result.m[11] = 0.0;
  4835. result.m[12] = temp * plane.d;
  4836. result.m[13] = temp2 * plane.d;
  4837. result.m[14] = temp3 * plane.d;
  4838. result.m[15] = 1.0;
  4839. result._markAsUpdated();
  4840. };
  4841. /**
  4842. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  4843. */
  4844. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  4845. result.m[0] = xaxis.x;
  4846. result.m[1] = xaxis.y;
  4847. result.m[2] = xaxis.z;
  4848. result.m[3] = 0.0;
  4849. result.m[4] = yaxis.x;
  4850. result.m[5] = yaxis.y;
  4851. result.m[6] = yaxis.z;
  4852. result.m[7] = 0.0;
  4853. result.m[8] = zaxis.x;
  4854. result.m[9] = zaxis.y;
  4855. result.m[10] = zaxis.z;
  4856. result.m[11] = 0.0;
  4857. result.m[12] = 0.0;
  4858. result.m[13] = 0.0;
  4859. result.m[14] = 0.0;
  4860. result.m[15] = 1.0;
  4861. result._markAsUpdated();
  4862. };
  4863. /**
  4864. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  4865. */
  4866. Matrix.FromQuaternionToRef = function (quat, result) {
  4867. var xx = quat.x * quat.x;
  4868. var yy = quat.y * quat.y;
  4869. var zz = quat.z * quat.z;
  4870. var xy = quat.x * quat.y;
  4871. var zw = quat.z * quat.w;
  4872. var zx = quat.z * quat.x;
  4873. var yw = quat.y * quat.w;
  4874. var yz = quat.y * quat.z;
  4875. var xw = quat.x * quat.w;
  4876. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4877. result.m[1] = 2.0 * (xy + zw);
  4878. result.m[2] = 2.0 * (zx - yw);
  4879. result.m[3] = 0.0;
  4880. result.m[4] = 2.0 * (xy - zw);
  4881. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4882. result.m[6] = 2.0 * (yz + xw);
  4883. result.m[7] = 0.0;
  4884. result.m[8] = 2.0 * (zx + yw);
  4885. result.m[9] = 2.0 * (yz - xw);
  4886. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4887. result.m[11] = 0.0;
  4888. result.m[12] = 0.0;
  4889. result.m[13] = 0.0;
  4890. result.m[14] = 0.0;
  4891. result.m[15] = 1.0;
  4892. result._markAsUpdated();
  4893. };
  4894. Matrix._tempQuaternion = new Quaternion();
  4895. Matrix._xAxis = Vector3.Zero();
  4896. Matrix._yAxis = Vector3.Zero();
  4897. Matrix._zAxis = Vector3.Zero();
  4898. Matrix._updateFlagSeed = 0;
  4899. Matrix._identityReadOnly = Matrix.Identity();
  4900. return Matrix;
  4901. }());
  4902. BABYLON.Matrix = Matrix;
  4903. var Plane = /** @class */ (function () {
  4904. /**
  4905. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  4906. */
  4907. function Plane(a, b, c, d) {
  4908. this.normal = new Vector3(a, b, c);
  4909. this.d = d;
  4910. }
  4911. /**
  4912. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4913. */
  4914. Plane.prototype.asArray = function () {
  4915. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4916. };
  4917. // Methods
  4918. /**
  4919. * Returns a new plane copied from the current Plane.
  4920. */
  4921. Plane.prototype.clone = function () {
  4922. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4923. };
  4924. /**
  4925. * Returns the string "Plane".
  4926. */
  4927. Plane.prototype.getClassName = function () {
  4928. return "Plane";
  4929. };
  4930. /**
  4931. * Returns the Plane hash code.
  4932. */
  4933. Plane.prototype.getHashCode = function () {
  4934. var hash = this.normal.getHashCode();
  4935. hash = (hash * 397) ^ (this.d || 0);
  4936. return hash;
  4937. };
  4938. /**
  4939. * Normalize the current Plane in place.
  4940. * Returns the updated Plane.
  4941. */
  4942. Plane.prototype.normalize = function () {
  4943. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  4944. var magnitude = 0.0;
  4945. if (norm !== 0) {
  4946. magnitude = 1.0 / norm;
  4947. }
  4948. this.normal.x *= magnitude;
  4949. this.normal.y *= magnitude;
  4950. this.normal.z *= magnitude;
  4951. this.d *= magnitude;
  4952. return this;
  4953. };
  4954. /**
  4955. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  4956. */
  4957. Plane.prototype.transform = function (transformation) {
  4958. var transposedMatrix = Matrix.Transpose(transformation);
  4959. var x = this.normal.x;
  4960. var y = this.normal.y;
  4961. var z = this.normal.z;
  4962. var d = this.d;
  4963. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  4964. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  4965. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  4966. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  4967. return new Plane(normalX, normalY, normalZ, finalD);
  4968. };
  4969. /**
  4970. * Returns the dot product (float) of the point coordinates and the plane normal.
  4971. */
  4972. Plane.prototype.dotCoordinate = function (point) {
  4973. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  4974. };
  4975. /**
  4976. * Updates the current Plane from the plane defined by the three passed points.
  4977. * Returns the updated Plane.
  4978. */
  4979. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  4980. var x1 = point2.x - point1.x;
  4981. var y1 = point2.y - point1.y;
  4982. var z1 = point2.z - point1.z;
  4983. var x2 = point3.x - point1.x;
  4984. var y2 = point3.y - point1.y;
  4985. var z2 = point3.z - point1.z;
  4986. var yz = (y1 * z2) - (z1 * y2);
  4987. var xz = (z1 * x2) - (x1 * z2);
  4988. var xy = (x1 * y2) - (y1 * x2);
  4989. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  4990. var invPyth;
  4991. if (pyth !== 0) {
  4992. invPyth = 1.0 / pyth;
  4993. }
  4994. else {
  4995. invPyth = 0.0;
  4996. }
  4997. this.normal.x = yz * invPyth;
  4998. this.normal.y = xz * invPyth;
  4999. this.normal.z = xy * invPyth;
  5000. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5001. return this;
  5002. };
  5003. /**
  5004. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5005. */
  5006. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5007. var dot = Vector3.Dot(this.normal, direction);
  5008. return (dot <= epsilon);
  5009. };
  5010. /**
  5011. * Returns the signed distance (float) from the passed point to the Plane.
  5012. */
  5013. Plane.prototype.signedDistanceTo = function (point) {
  5014. return Vector3.Dot(point, this.normal) + this.d;
  5015. };
  5016. // Statics
  5017. /**
  5018. * Returns a new Plane from the passed array.
  5019. */
  5020. Plane.FromArray = function (array) {
  5021. return new Plane(array[0], array[1], array[2], array[3]);
  5022. };
  5023. /**
  5024. * Returns a new Plane defined by the three passed points.
  5025. */
  5026. Plane.FromPoints = function (point1, point2, point3) {
  5027. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5028. result.copyFromPoints(point1, point2, point3);
  5029. return result;
  5030. };
  5031. /**
  5032. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5033. * Note : the vector "normal" is updated because normalized.
  5034. */
  5035. Plane.FromPositionAndNormal = function (origin, normal) {
  5036. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5037. normal.normalize();
  5038. result.normal = normal;
  5039. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5040. return result;
  5041. };
  5042. /**
  5043. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5044. */
  5045. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5046. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5047. return Vector3.Dot(point, normal) + d;
  5048. };
  5049. return Plane;
  5050. }());
  5051. BABYLON.Plane = Plane;
  5052. var Viewport = /** @class */ (function () {
  5053. /**
  5054. * Creates a Viewport object located at (x, y) and sized (width, height).
  5055. */
  5056. function Viewport(x, y, width, height) {
  5057. this.x = x;
  5058. this.y = y;
  5059. this.width = width;
  5060. this.height = height;
  5061. }
  5062. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5063. if (renderWidthOrEngine.getRenderWidth) {
  5064. var engine = renderWidthOrEngine;
  5065. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5066. }
  5067. var renderWidth = renderWidthOrEngine;
  5068. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5069. };
  5070. /**
  5071. * Returns a new Viewport copied from the current one.
  5072. */
  5073. Viewport.prototype.clone = function () {
  5074. return new Viewport(this.x, this.y, this.width, this.height);
  5075. };
  5076. return Viewport;
  5077. }());
  5078. BABYLON.Viewport = Viewport;
  5079. var Frustum = /** @class */ (function () {
  5080. function Frustum() {
  5081. }
  5082. /**
  5083. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5084. */
  5085. Frustum.GetPlanes = function (transform) {
  5086. var frustumPlanes = [];
  5087. for (var index = 0; index < 6; index++) {
  5088. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5089. }
  5090. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5091. return frustumPlanes;
  5092. };
  5093. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5094. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5095. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5096. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5097. frustumPlane.d = transform.m[15] + transform.m[14];
  5098. frustumPlane.normalize();
  5099. };
  5100. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5101. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5102. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5103. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5104. frustumPlane.d = transform.m[15] - transform.m[14];
  5105. frustumPlane.normalize();
  5106. };
  5107. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5108. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5109. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5110. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5111. frustumPlane.d = transform.m[15] + transform.m[12];
  5112. frustumPlane.normalize();
  5113. };
  5114. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5115. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5116. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5117. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  5118. frustumPlane.d = transform.m[15] - transform.m[12];
  5119. frustumPlane.normalize();
  5120. };
  5121. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  5122. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  5123. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  5124. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  5125. frustumPlane.d = transform.m[15] - transform.m[13];
  5126. frustumPlane.normalize();
  5127. };
  5128. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  5129. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  5130. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  5131. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  5132. frustumPlane.d = transform.m[15] + transform.m[13];
  5133. frustumPlane.normalize();
  5134. };
  5135. /**
  5136. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  5137. */
  5138. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  5139. // Near
  5140. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  5141. // Far
  5142. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  5143. // Left
  5144. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  5145. // Right
  5146. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  5147. // Top
  5148. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  5149. // Bottom
  5150. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  5151. };
  5152. return Frustum;
  5153. }());
  5154. BABYLON.Frustum = Frustum;
  5155. var Space;
  5156. (function (Space) {
  5157. Space[Space["LOCAL"] = 0] = "LOCAL";
  5158. Space[Space["WORLD"] = 1] = "WORLD";
  5159. Space[Space["BONE"] = 2] = "BONE";
  5160. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  5161. var Axis = /** @class */ (function () {
  5162. function Axis() {
  5163. }
  5164. Axis.X = new Vector3(1.0, 0.0, 0.0);
  5165. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  5166. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  5167. return Axis;
  5168. }());
  5169. BABYLON.Axis = Axis;
  5170. ;
  5171. var BezierCurve = /** @class */ (function () {
  5172. function BezierCurve() {
  5173. }
  5174. /**
  5175. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  5176. */
  5177. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  5178. // Extract X (which is equal to time here)
  5179. var f0 = 1 - 3 * x2 + 3 * x1;
  5180. var f1 = 3 * x2 - 6 * x1;
  5181. var f2 = 3 * x1;
  5182. var refinedT = t;
  5183. for (var i = 0; i < 5; i++) {
  5184. var refinedT2 = refinedT * refinedT;
  5185. var refinedT3 = refinedT2 * refinedT;
  5186. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  5187. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  5188. refinedT -= (x - t) * slope;
  5189. refinedT = Math.min(1, Math.max(0, refinedT));
  5190. }
  5191. // Resolve cubic bezier for the given x
  5192. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  5193. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  5194. Math.pow(refinedT, 3);
  5195. };
  5196. return BezierCurve;
  5197. }());
  5198. BABYLON.BezierCurve = BezierCurve;
  5199. var Orientation;
  5200. (function (Orientation) {
  5201. Orientation[Orientation["CW"] = 0] = "CW";
  5202. Orientation[Orientation["CCW"] = 1] = "CCW";
  5203. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  5204. var Angle = /** @class */ (function () {
  5205. /**
  5206. * Creates an Angle object of "radians" radians (float).
  5207. */
  5208. function Angle(radians) {
  5209. var _this = this;
  5210. /**
  5211. * Returns the Angle value in degrees (float).
  5212. */
  5213. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  5214. /**
  5215. * Returns the Angle value in radians (float).
  5216. */
  5217. this.radians = function () { return _this._radians; };
  5218. this._radians = radians;
  5219. if (this._radians < 0.0)
  5220. this._radians += (2.0 * Math.PI);
  5221. }
  5222. /**
  5223. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  5224. */
  5225. Angle.BetweenTwoPoints = function (a, b) {
  5226. var delta = b.subtract(a);
  5227. var theta = Math.atan2(delta.y, delta.x);
  5228. return new Angle(theta);
  5229. };
  5230. /**
  5231. * Returns a new Angle object from the passed float in radians.
  5232. */
  5233. Angle.FromRadians = function (radians) {
  5234. return new Angle(radians);
  5235. };
  5236. /**
  5237. * Returns a new Angle object from the passed float in degrees.
  5238. */
  5239. Angle.FromDegrees = function (degrees) {
  5240. return new Angle(degrees * Math.PI / 180.0);
  5241. };
  5242. return Angle;
  5243. }());
  5244. BABYLON.Angle = Angle;
  5245. var Arc2 = /** @class */ (function () {
  5246. /**
  5247. * Creates an Arc object from the three passed points : start, middle and end.
  5248. */
  5249. function Arc2(startPoint, midPoint, endPoint) {
  5250. this.startPoint = startPoint;
  5251. this.midPoint = midPoint;
  5252. this.endPoint = endPoint;
  5253. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  5254. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  5255. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  5256. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  5257. 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);
  5258. this.radius = this.centerPoint.subtract(this.startPoint).length();
  5259. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  5260. var a1 = this.startAngle.degrees();
  5261. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  5262. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  5263. // angles correction
  5264. if (a2 - a1 > +180.0)
  5265. a2 -= 360.0;
  5266. if (a2 - a1 < -180.0)
  5267. a2 += 360.0;
  5268. if (a3 - a2 > +180.0)
  5269. a3 -= 360.0;
  5270. if (a3 - a2 < -180.0)
  5271. a3 += 360.0;
  5272. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  5273. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  5274. }
  5275. return Arc2;
  5276. }());
  5277. BABYLON.Arc2 = Arc2;
  5278. var Path2 = /** @class */ (function () {
  5279. /**
  5280. * Creates a Path2 object from the starting 2D coordinates x and y.
  5281. */
  5282. function Path2(x, y) {
  5283. this._points = new Array();
  5284. this._length = 0.0;
  5285. this.closed = false;
  5286. this._points.push(new Vector2(x, y));
  5287. }
  5288. /**
  5289. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  5290. * Returns the updated Path2.
  5291. */
  5292. Path2.prototype.addLineTo = function (x, y) {
  5293. if (this.closed) {
  5294. //Tools.Error("cannot add lines to closed paths");
  5295. return this;
  5296. }
  5297. var newPoint = new Vector2(x, y);
  5298. var previousPoint = this._points[this._points.length - 1];
  5299. this._points.push(newPoint);
  5300. this._length += newPoint.subtract(previousPoint).length();
  5301. return this;
  5302. };
  5303. /**
  5304. * 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.
  5305. * Returns the updated Path2.
  5306. */
  5307. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  5308. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  5309. if (this.closed) {
  5310. //Tools.Error("cannot add arcs to closed paths");
  5311. return this;
  5312. }
  5313. var startPoint = this._points[this._points.length - 1];
  5314. var midPoint = new Vector2(midX, midY);
  5315. var endPoint = new Vector2(endX, endY);
  5316. var arc = new Arc2(startPoint, midPoint, endPoint);
  5317. var increment = arc.angle.radians() / numberOfSegments;
  5318. if (arc.orientation === Orientation.CW)
  5319. increment *= -1;
  5320. var currentAngle = arc.startAngle.radians() + increment;
  5321. for (var i = 0; i < numberOfSegments; i++) {
  5322. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  5323. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  5324. this.addLineTo(x, y);
  5325. currentAngle += increment;
  5326. }
  5327. return this;
  5328. };
  5329. /**
  5330. * Closes the Path2.
  5331. * Returns the Path2.
  5332. */
  5333. Path2.prototype.close = function () {
  5334. this.closed = true;
  5335. return this;
  5336. };
  5337. /**
  5338. * Returns the Path2 total length (float).
  5339. */
  5340. Path2.prototype.length = function () {
  5341. var result = this._length;
  5342. if (!this.closed) {
  5343. var lastPoint = this._points[this._points.length - 1];
  5344. var firstPoint = this._points[0];
  5345. result += (firstPoint.subtract(lastPoint).length());
  5346. }
  5347. return result;
  5348. };
  5349. /**
  5350. * Returns the Path2 internal array of points.
  5351. */
  5352. Path2.prototype.getPoints = function () {
  5353. return this._points;
  5354. };
  5355. /**
  5356. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  5357. */
  5358. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  5359. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  5360. //Tools.Error("normalized length position should be between 0 and 1.");
  5361. return Vector2.Zero();
  5362. }
  5363. var lengthPosition = normalizedLengthPosition * this.length();
  5364. var previousOffset = 0;
  5365. for (var i = 0; i < this._points.length; i++) {
  5366. var j = (i + 1) % this._points.length;
  5367. var a = this._points[i];
  5368. var b = this._points[j];
  5369. var bToA = b.subtract(a);
  5370. var nextOffset = (bToA.length() + previousOffset);
  5371. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  5372. var dir = bToA.normalize();
  5373. var localOffset = lengthPosition - previousOffset;
  5374. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  5375. }
  5376. previousOffset = nextOffset;
  5377. }
  5378. //Tools.Error("internal error");
  5379. return Vector2.Zero();
  5380. };
  5381. /**
  5382. * Returns a new Path2 starting at the coordinates (x, y).
  5383. */
  5384. Path2.StartingAt = function (x, y) {
  5385. return new Path2(x, y);
  5386. };
  5387. return Path2;
  5388. }());
  5389. BABYLON.Path2 = Path2;
  5390. var Path3D = /** @class */ (function () {
  5391. /**
  5392. * new Path3D(path, normal, raw)
  5393. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  5394. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  5395. * path : an array of Vector3, the curve axis of the Path3D
  5396. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  5397. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  5398. */
  5399. function Path3D(path, firstNormal, raw) {
  5400. if (firstNormal === void 0) { firstNormal = null; }
  5401. this.path = path;
  5402. this._curve = new Array();
  5403. this._distances = new Array();
  5404. this._tangents = new Array();
  5405. this._normals = new Array();
  5406. this._binormals = new Array();
  5407. for (var p = 0; p < path.length; p++) {
  5408. this._curve[p] = path[p].clone(); // hard copy
  5409. }
  5410. this._raw = raw || false;
  5411. this._compute(firstNormal);
  5412. }
  5413. /**
  5414. * Returns the Path3D array of successive Vector3 designing its curve.
  5415. */
  5416. Path3D.prototype.getCurve = function () {
  5417. return this._curve;
  5418. };
  5419. /**
  5420. * Returns an array populated with tangent vectors on each Path3D curve point.
  5421. */
  5422. Path3D.prototype.getTangents = function () {
  5423. return this._tangents;
  5424. };
  5425. /**
  5426. * Returns an array populated with normal vectors on each Path3D curve point.
  5427. */
  5428. Path3D.prototype.getNormals = function () {
  5429. return this._normals;
  5430. };
  5431. /**
  5432. * Returns an array populated with binormal vectors on each Path3D curve point.
  5433. */
  5434. Path3D.prototype.getBinormals = function () {
  5435. return this._binormals;
  5436. };
  5437. /**
  5438. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  5439. */
  5440. Path3D.prototype.getDistances = function () {
  5441. return this._distances;
  5442. };
  5443. /**
  5444. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  5445. * Returns the same object updated.
  5446. */
  5447. Path3D.prototype.update = function (path, firstNormal) {
  5448. if (firstNormal === void 0) { firstNormal = null; }
  5449. for (var p = 0; p < path.length; p++) {
  5450. this._curve[p].x = path[p].x;
  5451. this._curve[p].y = path[p].y;
  5452. this._curve[p].z = path[p].z;
  5453. }
  5454. this._compute(firstNormal);
  5455. return this;
  5456. };
  5457. // private function compute() : computes tangents, normals and binormals
  5458. Path3D.prototype._compute = function (firstNormal) {
  5459. var l = this._curve.length;
  5460. // first and last tangents
  5461. this._tangents[0] = this._getFirstNonNullVector(0);
  5462. if (!this._raw) {
  5463. this._tangents[0].normalize();
  5464. }
  5465. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  5466. if (!this._raw) {
  5467. this._tangents[l - 1].normalize();
  5468. }
  5469. // normals and binormals at first point : arbitrary vector with _normalVector()
  5470. var tg0 = this._tangents[0];
  5471. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  5472. this._normals[0] = pp0;
  5473. if (!this._raw) {
  5474. this._normals[0].normalize();
  5475. }
  5476. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  5477. if (!this._raw) {
  5478. this._binormals[0].normalize();
  5479. }
  5480. this._distances[0] = 0.0;
  5481. // normals and binormals : next points
  5482. var prev; // previous vector (segment)
  5483. var cur; // current vector (segment)
  5484. var curTang; // current tangent
  5485. // previous normal
  5486. var prevBinor; // previous binormal
  5487. for (var i = 1; i < l; i++) {
  5488. // tangents
  5489. prev = this._getLastNonNullVector(i);
  5490. if (i < l - 1) {
  5491. cur = this._getFirstNonNullVector(i);
  5492. this._tangents[i] = prev.add(cur);
  5493. this._tangents[i].normalize();
  5494. }
  5495. this._distances[i] = this._distances[i - 1] + prev.length();
  5496. // normals and binormals
  5497. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  5498. curTang = this._tangents[i];
  5499. prevBinor = this._binormals[i - 1];
  5500. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  5501. if (!this._raw) {
  5502. this._normals[i].normalize();
  5503. }
  5504. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  5505. if (!this._raw) {
  5506. this._binormals[i].normalize();
  5507. }
  5508. }
  5509. };
  5510. // private function getFirstNonNullVector(index)
  5511. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  5512. Path3D.prototype._getFirstNonNullVector = function (index) {
  5513. var i = 1;
  5514. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  5515. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  5516. i++;
  5517. nNVector = this._curve[index + i].subtract(this._curve[index]);
  5518. }
  5519. return nNVector;
  5520. };
  5521. // private function getLastNonNullVector(index)
  5522. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  5523. Path3D.prototype._getLastNonNullVector = function (index) {
  5524. var i = 1;
  5525. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  5526. while (nLVector.length() === 0 && index > i + 1) {
  5527. i++;
  5528. nLVector = this._curve[index].subtract(this._curve[index - i]);
  5529. }
  5530. return nLVector;
  5531. };
  5532. // private function normalVector(v0, vt, va) :
  5533. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  5534. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  5535. Path3D.prototype._normalVector = function (v0, vt, va) {
  5536. var normal0;
  5537. var tgl = vt.length();
  5538. if (tgl === 0.0) {
  5539. tgl = 1.0;
  5540. }
  5541. if (va === undefined || va === null) {
  5542. var point;
  5543. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  5544. point = new Vector3(0.0, -1.0, 0.0);
  5545. }
  5546. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  5547. point = new Vector3(1.0, 0.0, 0.0);
  5548. }
  5549. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  5550. point = new Vector3(0.0, 0.0, 1.0);
  5551. }
  5552. else {
  5553. point = Vector3.Zero();
  5554. }
  5555. normal0 = Vector3.Cross(vt, point);
  5556. }
  5557. else {
  5558. normal0 = Vector3.Cross(vt, va);
  5559. Vector3.CrossToRef(normal0, vt, normal0);
  5560. }
  5561. normal0.normalize();
  5562. return normal0;
  5563. };
  5564. return Path3D;
  5565. }());
  5566. BABYLON.Path3D = Path3D;
  5567. var Curve3 = /** @class */ (function () {
  5568. /**
  5569. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  5570. * A Curve3 is designed from a series of successive Vector3.
  5571. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  5572. */
  5573. function Curve3(points) {
  5574. this._length = 0.0;
  5575. this._points = points;
  5576. this._length = this._computeLength(points);
  5577. }
  5578. /**
  5579. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  5580. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  5581. * @param v1 (Vector3) the control point
  5582. * @param v2 (Vector3) the end point of the Quadratic Bezier
  5583. * @param nbPoints (integer) the wanted number of points in the curve
  5584. */
  5585. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  5586. nbPoints = nbPoints > 2 ? nbPoints : 3;
  5587. var bez = new Array();
  5588. var equation = function (t, val0, val1, val2) {
  5589. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  5590. return res;
  5591. };
  5592. for (var i = 0; i <= nbPoints; i++) {
  5593. 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)));
  5594. }
  5595. return new Curve3(bez);
  5596. };
  5597. /**
  5598. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  5599. * @param v0 (Vector3) the origin point of the Cubic Bezier
  5600. * @param v1 (Vector3) the first control point
  5601. * @param v2 (Vector3) the second control point
  5602. * @param v3 (Vector3) the end point of the Cubic Bezier
  5603. * @param nbPoints (integer) the wanted number of points in the curve
  5604. */
  5605. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  5606. nbPoints = nbPoints > 3 ? nbPoints : 4;
  5607. var bez = new Array();
  5608. var equation = function (t, val0, val1, val2, val3) {
  5609. 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;
  5610. return res;
  5611. };
  5612. for (var i = 0; i <= nbPoints; i++) {
  5613. 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)));
  5614. }
  5615. return new Curve3(bez);
  5616. };
  5617. /**
  5618. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  5619. * @param p1 (Vector3) the origin point of the Hermite Spline
  5620. * @param t1 (Vector3) the tangent vector at the origin point
  5621. * @param p2 (Vector3) the end point of the Hermite Spline
  5622. * @param t2 (Vector3) the tangent vector at the end point
  5623. * @param nbPoints (integer) the wanted number of points in the curve
  5624. */
  5625. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  5626. var hermite = new Array();
  5627. var step = 1.0 / nbPoints;
  5628. for (var i = 0; i <= nbPoints; i++) {
  5629. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  5630. }
  5631. return new Curve3(hermite);
  5632. };
  5633. /**
  5634. * Returns a Curve3 object along a CatmullRom Spline curve :
  5635. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  5636. * @param nbPoints (integer) the wanted number of points between each curve control points.
  5637. */
  5638. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  5639. var totalPoints = new Array();
  5640. totalPoints.push(points[0].clone());
  5641. Array.prototype.push.apply(totalPoints, points);
  5642. totalPoints.push(points[points.length - 1].clone());
  5643. var catmullRom = new Array();
  5644. var step = 1.0 / nbPoints;
  5645. var amount = 0.0;
  5646. for (var i = 0; i < totalPoints.length - 3; i++) {
  5647. amount = 0;
  5648. for (var c = 0; c < nbPoints; c++) {
  5649. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5650. amount += step;
  5651. }
  5652. }
  5653. i--;
  5654. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5655. return new Curve3(catmullRom);
  5656. };
  5657. /**
  5658. * Returns the Curve3 stored array of successive Vector3
  5659. */
  5660. Curve3.prototype.getPoints = function () {
  5661. return this._points;
  5662. };
  5663. /**
  5664. * Returns the computed length (float) of the curve.
  5665. */
  5666. Curve3.prototype.length = function () {
  5667. return this._length;
  5668. };
  5669. /**
  5670. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  5671. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  5672. * curveA and curveB keep unchanged.
  5673. */
  5674. Curve3.prototype.continue = function (curve) {
  5675. var lastPoint = this._points[this._points.length - 1];
  5676. var continuedPoints = this._points.slice();
  5677. var curvePoints = curve.getPoints();
  5678. for (var i = 1; i < curvePoints.length; i++) {
  5679. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  5680. }
  5681. var continuedCurve = new Curve3(continuedPoints);
  5682. return continuedCurve;
  5683. };
  5684. Curve3.prototype._computeLength = function (path) {
  5685. var l = 0;
  5686. for (var i = 1; i < path.length; i++) {
  5687. l += (path[i].subtract(path[i - 1])).length();
  5688. }
  5689. return l;
  5690. };
  5691. return Curve3;
  5692. }());
  5693. BABYLON.Curve3 = Curve3;
  5694. // Vertex formats
  5695. var PositionNormalVertex = /** @class */ (function () {
  5696. function PositionNormalVertex(position, normal) {
  5697. if (position === void 0) { position = Vector3.Zero(); }
  5698. if (normal === void 0) { normal = Vector3.Up(); }
  5699. this.position = position;
  5700. this.normal = normal;
  5701. }
  5702. PositionNormalVertex.prototype.clone = function () {
  5703. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  5704. };
  5705. return PositionNormalVertex;
  5706. }());
  5707. BABYLON.PositionNormalVertex = PositionNormalVertex;
  5708. var PositionNormalTextureVertex = /** @class */ (function () {
  5709. function PositionNormalTextureVertex(position, normal, uv) {
  5710. if (position === void 0) { position = Vector3.Zero(); }
  5711. if (normal === void 0) { normal = Vector3.Up(); }
  5712. if (uv === void 0) { uv = Vector2.Zero(); }
  5713. this.position = position;
  5714. this.normal = normal;
  5715. this.uv = uv;
  5716. }
  5717. PositionNormalTextureVertex.prototype.clone = function () {
  5718. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  5719. };
  5720. return PositionNormalTextureVertex;
  5721. }());
  5722. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  5723. // Temporary pre-allocated objects for engine internal use
  5724. // usage in any internal function :
  5725. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  5726. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  5727. var Tmp = /** @class */ (function () {
  5728. function Tmp() {
  5729. }
  5730. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  5731. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  5732. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  5733. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  5734. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  5735. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  5736. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  5737. Matrix.Zero(), Matrix.Zero(),
  5738. Matrix.Zero(), Matrix.Zero(),
  5739. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  5740. return Tmp;
  5741. }());
  5742. BABYLON.Tmp = Tmp;
  5743. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  5744. var MathTmp = /** @class */ (function () {
  5745. function MathTmp() {
  5746. }
  5747. MathTmp.Vector3 = [Vector3.Zero()];
  5748. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  5749. MathTmp.Quaternion = [Quaternion.Zero()];
  5750. return MathTmp;
  5751. }());
  5752. })(BABYLON || (BABYLON = {}));
  5753. //# sourceMappingURL=babylon.math.js.map
  5754. var BABYLON;
  5755. (function (BABYLON) {
  5756. var Scalar = /** @class */ (function () {
  5757. function Scalar() {
  5758. }
  5759. /**
  5760. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  5761. */
  5762. Scalar.WithinEpsilon = function (a, b, epsilon) {
  5763. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  5764. var num = a - b;
  5765. return -epsilon <= num && num <= epsilon;
  5766. };
  5767. /**
  5768. * Returns a string : the upper case translation of the number i to hexadecimal.
  5769. */
  5770. Scalar.ToHex = function (i) {
  5771. var str = i.toString(16);
  5772. if (i <= 15) {
  5773. return ("0" + str).toUpperCase();
  5774. }
  5775. return str.toUpperCase();
  5776. };
  5777. /**
  5778. * Returns -1 if value is negative and +1 is value is positive.
  5779. * Returns the value itself if it's equal to zero.
  5780. */
  5781. Scalar.Sign = function (value) {
  5782. value = +value; // convert to a number
  5783. if (value === 0 || isNaN(value))
  5784. return value;
  5785. return value > 0 ? 1 : -1;
  5786. };
  5787. /**
  5788. * Returns the value itself if it's between min and max.
  5789. * Returns min if the value is lower than min.
  5790. * Returns max if the value is greater than max.
  5791. */
  5792. Scalar.Clamp = function (value, min, max) {
  5793. if (min === void 0) { min = 0; }
  5794. if (max === void 0) { max = 1; }
  5795. return Math.min(max, Math.max(min, value));
  5796. };
  5797. /**
  5798. * Returns the log2 of value.
  5799. */
  5800. Scalar.Log2 = function (value) {
  5801. return Math.log(value) * Math.LOG2E;
  5802. };
  5803. /**
  5804. * Loops the value, so that it is never larger than length and never smaller than 0.
  5805. *
  5806. * This is similar to the modulo operator but it works with floating point numbers.
  5807. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  5808. * With t = 5 and length = 2.5, the result would be 0.0.
  5809. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  5810. */
  5811. Scalar.Repeat = function (value, length) {
  5812. return value - Math.floor(value / length) * length;
  5813. };
  5814. /**
  5815. * Normalize the value between 0.0 and 1.0 using min and max values
  5816. */
  5817. Scalar.Normalize = function (value, min, max) {
  5818. return (value - min) / (max - min);
  5819. };
  5820. /**
  5821. * Denormalize the value from 0.0 and 1.0 using min and max values
  5822. */
  5823. Scalar.Denormalize = function (normalized, min, max) {
  5824. return (normalized * (max - min) + min);
  5825. };
  5826. /**
  5827. * Calculates the shortest difference between two given angles given in degrees.
  5828. */
  5829. Scalar.DeltaAngle = function (current, target) {
  5830. var num = Scalar.Repeat(target - current, 360.0);
  5831. if (num > 180.0) {
  5832. num -= 360.0;
  5833. }
  5834. return num;
  5835. };
  5836. /**
  5837. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  5838. *
  5839. * The returned value will move back and forth between 0 and length
  5840. */
  5841. Scalar.PingPong = function (tx, length) {
  5842. var t = Scalar.Repeat(tx, length * 2.0);
  5843. return length - Math.abs(t - length);
  5844. };
  5845. /**
  5846. * Interpolates between min and max with smoothing at the limits.
  5847. *
  5848. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  5849. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  5850. */
  5851. Scalar.SmoothStep = function (from, to, tx) {
  5852. var t = Scalar.Clamp(tx);
  5853. t = -2.0 * t * t * t + 3.0 * t * t;
  5854. return to * t + from * (1.0 - t);
  5855. };
  5856. /**
  5857. * Moves a value current towards target.
  5858. *
  5859. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  5860. * Negative values of maxDelta pushes the value away from target.
  5861. */
  5862. Scalar.MoveTowards = function (current, target, maxDelta) {
  5863. var result = 0;
  5864. if (Math.abs(target - current) <= maxDelta) {
  5865. result = target;
  5866. }
  5867. else {
  5868. result = current + Scalar.Sign(target - current) * maxDelta;
  5869. }
  5870. return result;
  5871. };
  5872. /**
  5873. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5874. *
  5875. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  5876. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  5877. */
  5878. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  5879. var num = Scalar.DeltaAngle(current, target);
  5880. var result = 0;
  5881. if (-maxDelta < num && num < maxDelta) {
  5882. result = target;
  5883. }
  5884. else {
  5885. target = current + num;
  5886. result = Scalar.MoveTowards(current, target, maxDelta);
  5887. }
  5888. return result;
  5889. };
  5890. /**
  5891. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  5892. */
  5893. Scalar.Lerp = function (start, end, amount) {
  5894. return start + ((end - start) * amount);
  5895. };
  5896. /**
  5897. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5898. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  5899. */
  5900. Scalar.LerpAngle = function (start, end, amount) {
  5901. var num = Scalar.Repeat(end - start, 360.0);
  5902. if (num > 180.0) {
  5903. num -= 360.0;
  5904. }
  5905. return start + num * Scalar.Clamp(amount);
  5906. };
  5907. /**
  5908. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  5909. */
  5910. Scalar.InverseLerp = function (a, b, value) {
  5911. var result = 0;
  5912. if (a != b) {
  5913. result = Scalar.Clamp((value - a) / (b - a));
  5914. }
  5915. else {
  5916. result = 0.0;
  5917. }
  5918. return result;
  5919. };
  5920. /**
  5921. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  5922. */
  5923. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5924. var squared = amount * amount;
  5925. var cubed = amount * squared;
  5926. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5927. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5928. var part3 = (cubed - (2.0 * squared)) + amount;
  5929. var part4 = cubed - squared;
  5930. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  5931. };
  5932. /**
  5933. * Returns a random float number between and min and max values
  5934. */
  5935. Scalar.RandomRange = function (min, max) {
  5936. if (min === max)
  5937. return min;
  5938. return ((Math.random() * (max - min)) + min);
  5939. };
  5940. /**
  5941. * This function returns percentage of a number in a given range.
  5942. *
  5943. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5944. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5945. */
  5946. Scalar.RangeToPercent = function (number, min, max) {
  5947. return ((number - min) / (max - min));
  5948. };
  5949. /**
  5950. * This function returns number that corresponds to the percentage in a given range.
  5951. *
  5952. * PercentToRange(0.34,0,100) will return 34.
  5953. */
  5954. Scalar.PercentToRange = function (percent, min, max) {
  5955. return ((max - min) * percent + min);
  5956. };
  5957. /**
  5958. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  5959. * @param angle The angle to normalize in radian.
  5960. * @return The converted angle.
  5961. */
  5962. Scalar.NormalizeRadians = function (angle) {
  5963. // More precise but slower version kept for reference.
  5964. // angle = angle % Tools.TwoPi;
  5965. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  5966. //if (angle > Math.PI) {
  5967. // angle -= Tools.TwoPi;
  5968. //}
  5969. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  5970. return angle;
  5971. };
  5972. /**
  5973. * Two pi constants convenient for computation.
  5974. */
  5975. Scalar.TwoPi = Math.PI * 2;
  5976. return Scalar;
  5977. }());
  5978. BABYLON.Scalar = Scalar;
  5979. })(BABYLON || (BABYLON = {}));
  5980. //# sourceMappingURL=babylon.math.scalar.js.map
  5981. //# sourceMappingURL=babylon.mixins.js.map
  5982. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  5983. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  5984. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  5985. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  5986. //# sourceMappingURL=babylon.webgl2.js.map
  5987. var BABYLON;
  5988. (function (BABYLON) {
  5989. var __decoratorInitialStore = {};
  5990. var __mergedStore = {};
  5991. var _copySource = function (creationFunction, source, instanciate) {
  5992. var destination = creationFunction();
  5993. // Tags
  5994. if (BABYLON.Tags) {
  5995. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5996. }
  5997. var classStore = getMergedStore(destination);
  5998. // Properties
  5999. for (var property in classStore) {
  6000. var propertyDescriptor = classStore[property];
  6001. var sourceProperty = source[property];
  6002. var propertyType = propertyDescriptor.type;
  6003. if (sourceProperty !== undefined && sourceProperty !== null) {
  6004. switch (propertyType) {
  6005. case 0: // Value
  6006. case 6:// Mesh reference
  6007. destination[property] = sourceProperty;
  6008. break;
  6009. case 1:// Texture
  6010. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6011. break;
  6012. case 2: // Color3
  6013. case 3: // FresnelParameters
  6014. case 4: // Vector2
  6015. case 5: // Vector3
  6016. case 7: // Color Curves
  6017. case 10:// Quaternion
  6018. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6019. break;
  6020. }
  6021. }
  6022. }
  6023. return destination;
  6024. };
  6025. function getDirectStore(target) {
  6026. var classKey = target.getClassName();
  6027. if (!__decoratorInitialStore[classKey]) {
  6028. __decoratorInitialStore[classKey] = {};
  6029. }
  6030. return __decoratorInitialStore[classKey];
  6031. }
  6032. /**
  6033. * Return the list of properties flagged as serializable
  6034. * @param target: host object
  6035. */
  6036. function getMergedStore(target) {
  6037. var classKey = target.getClassName();
  6038. if (__mergedStore[classKey]) {
  6039. return __mergedStore[classKey];
  6040. }
  6041. __mergedStore[classKey] = {};
  6042. var store = __mergedStore[classKey];
  6043. var currentTarget = target;
  6044. var currentKey = classKey;
  6045. while (currentKey) {
  6046. var initialStore = __decoratorInitialStore[currentKey];
  6047. for (var property in initialStore) {
  6048. store[property] = initialStore[property];
  6049. }
  6050. var parent_1 = void 0;
  6051. var done = false;
  6052. do {
  6053. parent_1 = Object.getPrototypeOf(currentTarget);
  6054. if (!parent_1.getClassName) {
  6055. done = true;
  6056. break;
  6057. }
  6058. if (parent_1.getClassName() !== currentKey) {
  6059. break;
  6060. }
  6061. currentTarget = parent_1;
  6062. } while (parent_1);
  6063. if (done) {
  6064. break;
  6065. }
  6066. currentKey = parent_1.getClassName();
  6067. currentTarget = parent_1;
  6068. }
  6069. return store;
  6070. }
  6071. function generateSerializableMember(type, sourceName) {
  6072. return function (target, propertyKey) {
  6073. var classStore = getDirectStore(target);
  6074. if (!classStore[propertyKey]) {
  6075. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6076. }
  6077. };
  6078. }
  6079. function generateExpandMember(setCallback, targetKey) {
  6080. if (targetKey === void 0) { targetKey = null; }
  6081. return function (target, propertyKey) {
  6082. var key = targetKey || ("_" + propertyKey);
  6083. Object.defineProperty(target, propertyKey, {
  6084. get: function () {
  6085. return this[key];
  6086. },
  6087. set: function (value) {
  6088. if (this[key] === value) {
  6089. return;
  6090. }
  6091. this[key] = value;
  6092. target[setCallback].apply(this);
  6093. },
  6094. enumerable: true,
  6095. configurable: true
  6096. });
  6097. };
  6098. }
  6099. function expandToProperty(callback, targetKey) {
  6100. if (targetKey === void 0) { targetKey = null; }
  6101. return generateExpandMember(callback, targetKey);
  6102. }
  6103. BABYLON.expandToProperty = expandToProperty;
  6104. function serialize(sourceName) {
  6105. return generateSerializableMember(0, sourceName); // value member
  6106. }
  6107. BABYLON.serialize = serialize;
  6108. function serializeAsTexture(sourceName) {
  6109. return generateSerializableMember(1, sourceName); // texture member
  6110. }
  6111. BABYLON.serializeAsTexture = serializeAsTexture;
  6112. function serializeAsColor3(sourceName) {
  6113. return generateSerializableMember(2, sourceName); // color3 member
  6114. }
  6115. BABYLON.serializeAsColor3 = serializeAsColor3;
  6116. function serializeAsFresnelParameters(sourceName) {
  6117. return generateSerializableMember(3, sourceName); // fresnel parameters member
  6118. }
  6119. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  6120. function serializeAsVector2(sourceName) {
  6121. return generateSerializableMember(4, sourceName); // vector2 member
  6122. }
  6123. BABYLON.serializeAsVector2 = serializeAsVector2;
  6124. function serializeAsVector3(sourceName) {
  6125. return generateSerializableMember(5, sourceName); // vector3 member
  6126. }
  6127. BABYLON.serializeAsVector3 = serializeAsVector3;
  6128. function serializeAsMeshReference(sourceName) {
  6129. return generateSerializableMember(6, sourceName); // mesh reference member
  6130. }
  6131. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  6132. function serializeAsColorCurves(sourceName) {
  6133. return generateSerializableMember(7, sourceName); // color curves
  6134. }
  6135. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  6136. function serializeAsColor4(sourceName) {
  6137. return generateSerializableMember(8, sourceName); // color 4
  6138. }
  6139. BABYLON.serializeAsColor4 = serializeAsColor4;
  6140. function serializeAsImageProcessingConfiguration(sourceName) {
  6141. return generateSerializableMember(9, sourceName); // image processing
  6142. }
  6143. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  6144. function serializeAsQuaternion(sourceName) {
  6145. return generateSerializableMember(10, sourceName); // quaternion member
  6146. }
  6147. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  6148. var SerializationHelper = /** @class */ (function () {
  6149. function SerializationHelper() {
  6150. }
  6151. SerializationHelper.Serialize = function (entity, serializationObject) {
  6152. if (!serializationObject) {
  6153. serializationObject = {};
  6154. }
  6155. // Tags
  6156. if (BABYLON.Tags) {
  6157. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  6158. }
  6159. var serializedProperties = getMergedStore(entity);
  6160. // Properties
  6161. for (var property in serializedProperties) {
  6162. var propertyDescriptor = serializedProperties[property];
  6163. var targetPropertyName = propertyDescriptor.sourceName || property;
  6164. var propertyType = propertyDescriptor.type;
  6165. var sourceProperty = entity[property];
  6166. if (sourceProperty !== undefined && sourceProperty !== null) {
  6167. switch (propertyType) {
  6168. case 0:// Value
  6169. serializationObject[targetPropertyName] = sourceProperty;
  6170. break;
  6171. case 1:// Texture
  6172. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6173. break;
  6174. case 2:// Color3
  6175. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6176. break;
  6177. case 3:// FresnelParameters
  6178. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6179. break;
  6180. case 4:// Vector2
  6181. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6182. break;
  6183. case 5:// Vector3
  6184. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6185. break;
  6186. case 6:// Mesh reference
  6187. serializationObject[targetPropertyName] = sourceProperty.id;
  6188. break;
  6189. case 7:// Color Curves
  6190. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6191. break;
  6192. case 8:// Color 4
  6193. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6194. break;
  6195. case 9:// Image Processing
  6196. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6197. break;
  6198. }
  6199. }
  6200. }
  6201. return serializationObject;
  6202. };
  6203. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  6204. if (rootUrl === void 0) { rootUrl = null; }
  6205. var destination = creationFunction();
  6206. if (!rootUrl) {
  6207. rootUrl = "";
  6208. }
  6209. // Tags
  6210. if (BABYLON.Tags) {
  6211. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6212. }
  6213. var classStore = getMergedStore(destination);
  6214. // Properties
  6215. for (var property in classStore) {
  6216. var propertyDescriptor = classStore[property];
  6217. var sourceProperty = source[propertyDescriptor.sourceName || property];
  6218. var propertyType = propertyDescriptor.type;
  6219. if (sourceProperty !== undefined && sourceProperty !== null) {
  6220. var dest = destination;
  6221. switch (propertyType) {
  6222. case 0:// Value
  6223. dest[property] = sourceProperty;
  6224. break;
  6225. case 1:// Texture
  6226. if (scene) {
  6227. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  6228. }
  6229. break;
  6230. case 2:// Color3
  6231. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  6232. break;
  6233. case 3:// FresnelParameters
  6234. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  6235. break;
  6236. case 4:// Vector2
  6237. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  6238. break;
  6239. case 5:// Vector3
  6240. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  6241. break;
  6242. case 6:// Mesh reference
  6243. if (scene) {
  6244. dest[property] = scene.getLastMeshByID(sourceProperty);
  6245. }
  6246. break;
  6247. case 7:// Color Curves
  6248. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  6249. break;
  6250. case 8:// Color 4
  6251. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  6252. break;
  6253. case 9:// Image Processing
  6254. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  6255. break;
  6256. }
  6257. }
  6258. }
  6259. return destination;
  6260. };
  6261. SerializationHelper.Clone = function (creationFunction, source) {
  6262. return _copySource(creationFunction, source, false);
  6263. };
  6264. SerializationHelper.Instanciate = function (creationFunction, source) {
  6265. return _copySource(creationFunction, source, true);
  6266. };
  6267. return SerializationHelper;
  6268. }());
  6269. BABYLON.SerializationHelper = SerializationHelper;
  6270. })(BABYLON || (BABYLON = {}));
  6271. //# sourceMappingURL=babylon.decorators.js.map
  6272. var BABYLON;
  6273. (function (BABYLON) {
  6274. /**
  6275. * A class serves as a medium between the observable and its observers
  6276. */
  6277. var EventState = /** @class */ (function () {
  6278. /**
  6279. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  6280. */
  6281. function EventState(mask, skipNextObservers, target, currentTarget) {
  6282. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6283. this.initalize(mask, skipNextObservers, target, currentTarget);
  6284. }
  6285. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  6286. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6287. this.mask = mask;
  6288. this.skipNextObservers = skipNextObservers;
  6289. this.target = target;
  6290. this.currentTarget = currentTarget;
  6291. return this;
  6292. };
  6293. return EventState;
  6294. }());
  6295. BABYLON.EventState = EventState;
  6296. /**
  6297. * Represent an Observer registered to a given Observable object.
  6298. */
  6299. var Observer = /** @class */ (function () {
  6300. function Observer(callback, mask, scope) {
  6301. if (scope === void 0) { scope = null; }
  6302. this.callback = callback;
  6303. this.mask = mask;
  6304. this.scope = scope;
  6305. }
  6306. return Observer;
  6307. }());
  6308. BABYLON.Observer = Observer;
  6309. /**
  6310. * Represent a list of observers registered to multiple Observables object.
  6311. */
  6312. var MultiObserver = /** @class */ (function () {
  6313. function MultiObserver() {
  6314. }
  6315. MultiObserver.prototype.dispose = function () {
  6316. if (this._observers && this._observables) {
  6317. for (var index = 0; index < this._observers.length; index++) {
  6318. this._observables[index].remove(this._observers[index]);
  6319. }
  6320. }
  6321. this._observers = null;
  6322. this._observables = null;
  6323. };
  6324. MultiObserver.Watch = function (observables, callback, mask, scope) {
  6325. if (mask === void 0) { mask = -1; }
  6326. if (scope === void 0) { scope = null; }
  6327. var result = new MultiObserver();
  6328. result._observers = new Array();
  6329. result._observables = observables;
  6330. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  6331. var observable = observables_1[_i];
  6332. var observer = observable.add(callback, mask, false, scope);
  6333. if (observer) {
  6334. result._observers.push(observer);
  6335. }
  6336. }
  6337. return result;
  6338. };
  6339. return MultiObserver;
  6340. }());
  6341. BABYLON.MultiObserver = MultiObserver;
  6342. /**
  6343. * The Observable class is a simple implementation of the Observable pattern.
  6344. * 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.
  6345. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  6346. * 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).
  6347. * 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.
  6348. */
  6349. var Observable = /** @class */ (function () {
  6350. function Observable(onObserverAdded) {
  6351. this._observers = new Array();
  6352. this._eventState = new EventState(0);
  6353. if (onObserverAdded) {
  6354. this._onObserverAdded = onObserverAdded;
  6355. }
  6356. }
  6357. /**
  6358. * Create a new Observer with the specified callback
  6359. * @param callback the callback that will be executed for that Observer
  6360. * @param mask the mask used to filter observers
  6361. * @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.
  6362. * @param scope optional scope for the callback to be called from
  6363. */
  6364. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  6365. if (mask === void 0) { mask = -1; }
  6366. if (insertFirst === void 0) { insertFirst = false; }
  6367. if (scope === void 0) { scope = null; }
  6368. if (!callback) {
  6369. return null;
  6370. }
  6371. var observer = new Observer(callback, mask, scope);
  6372. if (insertFirst) {
  6373. this._observers.unshift(observer);
  6374. }
  6375. else {
  6376. this._observers.push(observer);
  6377. }
  6378. if (this._onObserverAdded) {
  6379. this._onObserverAdded(observer);
  6380. }
  6381. return observer;
  6382. };
  6383. /**
  6384. * Remove an Observer from the Observable object
  6385. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  6386. */
  6387. Observable.prototype.remove = function (observer) {
  6388. if (!observer) {
  6389. return false;
  6390. }
  6391. var index = this._observers.indexOf(observer);
  6392. if (index !== -1) {
  6393. this._observers.splice(index, 1);
  6394. return true;
  6395. }
  6396. return false;
  6397. };
  6398. /**
  6399. * Remove a callback from the Observable object
  6400. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  6401. */
  6402. Observable.prototype.removeCallback = function (callback) {
  6403. for (var index = 0; index < this._observers.length; index++) {
  6404. if (this._observers[index].callback === callback) {
  6405. this._observers.splice(index, 1);
  6406. return true;
  6407. }
  6408. }
  6409. return false;
  6410. };
  6411. /**
  6412. * Notify all Observers by calling their respective callback with the given data
  6413. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  6414. * @param eventData
  6415. * @param mask
  6416. */
  6417. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  6418. if (mask === void 0) { mask = -1; }
  6419. if (!this._observers.length) {
  6420. return true;
  6421. }
  6422. var state = this._eventState;
  6423. state.mask = mask;
  6424. state.target = target;
  6425. state.currentTarget = currentTarget;
  6426. state.skipNextObservers = false;
  6427. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6428. var obs = _a[_i];
  6429. if (obs.mask & mask) {
  6430. if (obs.scope) {
  6431. obs.callback.apply(obs.scope, [eventData, state]);
  6432. }
  6433. else {
  6434. obs.callback(eventData, state);
  6435. }
  6436. }
  6437. if (state.skipNextObservers) {
  6438. return false;
  6439. }
  6440. }
  6441. return true;
  6442. };
  6443. /**
  6444. * Notify a specific observer
  6445. * @param eventData
  6446. * @param mask
  6447. */
  6448. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  6449. if (mask === void 0) { mask = -1; }
  6450. var state = this._eventState;
  6451. state.mask = mask;
  6452. state.skipNextObservers = false;
  6453. observer.callback(eventData, state);
  6454. };
  6455. /**
  6456. * return true is the Observable has at least one Observer registered
  6457. */
  6458. Observable.prototype.hasObservers = function () {
  6459. return this._observers.length > 0;
  6460. };
  6461. /**
  6462. * Clear the list of observers
  6463. */
  6464. Observable.prototype.clear = function () {
  6465. this._observers = new Array();
  6466. this._onObserverAdded = null;
  6467. };
  6468. /**
  6469. * Clone the current observable
  6470. */
  6471. Observable.prototype.clone = function () {
  6472. var result = new Observable();
  6473. result._observers = this._observers.slice(0);
  6474. return result;
  6475. };
  6476. /**
  6477. * Does this observable handles observer registered with a given mask
  6478. * @param {number} trigger - the mask to be tested
  6479. * @return {boolean} whether or not one observer registered with the given mask is handeled
  6480. **/
  6481. Observable.prototype.hasSpecificMask = function (mask) {
  6482. if (mask === void 0) { mask = -1; }
  6483. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6484. var obs = _a[_i];
  6485. if (obs.mask & mask || obs.mask === mask) {
  6486. return true;
  6487. }
  6488. }
  6489. return false;
  6490. };
  6491. return Observable;
  6492. }());
  6493. BABYLON.Observable = Observable;
  6494. })(BABYLON || (BABYLON = {}));
  6495. //# sourceMappingURL=babylon.observable.js.map
  6496. var BABYLON;
  6497. (function (BABYLON) {
  6498. var SmartArray = /** @class */ (function () {
  6499. function SmartArray(capacity) {
  6500. this.length = 0;
  6501. this.data = new Array(capacity);
  6502. this._id = SmartArray._GlobalId++;
  6503. }
  6504. SmartArray.prototype.push = function (value) {
  6505. this.data[this.length++] = value;
  6506. if (this.length > this.data.length) {
  6507. this.data.length *= 2;
  6508. }
  6509. };
  6510. SmartArray.prototype.forEach = function (func) {
  6511. for (var index = 0; index < this.length; index++) {
  6512. func(this.data[index]);
  6513. }
  6514. };
  6515. SmartArray.prototype.sort = function (compareFn) {
  6516. this.data.sort(compareFn);
  6517. };
  6518. SmartArray.prototype.reset = function () {
  6519. this.length = 0;
  6520. };
  6521. SmartArray.prototype.dispose = function () {
  6522. this.reset();
  6523. if (this.data) {
  6524. this.data.length = 0;
  6525. this.data = [];
  6526. }
  6527. };
  6528. SmartArray.prototype.concat = function (array) {
  6529. if (array.length === 0) {
  6530. return;
  6531. }
  6532. if (this.length + array.length > this.data.length) {
  6533. this.data.length = (this.length + array.length) * 2;
  6534. }
  6535. for (var index = 0; index < array.length; index++) {
  6536. this.data[this.length++] = (array.data || array)[index];
  6537. }
  6538. };
  6539. SmartArray.prototype.indexOf = function (value) {
  6540. var position = this.data.indexOf(value);
  6541. if (position >= this.length) {
  6542. return -1;
  6543. }
  6544. return position;
  6545. };
  6546. SmartArray.prototype.contains = function (value) {
  6547. return this.data.indexOf(value) !== -1;
  6548. };
  6549. // Statics
  6550. SmartArray._GlobalId = 0;
  6551. return SmartArray;
  6552. }());
  6553. BABYLON.SmartArray = SmartArray;
  6554. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  6555. __extends(SmartArrayNoDuplicate, _super);
  6556. function SmartArrayNoDuplicate() {
  6557. var _this = _super !== null && _super.apply(this, arguments) || this;
  6558. _this._duplicateId = 0;
  6559. return _this;
  6560. }
  6561. SmartArrayNoDuplicate.prototype.push = function (value) {
  6562. _super.prototype.push.call(this, value);
  6563. if (!value.__smartArrayFlags) {
  6564. value.__smartArrayFlags = {};
  6565. }
  6566. value.__smartArrayFlags[this._id] = this._duplicateId;
  6567. };
  6568. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  6569. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  6570. return false;
  6571. }
  6572. this.push(value);
  6573. return true;
  6574. };
  6575. SmartArrayNoDuplicate.prototype.reset = function () {
  6576. _super.prototype.reset.call(this);
  6577. this._duplicateId++;
  6578. };
  6579. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  6580. if (array.length === 0) {
  6581. return;
  6582. }
  6583. if (this.length + array.length > this.data.length) {
  6584. this.data.length = (this.length + array.length) * 2;
  6585. }
  6586. for (var index = 0; index < array.length; index++) {
  6587. var item = (array.data || array)[index];
  6588. this.pushNoDuplicate(item);
  6589. }
  6590. };
  6591. return SmartArrayNoDuplicate;
  6592. }(SmartArray));
  6593. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  6594. })(BABYLON || (BABYLON = {}));
  6595. //# sourceMappingURL=babylon.smartArray.js.map
  6596. var BABYLON;
  6597. (function (BABYLON) {
  6598. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  6599. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  6600. var LoadFileError = /** @class */ (function (_super) {
  6601. __extends(LoadFileError, _super);
  6602. function LoadFileError(message, request) {
  6603. var _this = _super.call(this, message) || this;
  6604. _this.request = request;
  6605. _this.name = "LoadFileError";
  6606. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  6607. return _this;
  6608. }
  6609. // Polyfill for Object.setPrototypeOf if necessary.
  6610. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  6611. return LoadFileError;
  6612. }(Error));
  6613. BABYLON.LoadFileError = LoadFileError;
  6614. var RetryStrategy = /** @class */ (function () {
  6615. function RetryStrategy() {
  6616. }
  6617. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  6618. if (maxRetries === void 0) { maxRetries = 3; }
  6619. if (baseInterval === void 0) { baseInterval = 500; }
  6620. return function (url, request, retryIndex) {
  6621. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  6622. return -1;
  6623. }
  6624. return Math.pow(2, retryIndex) * baseInterval;
  6625. };
  6626. };
  6627. return RetryStrategy;
  6628. }());
  6629. BABYLON.RetryStrategy = RetryStrategy;
  6630. // Screenshots
  6631. var screenshotCanvas;
  6632. var cloneValue = function (source, destinationObject) {
  6633. if (!source)
  6634. return null;
  6635. if (source instanceof BABYLON.Mesh) {
  6636. return null;
  6637. }
  6638. if (source instanceof BABYLON.SubMesh) {
  6639. return source.clone(destinationObject);
  6640. }
  6641. else if (source.clone) {
  6642. return source.clone();
  6643. }
  6644. return null;
  6645. };
  6646. var Tools = /** @class */ (function () {
  6647. function Tools() {
  6648. }
  6649. /**
  6650. * Interpolates between a and b via alpha
  6651. * @param a The lower value (returned when alpha = 0)
  6652. * @param b The upper value (returned when alpha = 1)
  6653. * @param alpha The interpolation-factor
  6654. * @return The mixed value
  6655. */
  6656. Tools.Mix = function (a, b, alpha) {
  6657. return a * (1 - alpha) + b * alpha;
  6658. };
  6659. Tools.Instantiate = function (className) {
  6660. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  6661. return Tools.RegisteredExternalClasses[className];
  6662. }
  6663. var arr = className.split(".");
  6664. var fn = (window || this);
  6665. for (var i = 0, len = arr.length; i < len; i++) {
  6666. fn = fn[arr[i]];
  6667. }
  6668. if (typeof fn !== "function") {
  6669. return null;
  6670. }
  6671. return fn;
  6672. };
  6673. Tools.SetImmediate = function (action) {
  6674. if (window.setImmediate) {
  6675. window.setImmediate(action);
  6676. }
  6677. else {
  6678. setTimeout(action, 1);
  6679. }
  6680. };
  6681. Tools.IsExponentOfTwo = function (value) {
  6682. var count = 1;
  6683. do {
  6684. count *= 2;
  6685. } while (count < value);
  6686. return count === value;
  6687. };
  6688. /**
  6689. * Find the next highest power of two.
  6690. * @param x Number to start search from.
  6691. * @return Next highest power of two.
  6692. */
  6693. Tools.CeilingPOT = function (x) {
  6694. x--;
  6695. x |= x >> 1;
  6696. x |= x >> 2;
  6697. x |= x >> 4;
  6698. x |= x >> 8;
  6699. x |= x >> 16;
  6700. x++;
  6701. return x;
  6702. };
  6703. /**
  6704. * Find the next lowest power of two.
  6705. * @param x Number to start search from.
  6706. * @return Next lowest power of two.
  6707. */
  6708. Tools.FloorPOT = function (x) {
  6709. x = x | (x >> 1);
  6710. x = x | (x >> 2);
  6711. x = x | (x >> 4);
  6712. x = x | (x >> 8);
  6713. x = x | (x >> 16);
  6714. return x - (x >> 1);
  6715. };
  6716. /**
  6717. * Find the nearest power of two.
  6718. * @param x Number to start search from.
  6719. * @return Next nearest power of two.
  6720. */
  6721. Tools.NearestPOT = function (x) {
  6722. var c = Tools.CeilingPOT(x);
  6723. var f = Tools.FloorPOT(x);
  6724. return (c - x) > (x - f) ? f : c;
  6725. };
  6726. Tools.GetExponentOfTwo = function (value, max, mode) {
  6727. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  6728. var pot;
  6729. switch (mode) {
  6730. case BABYLON.Engine.SCALEMODE_FLOOR:
  6731. pot = Tools.FloorPOT(value);
  6732. break;
  6733. case BABYLON.Engine.SCALEMODE_NEAREST:
  6734. pot = Tools.NearestPOT(value);
  6735. break;
  6736. case BABYLON.Engine.SCALEMODE_CEILING:
  6737. default:
  6738. pot = Tools.CeilingPOT(value);
  6739. break;
  6740. }
  6741. return Math.min(pot, max);
  6742. };
  6743. Tools.GetFilename = function (path) {
  6744. var index = path.lastIndexOf("/");
  6745. if (index < 0)
  6746. return path;
  6747. return path.substring(index + 1);
  6748. };
  6749. Tools.GetFolderPath = function (uri) {
  6750. var index = uri.lastIndexOf("/");
  6751. if (index < 0)
  6752. return "";
  6753. return uri.substring(0, index + 1);
  6754. };
  6755. Tools.GetDOMTextContent = function (element) {
  6756. var result = "";
  6757. var child = element.firstChild;
  6758. while (child) {
  6759. if (child.nodeType === 3) {
  6760. result += child.textContent;
  6761. }
  6762. child = child.nextSibling;
  6763. }
  6764. return result;
  6765. };
  6766. Tools.ToDegrees = function (angle) {
  6767. return angle * 180 / Math.PI;
  6768. };
  6769. Tools.ToRadians = function (angle) {
  6770. return angle * Math.PI / 180;
  6771. };
  6772. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  6773. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  6774. var output = "";
  6775. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  6776. var i = 0;
  6777. var bytes = new Uint8Array(buffer);
  6778. while (i < bytes.length) {
  6779. chr1 = bytes[i++];
  6780. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  6781. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  6782. enc1 = chr1 >> 2;
  6783. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  6784. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  6785. enc4 = chr3 & 63;
  6786. if (isNaN(chr2)) {
  6787. enc3 = enc4 = 64;
  6788. }
  6789. else if (isNaN(chr3)) {
  6790. enc4 = 64;
  6791. }
  6792. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  6793. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  6794. }
  6795. return "data:image/png;base64," + output;
  6796. };
  6797. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  6798. if (bias === void 0) { bias = null; }
  6799. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6800. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6801. for (var index = indexStart; index < indexStart + indexCount; index++) {
  6802. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  6803. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6804. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6805. }
  6806. if (bias) {
  6807. minimum.x -= minimum.x * bias.x + bias.y;
  6808. minimum.y -= minimum.y * bias.x + bias.y;
  6809. minimum.z -= minimum.z * bias.x + bias.y;
  6810. maximum.x += maximum.x * bias.x + bias.y;
  6811. maximum.y += maximum.y * bias.x + bias.y;
  6812. maximum.z += maximum.z * bias.x + bias.y;
  6813. }
  6814. return {
  6815. minimum: minimum,
  6816. maximum: maximum
  6817. };
  6818. };
  6819. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  6820. if (bias === void 0) { bias = null; }
  6821. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6822. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6823. if (!stride) {
  6824. stride = 3;
  6825. }
  6826. for (var index = start; index < start + count; index++) {
  6827. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  6828. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6829. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6830. }
  6831. if (bias) {
  6832. minimum.x -= minimum.x * bias.x + bias.y;
  6833. minimum.y -= minimum.y * bias.x + bias.y;
  6834. minimum.z -= minimum.z * bias.x + bias.y;
  6835. maximum.x += maximum.x * bias.x + bias.y;
  6836. maximum.y += maximum.y * bias.x + bias.y;
  6837. maximum.z += maximum.z * bias.x + bias.y;
  6838. }
  6839. return {
  6840. minimum: minimum,
  6841. maximum: maximum
  6842. };
  6843. };
  6844. Tools.Vector2ArrayFeeder = function (array) {
  6845. return function (index) {
  6846. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  6847. var length = isFloatArray ? array.length / 2 : array.length;
  6848. if (index >= length) {
  6849. return null;
  6850. }
  6851. if (isFloatArray) {
  6852. var fa = array;
  6853. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  6854. }
  6855. var a = array;
  6856. return a[index];
  6857. };
  6858. };
  6859. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  6860. if (bias === void 0) { bias = null; }
  6861. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  6862. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  6863. var i = 0;
  6864. var cur = feeder(i++);
  6865. while (cur) {
  6866. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  6867. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  6868. cur = feeder(i++);
  6869. }
  6870. if (bias) {
  6871. minimum.x -= minimum.x * bias.x + bias.y;
  6872. minimum.y -= minimum.y * bias.x + bias.y;
  6873. maximum.x += maximum.x * bias.x + bias.y;
  6874. maximum.y += maximum.y * bias.x + bias.y;
  6875. }
  6876. return {
  6877. minimum: minimum,
  6878. maximum: maximum
  6879. };
  6880. };
  6881. Tools.MakeArray = function (obj, allowsNullUndefined) {
  6882. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6883. return null;
  6884. return Array.isArray(obj) ? obj : [obj];
  6885. };
  6886. // Misc.
  6887. Tools.GetPointerPrefix = function () {
  6888. var eventPrefix = "pointer";
  6889. // Check if pointer events are supported
  6890. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  6891. eventPrefix = "mouse";
  6892. }
  6893. return eventPrefix;
  6894. };
  6895. /**
  6896. * @param func - the function to be called
  6897. * @param requester - the object that will request the next frame. Falls back to window.
  6898. */
  6899. Tools.QueueNewFrame = function (func, requester) {
  6900. if (!Tools.IsWindowObjectExist()) {
  6901. return setTimeout(func, 16);
  6902. }
  6903. if (!requester) {
  6904. requester = window;
  6905. }
  6906. if (requester.requestAnimationFrame) {
  6907. return requester.requestAnimationFrame(func);
  6908. }
  6909. else if (requester.msRequestAnimationFrame) {
  6910. return requester.msRequestAnimationFrame(func);
  6911. }
  6912. else if (requester.webkitRequestAnimationFrame) {
  6913. return requester.webkitRequestAnimationFrame(func);
  6914. }
  6915. else if (requester.mozRequestAnimationFrame) {
  6916. return requester.mozRequestAnimationFrame(func);
  6917. }
  6918. else if (requester.oRequestAnimationFrame) {
  6919. return requester.oRequestAnimationFrame(func);
  6920. }
  6921. else {
  6922. return window.setTimeout(func, 16);
  6923. }
  6924. };
  6925. Tools.RequestFullscreen = function (element) {
  6926. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6927. if (!requestFunction)
  6928. return;
  6929. requestFunction.call(element);
  6930. };
  6931. Tools.ExitFullscreen = function () {
  6932. if (document.exitFullscreen) {
  6933. document.exitFullscreen();
  6934. }
  6935. else if (document.mozCancelFullScreen) {
  6936. document.mozCancelFullScreen();
  6937. }
  6938. else if (document.webkitCancelFullScreen) {
  6939. document.webkitCancelFullScreen();
  6940. }
  6941. else if (document.msCancelFullScreen) {
  6942. document.msCancelFullScreen();
  6943. }
  6944. };
  6945. Tools.SetCorsBehavior = function (url, element) {
  6946. if (url && url.indexOf("data:") === 0) {
  6947. return;
  6948. }
  6949. if (Tools.CorsBehavior) {
  6950. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  6951. element.crossOrigin = Tools.CorsBehavior;
  6952. }
  6953. else {
  6954. var result = Tools.CorsBehavior(url);
  6955. if (result) {
  6956. element.crossOrigin = result;
  6957. }
  6958. }
  6959. }
  6960. };
  6961. // External files
  6962. Tools.CleanUrl = function (url) {
  6963. url = url.replace(/#/mg, "%23");
  6964. return url;
  6965. };
  6966. Tools.LoadImage = function (url, onLoad, onError, database) {
  6967. if (url instanceof ArrayBuffer) {
  6968. url = Tools.EncodeArrayBufferTobase64(url);
  6969. }
  6970. url = Tools.CleanUrl(url);
  6971. url = Tools.PreprocessUrl(url);
  6972. var img = new Image();
  6973. Tools.SetCorsBehavior(url, img);
  6974. img.onload = function () {
  6975. onLoad(img);
  6976. };
  6977. img.onerror = function (err) {
  6978. Tools.Error("Error while trying to load image: " + url);
  6979. if (onError) {
  6980. onError("Error while trying to load image: " + url, err);
  6981. }
  6982. };
  6983. var noIndexedDB = function () {
  6984. img.src = url;
  6985. };
  6986. var loadFromIndexedDB = function () {
  6987. if (database) {
  6988. database.loadImageFromDB(url, img);
  6989. }
  6990. };
  6991. //ANY database to do!
  6992. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6993. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6994. }
  6995. else {
  6996. if (url.indexOf("file:") !== -1) {
  6997. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  6998. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  6999. try {
  7000. var blobURL;
  7001. try {
  7002. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  7003. }
  7004. catch (ex) {
  7005. // Chrome doesn't support oneTimeOnly parameter
  7006. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  7007. }
  7008. img.src = blobURL;
  7009. }
  7010. catch (e) {
  7011. img.src = "";
  7012. }
  7013. return img;
  7014. }
  7015. }
  7016. noIndexedDB();
  7017. }
  7018. return img;
  7019. };
  7020. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  7021. url = Tools.CleanUrl(url);
  7022. url = Tools.PreprocessUrl(url);
  7023. // If file and file input are set
  7024. if (url.indexOf("file:") !== -1) {
  7025. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  7026. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  7027. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  7028. }
  7029. }
  7030. var loadUrl = Tools.BaseUrl + url;
  7031. var aborted = false;
  7032. var fileRequest = {
  7033. onCompleteObservable: new BABYLON.Observable(),
  7034. abort: function () { return aborted = true; },
  7035. };
  7036. var requestFile = function () {
  7037. var request = new XMLHttpRequest();
  7038. var retryHandle = null;
  7039. fileRequest.abort = function () {
  7040. aborted = true;
  7041. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  7042. request.abort();
  7043. }
  7044. if (retryHandle !== null) {
  7045. clearTimeout(retryHandle);
  7046. retryHandle = null;
  7047. }
  7048. };
  7049. var retryLoop = function (retryIndex) {
  7050. request.open('GET', loadUrl, true);
  7051. if (useArrayBuffer) {
  7052. request.responseType = "arraybuffer";
  7053. }
  7054. if (onProgress) {
  7055. request.addEventListener("progress", onProgress);
  7056. }
  7057. var onLoadEnd = function () {
  7058. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7059. };
  7060. request.addEventListener("loadend", onLoadEnd);
  7061. var onReadyStateChange = function () {
  7062. if (aborted) {
  7063. return;
  7064. }
  7065. // In case of undefined state in some browsers.
  7066. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  7067. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  7068. request.removeEventListener("readystatechange", onReadyStateChange);
  7069. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  7070. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  7071. return;
  7072. }
  7073. var retryStrategy = Tools.DefaultRetryStrategy;
  7074. if (retryStrategy) {
  7075. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  7076. if (waitTime !== -1) {
  7077. // Prevent the request from completing for retry.
  7078. request.removeEventListener("loadend", onLoadEnd);
  7079. request = new XMLHttpRequest();
  7080. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  7081. return;
  7082. }
  7083. }
  7084. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  7085. if (onError) {
  7086. onError(request, e);
  7087. }
  7088. else {
  7089. throw e;
  7090. }
  7091. }
  7092. };
  7093. request.addEventListener("readystatechange", onReadyStateChange);
  7094. request.send();
  7095. };
  7096. retryLoop(0);
  7097. };
  7098. // Caching all files
  7099. if (database && database.enableSceneOffline) {
  7100. var noIndexedDB_1 = function () {
  7101. if (!aborted) {
  7102. requestFile();
  7103. }
  7104. };
  7105. var loadFromIndexedDB = function () {
  7106. // TODO: database needs to support aborting and should return a IFileRequest
  7107. if (aborted) {
  7108. return;
  7109. }
  7110. if (database) {
  7111. database.loadFileFromDB(url, function (data) {
  7112. if (!aborted) {
  7113. onSuccess(data);
  7114. }
  7115. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7116. }, onProgress ? function (event) {
  7117. if (!aborted) {
  7118. onProgress(event);
  7119. }
  7120. } : undefined, noIndexedDB_1, useArrayBuffer);
  7121. }
  7122. };
  7123. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  7124. }
  7125. else {
  7126. requestFile();
  7127. }
  7128. return fileRequest;
  7129. };
  7130. /**
  7131. * Load a script (identified by an url). When the url returns, the
  7132. * content of this file is added into a new script element, attached to the DOM (body element)
  7133. */
  7134. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  7135. var head = document.getElementsByTagName('head')[0];
  7136. var script = document.createElement('script');
  7137. script.type = 'text/javascript';
  7138. script.src = scriptUrl;
  7139. script.onload = function () {
  7140. if (onSuccess) {
  7141. onSuccess();
  7142. }
  7143. };
  7144. script.onerror = function (e) {
  7145. if (onError) {
  7146. onError("Unable to load script", e);
  7147. }
  7148. };
  7149. head.appendChild(script);
  7150. };
  7151. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  7152. var reader = new FileReader();
  7153. var request = {
  7154. onCompleteObservable: new BABYLON.Observable(),
  7155. abort: function () { return reader.abort(); },
  7156. };
  7157. reader.onloadend = function (e) {
  7158. request.onCompleteObservable.notifyObservers(request);
  7159. };
  7160. reader.onload = function (e) {
  7161. //target doesn't have result from ts 1.3
  7162. callback(e.target['result']);
  7163. };
  7164. reader.onprogress = progressCallback;
  7165. reader.readAsDataURL(fileToLoad);
  7166. return request;
  7167. };
  7168. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  7169. var reader = new FileReader();
  7170. var request = {
  7171. onCompleteObservable: new BABYLON.Observable(),
  7172. abort: function () { return reader.abort(); },
  7173. };
  7174. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  7175. reader.onerror = function (e) {
  7176. Tools.Log("Error while reading file: " + fileToLoad.name);
  7177. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  7178. };
  7179. reader.onload = function (e) {
  7180. //target doesn't have result from ts 1.3
  7181. callback(e.target['result']);
  7182. };
  7183. if (progressCallBack) {
  7184. reader.onprogress = progressCallBack;
  7185. }
  7186. if (!useArrayBuffer) {
  7187. // Asynchronous read
  7188. reader.readAsText(fileToLoad);
  7189. }
  7190. else {
  7191. reader.readAsArrayBuffer(fileToLoad);
  7192. }
  7193. return request;
  7194. };
  7195. //returns a downloadable url to a file content.
  7196. Tools.FileAsURL = function (content) {
  7197. var fileBlob = new Blob([content]);
  7198. var url = window.URL || window.webkitURL;
  7199. var link = url.createObjectURL(fileBlob);
  7200. return link;
  7201. };
  7202. // Misc.
  7203. Tools.Format = function (value, decimals) {
  7204. if (decimals === void 0) { decimals = 2; }
  7205. return value.toFixed(decimals);
  7206. };
  7207. Tools.CheckExtends = function (v, min, max) {
  7208. if (v.x < min.x)
  7209. min.x = v.x;
  7210. if (v.y < min.y)
  7211. min.y = v.y;
  7212. if (v.z < min.z)
  7213. min.z = v.z;
  7214. if (v.x > max.x)
  7215. max.x = v.x;
  7216. if (v.y > max.y)
  7217. max.y = v.y;
  7218. if (v.z > max.z)
  7219. max.z = v.z;
  7220. };
  7221. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  7222. for (var prop in source) {
  7223. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  7224. continue;
  7225. }
  7226. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  7227. continue;
  7228. }
  7229. var sourceValue = source[prop];
  7230. var typeOfSourceValue = typeof sourceValue;
  7231. if (typeOfSourceValue === "function") {
  7232. continue;
  7233. }
  7234. if (typeOfSourceValue === "object") {
  7235. if (sourceValue instanceof Array) {
  7236. destination[prop] = [];
  7237. if (sourceValue.length > 0) {
  7238. if (typeof sourceValue[0] == "object") {
  7239. for (var index = 0; index < sourceValue.length; index++) {
  7240. var clonedValue = cloneValue(sourceValue[index], destination);
  7241. if (destination[prop].indexOf(clonedValue) === -1) {
  7242. destination[prop].push(clonedValue);
  7243. }
  7244. }
  7245. }
  7246. else {
  7247. destination[prop] = sourceValue.slice(0);
  7248. }
  7249. }
  7250. }
  7251. else {
  7252. destination[prop] = cloneValue(sourceValue, destination);
  7253. }
  7254. }
  7255. else {
  7256. destination[prop] = sourceValue;
  7257. }
  7258. }
  7259. };
  7260. Tools.IsEmpty = function (obj) {
  7261. for (var i in obj) {
  7262. if (obj.hasOwnProperty(i)) {
  7263. return false;
  7264. }
  7265. }
  7266. return true;
  7267. };
  7268. Tools.RegisterTopRootEvents = function (events) {
  7269. for (var index = 0; index < events.length; index++) {
  7270. var event = events[index];
  7271. window.addEventListener(event.name, event.handler, false);
  7272. try {
  7273. if (window.parent) {
  7274. window.parent.addEventListener(event.name, event.handler, false);
  7275. }
  7276. }
  7277. catch (e) {
  7278. // Silently fails...
  7279. }
  7280. }
  7281. };
  7282. Tools.UnregisterTopRootEvents = function (events) {
  7283. for (var index = 0; index < events.length; index++) {
  7284. var event = events[index];
  7285. window.removeEventListener(event.name, event.handler);
  7286. try {
  7287. if (window.parent) {
  7288. window.parent.removeEventListener(event.name, event.handler);
  7289. }
  7290. }
  7291. catch (e) {
  7292. // Silently fails...
  7293. }
  7294. }
  7295. };
  7296. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  7297. if (mimeType === void 0) { mimeType = "image/png"; }
  7298. // Read the contents of the framebuffer
  7299. var numberOfChannelsByLine = width * 4;
  7300. var halfHeight = height / 2;
  7301. //Reading datas from WebGL
  7302. var data = engine.readPixels(0, 0, width, height);
  7303. //To flip image on Y axis.
  7304. for (var i = 0; i < halfHeight; i++) {
  7305. for (var j = 0; j < numberOfChannelsByLine; j++) {
  7306. var currentCell = j + i * numberOfChannelsByLine;
  7307. var targetLine = height - i - 1;
  7308. var targetCell = j + targetLine * numberOfChannelsByLine;
  7309. var temp = data[currentCell];
  7310. data[currentCell] = data[targetCell];
  7311. data[targetCell] = temp;
  7312. }
  7313. }
  7314. // Create a 2D canvas to store the result
  7315. if (!screenshotCanvas) {
  7316. screenshotCanvas = document.createElement('canvas');
  7317. }
  7318. screenshotCanvas.width = width;
  7319. screenshotCanvas.height = height;
  7320. var context = screenshotCanvas.getContext('2d');
  7321. if (context) {
  7322. // Copy the pixels to a 2D canvas
  7323. var imageData = context.createImageData(width, height);
  7324. var castData = (imageData.data);
  7325. castData.set(data);
  7326. context.putImageData(imageData, 0, 0);
  7327. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  7328. }
  7329. };
  7330. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  7331. if (mimeType === void 0) { mimeType = "image/png"; }
  7332. var base64Image = screenshotCanvas.toDataURL(mimeType);
  7333. if (successCallback) {
  7334. successCallback(base64Image);
  7335. }
  7336. else {
  7337. // We need HTMLCanvasElement.toBlob for HD screenshots
  7338. if (!screenshotCanvas.toBlob) {
  7339. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  7340. screenshotCanvas.toBlob = function (callback, type, quality) {
  7341. var _this = this;
  7342. setTimeout(function () {
  7343. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  7344. for (var i = 0; i < len; i++) {
  7345. arr[i] = binStr.charCodeAt(i);
  7346. }
  7347. callback(new Blob([arr], { type: type || 'image/png' }));
  7348. });
  7349. };
  7350. }
  7351. screenshotCanvas.toBlob(function (blob) {
  7352. var url = URL.createObjectURL(blob);
  7353. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  7354. if (("download" in document.createElement("a"))) {
  7355. var a = window.document.createElement("a");
  7356. a.href = url;
  7357. if (fileName) {
  7358. a.setAttribute("download", fileName);
  7359. }
  7360. else {
  7361. var date = new Date();
  7362. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  7363. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  7364. }
  7365. window.document.body.appendChild(a);
  7366. a.addEventListener("click", function () {
  7367. if (a.parentElement) {
  7368. a.parentElement.removeChild(a);
  7369. }
  7370. });
  7371. a.click();
  7372. }
  7373. else {
  7374. var newWindow = window.open("");
  7375. if (!newWindow)
  7376. return;
  7377. var img = newWindow.document.createElement("img");
  7378. img.onload = function () {
  7379. // no longer need to read the blob so it's revoked
  7380. URL.revokeObjectURL(url);
  7381. };
  7382. img.src = url;
  7383. newWindow.document.body.appendChild(img);
  7384. }
  7385. });
  7386. }
  7387. };
  7388. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  7389. if (mimeType === void 0) { mimeType = "image/png"; }
  7390. var width;
  7391. var height;
  7392. // If a precision value is specified
  7393. if (size.precision) {
  7394. width = Math.round(engine.getRenderWidth() * size.precision);
  7395. height = Math.round(width / engine.getAspectRatio(camera));
  7396. }
  7397. else if (size.width && size.height) {
  7398. width = size.width;
  7399. height = size.height;
  7400. }
  7401. else if (size.width && !size.height) {
  7402. width = size.width;
  7403. height = Math.round(width / engine.getAspectRatio(camera));
  7404. }
  7405. else if (size.height && !size.width) {
  7406. height = size.height;
  7407. width = Math.round(height * engine.getAspectRatio(camera));
  7408. }
  7409. else if (!isNaN(size)) {
  7410. height = size;
  7411. width = size;
  7412. }
  7413. else {
  7414. Tools.Error("Invalid 'size' parameter !");
  7415. return;
  7416. }
  7417. if (!screenshotCanvas) {
  7418. screenshotCanvas = document.createElement('canvas');
  7419. }
  7420. screenshotCanvas.width = width;
  7421. screenshotCanvas.height = height;
  7422. var renderContext = screenshotCanvas.getContext("2d");
  7423. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  7424. var newWidth = width;
  7425. var newHeight = newWidth / ratio;
  7426. if (newHeight > height) {
  7427. newHeight = height;
  7428. newWidth = newHeight * ratio;
  7429. }
  7430. var offsetX = Math.max(0, width - newWidth) / 2;
  7431. var offsetY = Math.max(0, height - newHeight) / 2;
  7432. var renderingCanvas = engine.getRenderingCanvas();
  7433. if (renderContext && renderingCanvas) {
  7434. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  7435. }
  7436. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  7437. };
  7438. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  7439. if (mimeType === void 0) { mimeType = "image/png"; }
  7440. if (samples === void 0) { samples = 1; }
  7441. if (antialiasing === void 0) { antialiasing = false; }
  7442. var width;
  7443. var height;
  7444. //If a precision value is specified
  7445. if (size.precision) {
  7446. width = Math.round(engine.getRenderWidth() * size.precision);
  7447. height = Math.round(width / engine.getAspectRatio(camera));
  7448. size = { width: width, height: height };
  7449. }
  7450. else if (size.width && size.height) {
  7451. width = size.width;
  7452. height = size.height;
  7453. }
  7454. else if (size.width && !size.height) {
  7455. width = size.width;
  7456. height = Math.round(width / engine.getAspectRatio(camera));
  7457. size = { width: width, height: height };
  7458. }
  7459. else if (size.height && !size.width) {
  7460. height = size.height;
  7461. width = Math.round(height * engine.getAspectRatio(camera));
  7462. size = { width: width, height: height };
  7463. }
  7464. else if (!isNaN(size)) {
  7465. height = size;
  7466. width = size;
  7467. }
  7468. else {
  7469. Tools.Error("Invalid 'size' parameter !");
  7470. return;
  7471. }
  7472. var scene = camera.getScene();
  7473. var previousCamera = null;
  7474. if (scene.activeCamera !== camera) {
  7475. previousCamera = scene.activeCamera;
  7476. scene.activeCamera = camera;
  7477. }
  7478. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  7479. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7480. texture.renderList = null;
  7481. texture.samples = samples;
  7482. if (antialiasing) {
  7483. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  7484. }
  7485. texture.onAfterRenderObservable.add(function () {
  7486. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  7487. });
  7488. scene.incrementRenderId();
  7489. scene.resetCachedMaterial();
  7490. texture.render(true);
  7491. texture.dispose();
  7492. if (previousCamera) {
  7493. scene.activeCamera = previousCamera;
  7494. }
  7495. camera.getProjectionMatrix(true); // Force cache refresh;
  7496. };
  7497. // XHR response validator for local file scenario
  7498. Tools.ValidateXHRData = function (xhr, dataType) {
  7499. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  7500. if (dataType === void 0) { dataType = 7; }
  7501. try {
  7502. if (dataType & 1) {
  7503. if (xhr.responseText && xhr.responseText.length > 0) {
  7504. return true;
  7505. }
  7506. else if (dataType === 1) {
  7507. return false;
  7508. }
  7509. }
  7510. if (dataType & 2) {
  7511. // Check header width and height since there is no "TGA" magic number
  7512. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  7513. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  7514. return true;
  7515. }
  7516. else if (dataType === 2) {
  7517. return false;
  7518. }
  7519. }
  7520. if (dataType & 4) {
  7521. // Check for the "DDS" magic number
  7522. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  7523. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  7524. return true;
  7525. }
  7526. else {
  7527. return false;
  7528. }
  7529. }
  7530. }
  7531. catch (e) {
  7532. // Global protection
  7533. }
  7534. return false;
  7535. };
  7536. /**
  7537. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  7538. * Be aware Math.random() could cause collisions, but:
  7539. * "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"
  7540. */
  7541. Tools.RandomId = function () {
  7542. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  7543. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  7544. return v.toString(16);
  7545. });
  7546. };
  7547. Object.defineProperty(Tools, "NoneLogLevel", {
  7548. get: function () {
  7549. return Tools._NoneLogLevel;
  7550. },
  7551. enumerable: true,
  7552. configurable: true
  7553. });
  7554. Object.defineProperty(Tools, "MessageLogLevel", {
  7555. get: function () {
  7556. return Tools._MessageLogLevel;
  7557. },
  7558. enumerable: true,
  7559. configurable: true
  7560. });
  7561. Object.defineProperty(Tools, "WarningLogLevel", {
  7562. get: function () {
  7563. return Tools._WarningLogLevel;
  7564. },
  7565. enumerable: true,
  7566. configurable: true
  7567. });
  7568. Object.defineProperty(Tools, "ErrorLogLevel", {
  7569. get: function () {
  7570. return Tools._ErrorLogLevel;
  7571. },
  7572. enumerable: true,
  7573. configurable: true
  7574. });
  7575. Object.defineProperty(Tools, "AllLogLevel", {
  7576. get: function () {
  7577. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  7578. },
  7579. enumerable: true,
  7580. configurable: true
  7581. });
  7582. Tools._AddLogEntry = function (entry) {
  7583. Tools._LogCache = entry + Tools._LogCache;
  7584. if (Tools.OnNewCacheEntry) {
  7585. Tools.OnNewCacheEntry(entry);
  7586. }
  7587. };
  7588. Tools._FormatMessage = function (message) {
  7589. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  7590. var date = new Date();
  7591. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  7592. };
  7593. Tools._LogDisabled = function (message) {
  7594. // nothing to do
  7595. };
  7596. Tools._LogEnabled = function (message) {
  7597. var formattedMessage = Tools._FormatMessage(message);
  7598. console.log("BJS - " + formattedMessage);
  7599. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  7600. Tools._AddLogEntry(entry);
  7601. };
  7602. Tools._WarnDisabled = function (message) {
  7603. // nothing to do
  7604. };
  7605. Tools._WarnEnabled = function (message) {
  7606. var formattedMessage = Tools._FormatMessage(message);
  7607. console.warn("BJS - " + formattedMessage);
  7608. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  7609. Tools._AddLogEntry(entry);
  7610. };
  7611. Tools._ErrorDisabled = function (message) {
  7612. // nothing to do
  7613. };
  7614. Tools._ErrorEnabled = function (message) {
  7615. Tools.errorsCount++;
  7616. var formattedMessage = Tools._FormatMessage(message);
  7617. console.error("BJS - " + formattedMessage);
  7618. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  7619. Tools._AddLogEntry(entry);
  7620. };
  7621. Object.defineProperty(Tools, "LogCache", {
  7622. get: function () {
  7623. return Tools._LogCache;
  7624. },
  7625. enumerable: true,
  7626. configurable: true
  7627. });
  7628. Tools.ClearLogCache = function () {
  7629. Tools._LogCache = "";
  7630. Tools.errorsCount = 0;
  7631. };
  7632. Object.defineProperty(Tools, "LogLevels", {
  7633. set: function (level) {
  7634. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  7635. Tools.Log = Tools._LogEnabled;
  7636. }
  7637. else {
  7638. Tools.Log = Tools._LogDisabled;
  7639. }
  7640. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  7641. Tools.Warn = Tools._WarnEnabled;
  7642. }
  7643. else {
  7644. Tools.Warn = Tools._WarnDisabled;
  7645. }
  7646. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  7647. Tools.Error = Tools._ErrorEnabled;
  7648. }
  7649. else {
  7650. Tools.Error = Tools._ErrorDisabled;
  7651. }
  7652. },
  7653. enumerable: true,
  7654. configurable: true
  7655. });
  7656. Tools.IsWindowObjectExist = function () {
  7657. return (typeof window) !== "undefined";
  7658. };
  7659. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  7660. get: function () {
  7661. return Tools._PerformanceNoneLogLevel;
  7662. },
  7663. enumerable: true,
  7664. configurable: true
  7665. });
  7666. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  7667. get: function () {
  7668. return Tools._PerformanceUserMarkLogLevel;
  7669. },
  7670. enumerable: true,
  7671. configurable: true
  7672. });
  7673. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  7674. get: function () {
  7675. return Tools._PerformanceConsoleLogLevel;
  7676. },
  7677. enumerable: true,
  7678. configurable: true
  7679. });
  7680. Object.defineProperty(Tools, "PerformanceLogLevel", {
  7681. set: function (level) {
  7682. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  7683. Tools.StartPerformanceCounter = Tools._StartUserMark;
  7684. Tools.EndPerformanceCounter = Tools._EndUserMark;
  7685. return;
  7686. }
  7687. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  7688. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  7689. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  7690. return;
  7691. }
  7692. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7693. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7694. },
  7695. enumerable: true,
  7696. configurable: true
  7697. });
  7698. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  7699. };
  7700. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  7701. };
  7702. Tools._StartUserMark = function (counterName, condition) {
  7703. if (condition === void 0) { condition = true; }
  7704. if (!Tools._performance) {
  7705. if (!Tools.IsWindowObjectExist()) {
  7706. return;
  7707. }
  7708. Tools._performance = window.performance;
  7709. }
  7710. if (!condition || !Tools._performance.mark) {
  7711. return;
  7712. }
  7713. Tools._performance.mark(counterName + "-Begin");
  7714. };
  7715. Tools._EndUserMark = function (counterName, condition) {
  7716. if (condition === void 0) { condition = true; }
  7717. if (!condition || !Tools._performance.mark) {
  7718. return;
  7719. }
  7720. Tools._performance.mark(counterName + "-End");
  7721. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  7722. };
  7723. Tools._StartPerformanceConsole = function (counterName, condition) {
  7724. if (condition === void 0) { condition = true; }
  7725. if (!condition) {
  7726. return;
  7727. }
  7728. Tools._StartUserMark(counterName, condition);
  7729. if (console.time) {
  7730. console.time(counterName);
  7731. }
  7732. };
  7733. Tools._EndPerformanceConsole = function (counterName, condition) {
  7734. if (condition === void 0) { condition = true; }
  7735. if (!condition) {
  7736. return;
  7737. }
  7738. Tools._EndUserMark(counterName, condition);
  7739. if (console.time) {
  7740. console.timeEnd(counterName);
  7741. }
  7742. };
  7743. Object.defineProperty(Tools, "Now", {
  7744. get: function () {
  7745. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  7746. return window.performance.now();
  7747. }
  7748. return new Date().getTime();
  7749. },
  7750. enumerable: true,
  7751. configurable: true
  7752. });
  7753. /**
  7754. * This method will return the name of the class used to create the instance of the given object.
  7755. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  7756. * @param object the object to get the class name from
  7757. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  7758. */
  7759. Tools.GetClassName = function (object, isType) {
  7760. if (isType === void 0) { isType = false; }
  7761. var name = null;
  7762. if (!isType && object.getClassName) {
  7763. name = object.getClassName();
  7764. }
  7765. else {
  7766. if (object instanceof Object) {
  7767. var classObj = isType ? object : Object.getPrototypeOf(object);
  7768. name = classObj.constructor["__bjsclassName__"];
  7769. }
  7770. if (!name) {
  7771. name = typeof object;
  7772. }
  7773. }
  7774. return name;
  7775. };
  7776. Tools.First = function (array, predicate) {
  7777. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  7778. var el = array_1[_i];
  7779. if (predicate(el)) {
  7780. return el;
  7781. }
  7782. }
  7783. return null;
  7784. };
  7785. /**
  7786. * This method will return the name of the full name of the class, including its owning module (if any).
  7787. * 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).
  7788. * @param object the object to get the class name from
  7789. * @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.
  7790. */
  7791. Tools.getFullClassName = function (object, isType) {
  7792. if (isType === void 0) { isType = false; }
  7793. var className = null;
  7794. var moduleName = null;
  7795. if (!isType && object.getClassName) {
  7796. className = object.getClassName();
  7797. }
  7798. else {
  7799. if (object instanceof Object) {
  7800. var classObj = isType ? object : Object.getPrototypeOf(object);
  7801. className = classObj.constructor["__bjsclassName__"];
  7802. moduleName = classObj.constructor["__bjsmoduleName__"];
  7803. }
  7804. if (!className) {
  7805. className = typeof object;
  7806. }
  7807. }
  7808. if (!className) {
  7809. return null;
  7810. }
  7811. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  7812. };
  7813. /**
  7814. * 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.
  7815. * @param array
  7816. */
  7817. Tools.arrayOrStringFeeder = function (array) {
  7818. return function (index) {
  7819. if (index >= array.length) {
  7820. return null;
  7821. }
  7822. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  7823. if (val && val.getHashCode) {
  7824. val = val.getHashCode();
  7825. }
  7826. if (typeof val === "string") {
  7827. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  7828. }
  7829. return val;
  7830. };
  7831. };
  7832. /**
  7833. * Compute the hashCode of a stream of number
  7834. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  7835. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  7836. * @return the hash code computed
  7837. */
  7838. Tools.hashCodeFromStream = function (feeder) {
  7839. // Based from here: http://stackoverflow.com/a/7616484/802124
  7840. var hash = 0;
  7841. var index = 0;
  7842. var chr = feeder(index++);
  7843. while (chr != null) {
  7844. hash = ((hash << 5) - hash) + chr;
  7845. hash |= 0; // Convert to 32bit integer
  7846. chr = feeder(index++);
  7847. }
  7848. return hash;
  7849. };
  7850. Tools.BaseUrl = "";
  7851. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  7852. /**
  7853. * Default behaviour for cors in the application.
  7854. * It can be a string if the expected behavior is identical in the entire app.
  7855. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  7856. */
  7857. Tools.CorsBehavior = "anonymous";
  7858. Tools.UseFallbackTexture = true;
  7859. /**
  7860. * Use this object to register external classes like custom textures or material
  7861. * to allow the laoders to instantiate them
  7862. */
  7863. Tools.RegisteredExternalClasses = {};
  7864. // Used in case of a texture loading problem
  7865. 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";
  7866. Tools.PreprocessUrl = function (url) {
  7867. return url;
  7868. };
  7869. // Logs
  7870. Tools._NoneLogLevel = 0;
  7871. Tools._MessageLogLevel = 1;
  7872. Tools._WarningLogLevel = 2;
  7873. Tools._ErrorLogLevel = 4;
  7874. Tools._LogCache = "";
  7875. Tools.errorsCount = 0;
  7876. Tools.Log = Tools._LogEnabled;
  7877. Tools.Warn = Tools._WarnEnabled;
  7878. Tools.Error = Tools._ErrorEnabled;
  7879. // Performances
  7880. Tools._PerformanceNoneLogLevel = 0;
  7881. Tools._PerformanceUserMarkLogLevel = 1;
  7882. Tools._PerformanceConsoleLogLevel = 2;
  7883. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7884. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7885. return Tools;
  7886. }());
  7887. BABYLON.Tools = Tools;
  7888. /**
  7889. * This class is used to track a performance counter which is number based.
  7890. * The user has access to many properties which give statistics of different nature
  7891. *
  7892. * The implementer can track two kinds of Performance Counter: time and count
  7893. * 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.
  7894. * 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.
  7895. */
  7896. var PerfCounter = /** @class */ (function () {
  7897. function PerfCounter() {
  7898. this._startMonitoringTime = 0;
  7899. this._min = 0;
  7900. this._max = 0;
  7901. this._average = 0;
  7902. this._lastSecAverage = 0;
  7903. this._current = 0;
  7904. this._totalValueCount = 0;
  7905. this._totalAccumulated = 0;
  7906. this._lastSecAccumulated = 0;
  7907. this._lastSecTime = 0;
  7908. this._lastSecValueCount = 0;
  7909. }
  7910. Object.defineProperty(PerfCounter.prototype, "min", {
  7911. /**
  7912. * Returns the smallest value ever
  7913. */
  7914. get: function () {
  7915. return this._min;
  7916. },
  7917. enumerable: true,
  7918. configurable: true
  7919. });
  7920. Object.defineProperty(PerfCounter.prototype, "max", {
  7921. /**
  7922. * Returns the biggest value ever
  7923. */
  7924. get: function () {
  7925. return this._max;
  7926. },
  7927. enumerable: true,
  7928. configurable: true
  7929. });
  7930. Object.defineProperty(PerfCounter.prototype, "average", {
  7931. /**
  7932. * Returns the average value since the performance counter is running
  7933. */
  7934. get: function () {
  7935. return this._average;
  7936. },
  7937. enumerable: true,
  7938. configurable: true
  7939. });
  7940. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  7941. /**
  7942. * Returns the average value of the last second the counter was monitored
  7943. */
  7944. get: function () {
  7945. return this._lastSecAverage;
  7946. },
  7947. enumerable: true,
  7948. configurable: true
  7949. });
  7950. Object.defineProperty(PerfCounter.prototype, "current", {
  7951. /**
  7952. * Returns the current value
  7953. */
  7954. get: function () {
  7955. return this._current;
  7956. },
  7957. enumerable: true,
  7958. configurable: true
  7959. });
  7960. Object.defineProperty(PerfCounter.prototype, "total", {
  7961. get: function () {
  7962. return this._totalAccumulated;
  7963. },
  7964. enumerable: true,
  7965. configurable: true
  7966. });
  7967. Object.defineProperty(PerfCounter.prototype, "count", {
  7968. get: function () {
  7969. return this._totalValueCount;
  7970. },
  7971. enumerable: true,
  7972. configurable: true
  7973. });
  7974. /**
  7975. * Call this method to start monitoring a new frame.
  7976. * 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.
  7977. */
  7978. PerfCounter.prototype.fetchNewFrame = function () {
  7979. this._totalValueCount++;
  7980. this._current = 0;
  7981. this._lastSecValueCount++;
  7982. };
  7983. /**
  7984. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  7985. * @param newCount the count value to add to the monitored count
  7986. * @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.
  7987. */
  7988. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  7989. if (!PerfCounter.Enabled) {
  7990. return;
  7991. }
  7992. this._current += newCount;
  7993. if (fetchResult) {
  7994. this._fetchResult();
  7995. }
  7996. };
  7997. /**
  7998. * Start monitoring this performance counter
  7999. */
  8000. PerfCounter.prototype.beginMonitoring = function () {
  8001. if (!PerfCounter.Enabled) {
  8002. return;
  8003. }
  8004. this._startMonitoringTime = Tools.Now;
  8005. };
  8006. /**
  8007. * Compute the time lapsed since the previous beginMonitoring() call.
  8008. * @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
  8009. */
  8010. PerfCounter.prototype.endMonitoring = function (newFrame) {
  8011. if (newFrame === void 0) { newFrame = true; }
  8012. if (!PerfCounter.Enabled) {
  8013. return;
  8014. }
  8015. if (newFrame) {
  8016. this.fetchNewFrame();
  8017. }
  8018. var currentTime = Tools.Now;
  8019. this._current = currentTime - this._startMonitoringTime;
  8020. if (newFrame) {
  8021. this._fetchResult();
  8022. }
  8023. };
  8024. PerfCounter.prototype._fetchResult = function () {
  8025. this._totalAccumulated += this._current;
  8026. this._lastSecAccumulated += this._current;
  8027. // Min/Max update
  8028. this._min = Math.min(this._min, this._current);
  8029. this._max = Math.max(this._max, this._current);
  8030. this._average = this._totalAccumulated / this._totalValueCount;
  8031. // Reset last sec?
  8032. var now = Tools.Now;
  8033. if ((now - this._lastSecTime) > 1000) {
  8034. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  8035. this._lastSecTime = now;
  8036. this._lastSecAccumulated = 0;
  8037. this._lastSecValueCount = 0;
  8038. }
  8039. };
  8040. PerfCounter.Enabled = true;
  8041. return PerfCounter;
  8042. }());
  8043. BABYLON.PerfCounter = PerfCounter;
  8044. /**
  8045. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  8046. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  8047. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  8048. * @param name The name of the class, case should be preserved
  8049. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  8050. */
  8051. function className(name, module) {
  8052. return function (target) {
  8053. target["__bjsclassName__"] = name;
  8054. target["__bjsmoduleName__"] = (module != null) ? module : null;
  8055. };
  8056. }
  8057. BABYLON.className = className;
  8058. /**
  8059. * An implementation of a loop for asynchronous functions.
  8060. */
  8061. var AsyncLoop = /** @class */ (function () {
  8062. /**
  8063. * Constroctor.
  8064. * @param iterations the number of iterations.
  8065. * @param _fn the function to run each iteration
  8066. * @param _successCallback the callback that will be called upon succesful execution
  8067. * @param offset starting offset.
  8068. */
  8069. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  8070. if (offset === void 0) { offset = 0; }
  8071. this.iterations = iterations;
  8072. this._fn = _fn;
  8073. this._successCallback = _successCallback;
  8074. this.index = offset - 1;
  8075. this._done = false;
  8076. }
  8077. /**
  8078. * Execute the next iteration. Must be called after the last iteration was finished.
  8079. */
  8080. AsyncLoop.prototype.executeNext = function () {
  8081. if (!this._done) {
  8082. if (this.index + 1 < this.iterations) {
  8083. ++this.index;
  8084. this._fn(this);
  8085. }
  8086. else {
  8087. this.breakLoop();
  8088. }
  8089. }
  8090. };
  8091. /**
  8092. * Break the loop and run the success callback.
  8093. */
  8094. AsyncLoop.prototype.breakLoop = function () {
  8095. this._done = true;
  8096. this._successCallback();
  8097. };
  8098. /**
  8099. * Helper function
  8100. */
  8101. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  8102. if (offset === void 0) { offset = 0; }
  8103. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  8104. loop.executeNext();
  8105. return loop;
  8106. };
  8107. /**
  8108. * A for-loop that will run a given number of iterations synchronous and the rest async.
  8109. * @param iterations total number of iterations
  8110. * @param syncedIterations number of synchronous iterations in each async iteration.
  8111. * @param fn the function to call each iteration.
  8112. * @param callback a success call back that will be called when iterating stops.
  8113. * @param breakFunction a break condition (optional)
  8114. * @param timeout timeout settings for the setTimeout function. default - 0.
  8115. * @constructor
  8116. */
  8117. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  8118. if (timeout === void 0) { timeout = 0; }
  8119. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  8120. if (breakFunction && breakFunction())
  8121. loop.breakLoop();
  8122. else {
  8123. setTimeout(function () {
  8124. for (var i = 0; i < syncedIterations; ++i) {
  8125. var iteration = (loop.index * syncedIterations) + i;
  8126. if (iteration >= iterations)
  8127. break;
  8128. fn(iteration);
  8129. if (breakFunction && breakFunction()) {
  8130. loop.breakLoop();
  8131. break;
  8132. }
  8133. }
  8134. loop.executeNext();
  8135. }, timeout);
  8136. }
  8137. }, callback);
  8138. };
  8139. return AsyncLoop;
  8140. }());
  8141. BABYLON.AsyncLoop = AsyncLoop;
  8142. })(BABYLON || (BABYLON = {}));
  8143. //# sourceMappingURL=babylon.tools.js.map
  8144. var BABYLON;
  8145. (function (BABYLON) {
  8146. var _AlphaState = /** @class */ (function () {
  8147. /**
  8148. * Initializes the state.
  8149. */
  8150. function _AlphaState() {
  8151. this._isAlphaBlendDirty = false;
  8152. this._isBlendFunctionParametersDirty = false;
  8153. this._isBlendEquationParametersDirty = false;
  8154. this._isBlendConstantsDirty = false;
  8155. this._alphaBlend = false;
  8156. this._blendFunctionParameters = new Array(4);
  8157. this._blendEquationParameters = new Array(2);
  8158. this._blendConstants = new Array(4);
  8159. this.reset();
  8160. }
  8161. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  8162. get: function () {
  8163. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  8164. },
  8165. enumerable: true,
  8166. configurable: true
  8167. });
  8168. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  8169. get: function () {
  8170. return this._alphaBlend;
  8171. },
  8172. set: function (value) {
  8173. if (this._alphaBlend === value) {
  8174. return;
  8175. }
  8176. this._alphaBlend = value;
  8177. this._isAlphaBlendDirty = true;
  8178. },
  8179. enumerable: true,
  8180. configurable: true
  8181. });
  8182. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  8183. if (this._blendConstants[0] === r &&
  8184. this._blendConstants[1] === g &&
  8185. this._blendConstants[2] === b &&
  8186. this._blendConstants[3] === a) {
  8187. return;
  8188. }
  8189. this._blendConstants[0] = r;
  8190. this._blendConstants[1] = g;
  8191. this._blendConstants[2] = b;
  8192. this._blendConstants[3] = a;
  8193. this._isBlendConstantsDirty = true;
  8194. };
  8195. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  8196. if (this._blendFunctionParameters[0] === value0 &&
  8197. this._blendFunctionParameters[1] === value1 &&
  8198. this._blendFunctionParameters[2] === value2 &&
  8199. this._blendFunctionParameters[3] === value3) {
  8200. return;
  8201. }
  8202. this._blendFunctionParameters[0] = value0;
  8203. this._blendFunctionParameters[1] = value1;
  8204. this._blendFunctionParameters[2] = value2;
  8205. this._blendFunctionParameters[3] = value3;
  8206. this._isBlendFunctionParametersDirty = true;
  8207. };
  8208. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  8209. if (this._blendEquationParameters[0] === rgb &&
  8210. this._blendEquationParameters[1] === alpha) {
  8211. return;
  8212. }
  8213. this._blendEquationParameters[0] = rgb;
  8214. this._blendEquationParameters[1] = alpha;
  8215. this._isBlendEquationParametersDirty = true;
  8216. };
  8217. _AlphaState.prototype.reset = function () {
  8218. this._alphaBlend = false;
  8219. this._blendFunctionParameters[0] = null;
  8220. this._blendFunctionParameters[1] = null;
  8221. this._blendFunctionParameters[2] = null;
  8222. this._blendFunctionParameters[3] = null;
  8223. this._blendEquationParameters[0] = null;
  8224. this._blendEquationParameters[1] = null;
  8225. this._blendConstants[0] = null;
  8226. this._blendConstants[1] = null;
  8227. this._blendConstants[2] = null;
  8228. this._blendConstants[3] = null;
  8229. this._isAlphaBlendDirty = true;
  8230. this._isBlendFunctionParametersDirty = false;
  8231. this._isBlendEquationParametersDirty = false;
  8232. this._isBlendConstantsDirty = false;
  8233. };
  8234. _AlphaState.prototype.apply = function (gl) {
  8235. if (!this.isDirty) {
  8236. return;
  8237. }
  8238. // Alpha blend
  8239. if (this._isAlphaBlendDirty) {
  8240. if (this._alphaBlend) {
  8241. gl.enable(gl.BLEND);
  8242. }
  8243. else {
  8244. gl.disable(gl.BLEND);
  8245. }
  8246. this._isAlphaBlendDirty = false;
  8247. }
  8248. // Alpha function
  8249. if (this._isBlendFunctionParametersDirty) {
  8250. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  8251. this._isBlendFunctionParametersDirty = false;
  8252. }
  8253. // Alpha equation
  8254. if (this._isBlendEquationParametersDirty) {
  8255. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  8256. this._isBlendEquationParametersDirty = false;
  8257. }
  8258. // Constants
  8259. if (this._isBlendConstantsDirty) {
  8260. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  8261. this._isBlendConstantsDirty = false;
  8262. }
  8263. };
  8264. return _AlphaState;
  8265. }());
  8266. BABYLON._AlphaState = _AlphaState;
  8267. })(BABYLON || (BABYLON = {}));
  8268. //# sourceMappingURL=babylon.alphaCullingState.js.map
  8269. var BABYLON;
  8270. (function (BABYLON) {
  8271. var _DepthCullingState = /** @class */ (function () {
  8272. /**
  8273. * Initializes the state.
  8274. */
  8275. function _DepthCullingState() {
  8276. this._isDepthTestDirty = false;
  8277. this._isDepthMaskDirty = false;
  8278. this._isDepthFuncDirty = false;
  8279. this._isCullFaceDirty = false;
  8280. this._isCullDirty = false;
  8281. this._isZOffsetDirty = false;
  8282. this._isFrontFaceDirty = false;
  8283. this.reset();
  8284. }
  8285. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  8286. get: function () {
  8287. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  8288. },
  8289. enumerable: true,
  8290. configurable: true
  8291. });
  8292. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  8293. get: function () {
  8294. return this._zOffset;
  8295. },
  8296. set: function (value) {
  8297. if (this._zOffset === value) {
  8298. return;
  8299. }
  8300. this._zOffset = value;
  8301. this._isZOffsetDirty = true;
  8302. },
  8303. enumerable: true,
  8304. configurable: true
  8305. });
  8306. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  8307. get: function () {
  8308. return this._cullFace;
  8309. },
  8310. set: function (value) {
  8311. if (this._cullFace === value) {
  8312. return;
  8313. }
  8314. this._cullFace = value;
  8315. this._isCullFaceDirty = true;
  8316. },
  8317. enumerable: true,
  8318. configurable: true
  8319. });
  8320. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  8321. get: function () {
  8322. return this._cull;
  8323. },
  8324. set: function (value) {
  8325. if (this._cull === value) {
  8326. return;
  8327. }
  8328. this._cull = value;
  8329. this._isCullDirty = true;
  8330. },
  8331. enumerable: true,
  8332. configurable: true
  8333. });
  8334. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  8335. get: function () {
  8336. return this._depthFunc;
  8337. },
  8338. set: function (value) {
  8339. if (this._depthFunc === value) {
  8340. return;
  8341. }
  8342. this._depthFunc = value;
  8343. this._isDepthFuncDirty = true;
  8344. },
  8345. enumerable: true,
  8346. configurable: true
  8347. });
  8348. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  8349. get: function () {
  8350. return this._depthMask;
  8351. },
  8352. set: function (value) {
  8353. if (this._depthMask === value) {
  8354. return;
  8355. }
  8356. this._depthMask = value;
  8357. this._isDepthMaskDirty = true;
  8358. },
  8359. enumerable: true,
  8360. configurable: true
  8361. });
  8362. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  8363. get: function () {
  8364. return this._depthTest;
  8365. },
  8366. set: function (value) {
  8367. if (this._depthTest === value) {
  8368. return;
  8369. }
  8370. this._depthTest = value;
  8371. this._isDepthTestDirty = true;
  8372. },
  8373. enumerable: true,
  8374. configurable: true
  8375. });
  8376. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  8377. get: function () {
  8378. return this._frontFace;
  8379. },
  8380. set: function (value) {
  8381. if (this._frontFace === value) {
  8382. return;
  8383. }
  8384. this._frontFace = value;
  8385. this._isFrontFaceDirty = true;
  8386. },
  8387. enumerable: true,
  8388. configurable: true
  8389. });
  8390. _DepthCullingState.prototype.reset = function () {
  8391. this._depthMask = true;
  8392. this._depthTest = true;
  8393. this._depthFunc = null;
  8394. this._cullFace = null;
  8395. this._cull = null;
  8396. this._zOffset = 0;
  8397. this._frontFace = null;
  8398. this._isDepthTestDirty = true;
  8399. this._isDepthMaskDirty = true;
  8400. this._isDepthFuncDirty = false;
  8401. this._isCullFaceDirty = false;
  8402. this._isCullDirty = false;
  8403. this._isZOffsetDirty = false;
  8404. this._isFrontFaceDirty = false;
  8405. };
  8406. _DepthCullingState.prototype.apply = function (gl) {
  8407. if (!this.isDirty) {
  8408. return;
  8409. }
  8410. // Cull
  8411. if (this._isCullDirty) {
  8412. if (this.cull) {
  8413. gl.enable(gl.CULL_FACE);
  8414. }
  8415. else {
  8416. gl.disable(gl.CULL_FACE);
  8417. }
  8418. this._isCullDirty = false;
  8419. }
  8420. // Cull face
  8421. if (this._isCullFaceDirty) {
  8422. gl.cullFace(this.cullFace);
  8423. this._isCullFaceDirty = false;
  8424. }
  8425. // Depth mask
  8426. if (this._isDepthMaskDirty) {
  8427. gl.depthMask(this.depthMask);
  8428. this._isDepthMaskDirty = false;
  8429. }
  8430. // Depth test
  8431. if (this._isDepthTestDirty) {
  8432. if (this.depthTest) {
  8433. gl.enable(gl.DEPTH_TEST);
  8434. }
  8435. else {
  8436. gl.disable(gl.DEPTH_TEST);
  8437. }
  8438. this._isDepthTestDirty = false;
  8439. }
  8440. // Depth func
  8441. if (this._isDepthFuncDirty) {
  8442. gl.depthFunc(this.depthFunc);
  8443. this._isDepthFuncDirty = false;
  8444. }
  8445. // zOffset
  8446. if (this._isZOffsetDirty) {
  8447. if (this.zOffset) {
  8448. gl.enable(gl.POLYGON_OFFSET_FILL);
  8449. gl.polygonOffset(this.zOffset, 0);
  8450. }
  8451. else {
  8452. gl.disable(gl.POLYGON_OFFSET_FILL);
  8453. }
  8454. this._isZOffsetDirty = false;
  8455. }
  8456. // Front face
  8457. if (this._isFrontFaceDirty) {
  8458. gl.frontFace(this.frontFace);
  8459. this._isFrontFaceDirty = false;
  8460. }
  8461. };
  8462. return _DepthCullingState;
  8463. }());
  8464. BABYLON._DepthCullingState = _DepthCullingState;
  8465. })(BABYLON || (BABYLON = {}));
  8466. //# sourceMappingURL=babylon.depthCullingState.js.map
  8467. var BABYLON;
  8468. (function (BABYLON) {
  8469. var _StencilState = /** @class */ (function () {
  8470. function _StencilState() {
  8471. this._isStencilTestDirty = false;
  8472. this._isStencilMaskDirty = false;
  8473. this._isStencilFuncDirty = false;
  8474. this._isStencilOpDirty = false;
  8475. this.reset();
  8476. }
  8477. Object.defineProperty(_StencilState.prototype, "isDirty", {
  8478. get: function () {
  8479. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  8480. },
  8481. enumerable: true,
  8482. configurable: true
  8483. });
  8484. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  8485. get: function () {
  8486. return this._stencilFunc;
  8487. },
  8488. set: function (value) {
  8489. if (this._stencilFunc === value) {
  8490. return;
  8491. }
  8492. this._stencilFunc = value;
  8493. this._isStencilFuncDirty = true;
  8494. },
  8495. enumerable: true,
  8496. configurable: true
  8497. });
  8498. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  8499. get: function () {
  8500. return this._stencilFuncRef;
  8501. },
  8502. set: function (value) {
  8503. if (this._stencilFuncRef === value) {
  8504. return;
  8505. }
  8506. this._stencilFuncRef = value;
  8507. this._isStencilFuncDirty = true;
  8508. },
  8509. enumerable: true,
  8510. configurable: true
  8511. });
  8512. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  8513. get: function () {
  8514. return this._stencilFuncMask;
  8515. },
  8516. set: function (value) {
  8517. if (this._stencilFuncMask === value) {
  8518. return;
  8519. }
  8520. this._stencilFuncMask = value;
  8521. this._isStencilFuncDirty = true;
  8522. },
  8523. enumerable: true,
  8524. configurable: true
  8525. });
  8526. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  8527. get: function () {
  8528. return this._stencilOpStencilFail;
  8529. },
  8530. set: function (value) {
  8531. if (this._stencilOpStencilFail === value) {
  8532. return;
  8533. }
  8534. this._stencilOpStencilFail = value;
  8535. this._isStencilOpDirty = true;
  8536. },
  8537. enumerable: true,
  8538. configurable: true
  8539. });
  8540. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  8541. get: function () {
  8542. return this._stencilOpDepthFail;
  8543. },
  8544. set: function (value) {
  8545. if (this._stencilOpDepthFail === value) {
  8546. return;
  8547. }
  8548. this._stencilOpDepthFail = value;
  8549. this._isStencilOpDirty = true;
  8550. },
  8551. enumerable: true,
  8552. configurable: true
  8553. });
  8554. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  8555. get: function () {
  8556. return this._stencilOpStencilDepthPass;
  8557. },
  8558. set: function (value) {
  8559. if (this._stencilOpStencilDepthPass === value) {
  8560. return;
  8561. }
  8562. this._stencilOpStencilDepthPass = value;
  8563. this._isStencilOpDirty = true;
  8564. },
  8565. enumerable: true,
  8566. configurable: true
  8567. });
  8568. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  8569. get: function () {
  8570. return this._stencilMask;
  8571. },
  8572. set: function (value) {
  8573. if (this._stencilMask === value) {
  8574. return;
  8575. }
  8576. this._stencilMask = value;
  8577. this._isStencilMaskDirty = true;
  8578. },
  8579. enumerable: true,
  8580. configurable: true
  8581. });
  8582. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  8583. get: function () {
  8584. return this._stencilTest;
  8585. },
  8586. set: function (value) {
  8587. if (this._stencilTest === value) {
  8588. return;
  8589. }
  8590. this._stencilTest = value;
  8591. this._isStencilTestDirty = true;
  8592. },
  8593. enumerable: true,
  8594. configurable: true
  8595. });
  8596. _StencilState.prototype.reset = function () {
  8597. this._stencilTest = false;
  8598. this._stencilMask = 0xFF;
  8599. this._stencilFunc = BABYLON.Engine.ALWAYS;
  8600. this._stencilFuncRef = 1;
  8601. this._stencilFuncMask = 0xFF;
  8602. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  8603. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  8604. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  8605. this._isStencilTestDirty = true;
  8606. this._isStencilMaskDirty = true;
  8607. this._isStencilFuncDirty = true;
  8608. this._isStencilOpDirty = true;
  8609. };
  8610. _StencilState.prototype.apply = function (gl) {
  8611. if (!this.isDirty) {
  8612. return;
  8613. }
  8614. // Stencil test
  8615. if (this._isStencilTestDirty) {
  8616. if (this.stencilTest) {
  8617. gl.enable(gl.STENCIL_TEST);
  8618. }
  8619. else {
  8620. gl.disable(gl.STENCIL_TEST);
  8621. }
  8622. this._isStencilTestDirty = false;
  8623. }
  8624. // Stencil mask
  8625. if (this._isStencilMaskDirty) {
  8626. gl.stencilMask(this.stencilMask);
  8627. this._isStencilMaskDirty = false;
  8628. }
  8629. // Stencil func
  8630. if (this._isStencilFuncDirty) {
  8631. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  8632. this._isStencilFuncDirty = false;
  8633. }
  8634. // Stencil op
  8635. if (this._isStencilOpDirty) {
  8636. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  8637. this._isStencilOpDirty = false;
  8638. }
  8639. };
  8640. return _StencilState;
  8641. }());
  8642. BABYLON._StencilState = _StencilState;
  8643. })(BABYLON || (BABYLON = {}));
  8644. //# sourceMappingURL=babylon.stencilState.js.map
  8645. var BABYLON;
  8646. (function (BABYLON) {
  8647. var compileShader = function (gl, source, type, defines, shaderVersion) {
  8648. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  8649. };
  8650. var compileRawShader = function (gl, source, type) {
  8651. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  8652. gl.shaderSource(shader, source);
  8653. gl.compileShader(shader);
  8654. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  8655. var log = gl.getShaderInfoLog(shader);
  8656. if (log) {
  8657. throw new Error(log);
  8658. }
  8659. }
  8660. if (!shader) {
  8661. throw new Error("Something went wrong while compile the shader.");
  8662. }
  8663. return shader;
  8664. };
  8665. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  8666. var magFilter = gl.NEAREST;
  8667. var minFilter = gl.NEAREST;
  8668. switch (samplingMode) {
  8669. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  8670. magFilter = gl.LINEAR;
  8671. if (generateMipMaps) {
  8672. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  8673. }
  8674. else {
  8675. minFilter = gl.LINEAR;
  8676. }
  8677. break;
  8678. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  8679. magFilter = gl.LINEAR;
  8680. if (generateMipMaps) {
  8681. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  8682. }
  8683. else {
  8684. minFilter = gl.LINEAR;
  8685. }
  8686. break;
  8687. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  8688. magFilter = gl.NEAREST;
  8689. if (generateMipMaps) {
  8690. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  8691. }
  8692. else {
  8693. minFilter = gl.NEAREST;
  8694. }
  8695. break;
  8696. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  8697. magFilter = gl.NEAREST;
  8698. if (generateMipMaps) {
  8699. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  8700. }
  8701. else {
  8702. minFilter = gl.NEAREST;
  8703. }
  8704. break;
  8705. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  8706. magFilter = gl.NEAREST;
  8707. if (generateMipMaps) {
  8708. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  8709. }
  8710. else {
  8711. minFilter = gl.LINEAR;
  8712. }
  8713. break;
  8714. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  8715. magFilter = gl.NEAREST;
  8716. if (generateMipMaps) {
  8717. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  8718. }
  8719. else {
  8720. minFilter = gl.LINEAR;
  8721. }
  8722. break;
  8723. case BABYLON.Texture.NEAREST_LINEAR:
  8724. magFilter = gl.NEAREST;
  8725. minFilter = gl.LINEAR;
  8726. break;
  8727. case BABYLON.Texture.NEAREST_NEAREST:
  8728. magFilter = gl.NEAREST;
  8729. minFilter = gl.NEAREST;
  8730. break;
  8731. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  8732. magFilter = gl.LINEAR;
  8733. if (generateMipMaps) {
  8734. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  8735. }
  8736. else {
  8737. minFilter = gl.NEAREST;
  8738. }
  8739. break;
  8740. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  8741. magFilter = gl.LINEAR;
  8742. if (generateMipMaps) {
  8743. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  8744. }
  8745. else {
  8746. minFilter = gl.NEAREST;
  8747. }
  8748. break;
  8749. case BABYLON.Texture.LINEAR_LINEAR:
  8750. magFilter = gl.LINEAR;
  8751. minFilter = gl.LINEAR;
  8752. break;
  8753. case BABYLON.Texture.LINEAR_NEAREST:
  8754. magFilter = gl.LINEAR;
  8755. minFilter = gl.NEAREST;
  8756. break;
  8757. }
  8758. return {
  8759. min: minFilter,
  8760. mag: magFilter
  8761. };
  8762. };
  8763. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  8764. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  8765. var img;
  8766. var onload = function () {
  8767. loadedImages[index] = img;
  8768. loadedImages._internalCount++;
  8769. if (scene) {
  8770. scene._removePendingData(img);
  8771. }
  8772. if (loadedImages._internalCount === 6) {
  8773. onfinish(loadedImages);
  8774. }
  8775. };
  8776. var onerror = function (message, exception) {
  8777. if (scene) {
  8778. scene._removePendingData(img);
  8779. }
  8780. if (onErrorCallBack) {
  8781. onErrorCallBack(message, exception);
  8782. }
  8783. };
  8784. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  8785. if (scene) {
  8786. scene._addPendingData(img);
  8787. }
  8788. };
  8789. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  8790. if (onError === void 0) { onError = null; }
  8791. var loadedImages = [];
  8792. loadedImages._internalCount = 0;
  8793. for (var index = 0; index < 6; index++) {
  8794. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  8795. }
  8796. };
  8797. var BufferPointer = /** @class */ (function () {
  8798. function BufferPointer() {
  8799. }
  8800. return BufferPointer;
  8801. }());
  8802. var InstancingAttributeInfo = /** @class */ (function () {
  8803. function InstancingAttributeInfo() {
  8804. }
  8805. return InstancingAttributeInfo;
  8806. }());
  8807. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  8808. /**
  8809. * Define options used to create a render target texture
  8810. */
  8811. var RenderTargetCreationOptions = /** @class */ (function () {
  8812. function RenderTargetCreationOptions() {
  8813. }
  8814. return RenderTargetCreationOptions;
  8815. }());
  8816. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  8817. /**
  8818. * Regroup several parameters relative to the browser in use
  8819. */
  8820. var EngineCapabilities = /** @class */ (function () {
  8821. function EngineCapabilities() {
  8822. }
  8823. return EngineCapabilities;
  8824. }());
  8825. BABYLON.EngineCapabilities = EngineCapabilities;
  8826. /**
  8827. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  8828. */
  8829. var Engine = /** @class */ (function () {
  8830. /**
  8831. * @constructor
  8832. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  8833. * @param {boolean} [antialias] - enable antialias
  8834. * @param options - further options to be sent to the getContext function
  8835. */
  8836. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  8837. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  8838. var _this = this;
  8839. // Public members
  8840. this.forcePOTTextures = false;
  8841. this.isFullscreen = false;
  8842. this.isPointerLock = false;
  8843. this.cullBackFaces = true;
  8844. this.renderEvenInBackground = true;
  8845. this.preventCacheWipeBetweenFrames = false;
  8846. // To enable/disable IDB support and avoid XHR on .manifest
  8847. this.enableOfflineSupport = false;
  8848. this.scenes = new Array();
  8849. this.postProcesses = new Array();
  8850. // Observables
  8851. /**
  8852. * Observable event triggered each time the rendering canvas is resized
  8853. */
  8854. this.onResizeObservable = new BABYLON.Observable();
  8855. /**
  8856. * Observable event triggered each time the canvas loses focus
  8857. */
  8858. this.onCanvasBlurObservable = new BABYLON.Observable();
  8859. /**
  8860. * Observable event triggered each time the canvas gains focus
  8861. */
  8862. this.onCanvasFocusObservable = new BABYLON.Observable();
  8863. /**
  8864. * Observable event triggered each time the canvas receives pointerout event
  8865. */
  8866. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  8867. /**
  8868. * Observable event triggered before each texture is initialized
  8869. */
  8870. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  8871. //WebVR
  8872. this._vrDisplay = undefined;
  8873. this._vrSupported = false;
  8874. this._vrExclusivePointerMode = false;
  8875. // Uniform buffers list
  8876. this.disableUniformBuffers = false;
  8877. this._uniformBuffers = new Array();
  8878. // Observables
  8879. /**
  8880. * Observable raised when the engine begins a new frame
  8881. */
  8882. this.onBeginFrameObservable = new BABYLON.Observable();
  8883. /**
  8884. * Observable raised when the engine ends the current frame
  8885. */
  8886. this.onEndFrameObservable = new BABYLON.Observable();
  8887. /**
  8888. * Observable raised when the engine is about to compile a shader
  8889. */
  8890. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  8891. /**
  8892. * Observable raised when the engine has jsut compiled a shader
  8893. */
  8894. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  8895. this._windowIsBackground = false;
  8896. this._webGLVersion = 1.0;
  8897. this._badOS = false;
  8898. this._badDesktopOS = false;
  8899. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  8900. this.onVRRequestPresentComplete = new BABYLON.Observable();
  8901. this.onVRRequestPresentStart = new BABYLON.Observable();
  8902. this._colorWrite = true;
  8903. this._drawCalls = new BABYLON.PerfCounter();
  8904. this._textureCollisions = new BABYLON.PerfCounter();
  8905. this._renderingQueueLaunched = false;
  8906. this._activeRenderLoops = new Array();
  8907. // Deterministic lockstepMaxSteps
  8908. this._deterministicLockstep = false;
  8909. this._lockstepMaxSteps = 4;
  8910. // Lost context
  8911. this.onContextLostObservable = new BABYLON.Observable();
  8912. this.onContextRestoredObservable = new BABYLON.Observable();
  8913. this._contextWasLost = false;
  8914. this._doNotHandleContextLost = false;
  8915. // FPS
  8916. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  8917. this._fps = 60;
  8918. this._deltaTime = 0;
  8919. /**
  8920. * Turn this value on if you want to pause FPS computation when in background
  8921. */
  8922. this.disablePerformanceMonitorInBackground = false;
  8923. // States
  8924. this._depthCullingState = new BABYLON._DepthCullingState();
  8925. this._stencilState = new BABYLON._StencilState();
  8926. this._alphaState = new BABYLON._AlphaState();
  8927. this._alphaMode = Engine.ALPHA_DISABLE;
  8928. // Cache
  8929. this._internalTexturesCache = new Array();
  8930. this._boundTexturesCache = {};
  8931. this._boundTexturesStack = new Array();
  8932. this._compiledEffects = {};
  8933. this._vertexAttribArraysEnabled = [];
  8934. this._uintIndicesCurrentlySet = false;
  8935. this._currentBoundBuffer = new Array();
  8936. this._currentBufferPointers = new Array();
  8937. this._currentInstanceLocations = new Array();
  8938. this._currentInstanceBuffers = new Array();
  8939. this._vaoRecordInProgress = false;
  8940. this._mustWipeVertexAttributes = false;
  8941. this._nextFreeTextureSlots = new Array();
  8942. this._activeRequests = new Array();
  8943. // Hardware supported Compressed Textures
  8944. this._texturesSupported = new Array();
  8945. this._onVRFullScreenTriggered = function () {
  8946. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  8947. //get the old size before we change
  8948. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  8949. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  8950. //get the width and height, change the render size
  8951. var leftEye = _this._vrDisplay.getEyeParameters('left');
  8952. _this.setHardwareScalingLevel(1);
  8953. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  8954. }
  8955. else {
  8956. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  8957. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  8958. }
  8959. };
  8960. this._boundUniforms = {};
  8961. var canvas = null;
  8962. Engine.Instances.push(this);
  8963. if (!canvasOrContext) {
  8964. return;
  8965. }
  8966. options = options || {};
  8967. if (canvasOrContext.getContext) {
  8968. canvas = canvasOrContext;
  8969. this._renderingCanvas = canvas;
  8970. if (antialias != null) {
  8971. options.antialias = antialias;
  8972. }
  8973. if (options.deterministicLockstep === undefined) {
  8974. options.deterministicLockstep = false;
  8975. }
  8976. if (options.lockstepMaxSteps === undefined) {
  8977. options.lockstepMaxSteps = 4;
  8978. }
  8979. if (options.preserveDrawingBuffer === undefined) {
  8980. options.preserveDrawingBuffer = false;
  8981. }
  8982. if (options.audioEngine === undefined) {
  8983. options.audioEngine = true;
  8984. }
  8985. if (options.stencil === undefined) {
  8986. options.stencil = true;
  8987. }
  8988. this._deterministicLockstep = options.deterministicLockstep;
  8989. this._lockstepMaxSteps = options.lockstepMaxSteps;
  8990. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  8991. // Exceptions
  8992. if (navigator && navigator.userAgent) {
  8993. var ua = navigator.userAgent;
  8994. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  8995. var exception = _a[_i];
  8996. var key = exception.key;
  8997. var targets = exception.targets;
  8998. if (ua.indexOf(key) > -1) {
  8999. if (exception.capture && exception.captureConstraint) {
  9000. var capture = exception.capture;
  9001. var constraint = exception.captureConstraint;
  9002. var regex = new RegExp(capture);
  9003. var matches = regex.exec(ua);
  9004. if (matches && matches.length > 0) {
  9005. var capturedValue = parseInt(matches[matches.length - 1]);
  9006. if (capturedValue >= constraint) {
  9007. continue;
  9008. }
  9009. }
  9010. }
  9011. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  9012. var target = targets_1[_b];
  9013. switch (target) {
  9014. case "uniformBuffer":
  9015. this.disableUniformBuffers = true;
  9016. break;
  9017. }
  9018. }
  9019. break;
  9020. }
  9021. }
  9022. }
  9023. // GL
  9024. if (!options.disableWebGL2Support) {
  9025. try {
  9026. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  9027. if (this._gl) {
  9028. this._webGLVersion = 2.0;
  9029. }
  9030. }
  9031. catch (e) {
  9032. // Do nothing
  9033. }
  9034. }
  9035. if (!this._gl) {
  9036. if (!canvas) {
  9037. throw new Error("The provided canvas is null or undefined.");
  9038. }
  9039. try {
  9040. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  9041. }
  9042. catch (e) {
  9043. throw new Error("WebGL not supported");
  9044. }
  9045. }
  9046. if (!this._gl) {
  9047. throw new Error("WebGL not supported");
  9048. }
  9049. this._onCanvasFocus = function () {
  9050. _this.onCanvasFocusObservable.notifyObservers(_this);
  9051. };
  9052. this._onCanvasBlur = function () {
  9053. _this.onCanvasBlurObservable.notifyObservers(_this);
  9054. };
  9055. canvas.addEventListener("focus", this._onCanvasFocus);
  9056. canvas.addEventListener("blur", this._onCanvasBlur);
  9057. this._onBlur = function () {
  9058. if (_this.disablePerformanceMonitorInBackground) {
  9059. _this._performanceMonitor.disable();
  9060. }
  9061. _this._windowIsBackground = true;
  9062. };
  9063. this._onFocus = function () {
  9064. if (_this.disablePerformanceMonitorInBackground) {
  9065. _this._performanceMonitor.enable();
  9066. }
  9067. _this._windowIsBackground = false;
  9068. };
  9069. this._onCanvasPointerOut = function () {
  9070. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  9071. };
  9072. window.addEventListener("blur", this._onBlur);
  9073. window.addEventListener("focus", this._onFocus);
  9074. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  9075. // Context lost
  9076. if (!this._doNotHandleContextLost) {
  9077. this._onContextLost = function (evt) {
  9078. evt.preventDefault();
  9079. _this._contextWasLost = true;
  9080. BABYLON.Tools.Warn("WebGL context lost.");
  9081. _this.onContextLostObservable.notifyObservers(_this);
  9082. };
  9083. this._onContextRestored = function (evt) {
  9084. // Adding a timeout to avoid race condition at browser level
  9085. setTimeout(function () {
  9086. // Rebuild gl context
  9087. _this._initGLContext();
  9088. // Rebuild effects
  9089. _this._rebuildEffects();
  9090. // Rebuild textures
  9091. _this._rebuildInternalTextures();
  9092. // Rebuild buffers
  9093. _this._rebuildBuffers();
  9094. // Cache
  9095. _this.wipeCaches(true);
  9096. BABYLON.Tools.Warn("WebGL context successfully restored.");
  9097. _this.onContextRestoredObservable.notifyObservers(_this);
  9098. _this._contextWasLost = false;
  9099. }, 0);
  9100. };
  9101. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  9102. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  9103. }
  9104. }
  9105. else {
  9106. this._gl = canvasOrContext;
  9107. this._renderingCanvas = this._gl.canvas;
  9108. if (this._gl.renderbufferStorageMultisample) {
  9109. this._webGLVersion = 2.0;
  9110. }
  9111. options.stencil = this._gl.getContextAttributes().stencil;
  9112. }
  9113. // Viewport
  9114. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  9115. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  9116. this.resize();
  9117. this._isStencilEnable = options.stencil ? true : false;
  9118. this._initGLContext();
  9119. if (canvas) {
  9120. // Fullscreen
  9121. this._onFullscreenChange = function () {
  9122. if (document.fullscreen !== undefined) {
  9123. _this.isFullscreen = document.fullscreen;
  9124. }
  9125. else if (document.mozFullScreen !== undefined) {
  9126. _this.isFullscreen = document.mozFullScreen;
  9127. }
  9128. else if (document.webkitIsFullScreen !== undefined) {
  9129. _this.isFullscreen = document.webkitIsFullScreen;
  9130. }
  9131. else if (document.msIsFullScreen !== undefined) {
  9132. _this.isFullscreen = document.msIsFullScreen;
  9133. }
  9134. // Pointer lock
  9135. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  9136. canvas.requestPointerLock = canvas.requestPointerLock ||
  9137. canvas.msRequestPointerLock ||
  9138. canvas.mozRequestPointerLock ||
  9139. canvas.webkitRequestPointerLock;
  9140. if (canvas.requestPointerLock) {
  9141. canvas.requestPointerLock();
  9142. }
  9143. }
  9144. };
  9145. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  9146. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  9147. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  9148. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  9149. // Pointer lock
  9150. this._onPointerLockChange = function () {
  9151. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  9152. document.webkitPointerLockElement === canvas ||
  9153. document.msPointerLockElement === canvas ||
  9154. document.pointerLockElement === canvas);
  9155. };
  9156. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  9157. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  9158. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  9159. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  9160. this._onVRDisplayPointerRestricted = function () {
  9161. if (canvas) {
  9162. canvas.requestPointerLock();
  9163. }
  9164. };
  9165. this._onVRDisplayPointerUnrestricted = function () {
  9166. document.exitPointerLock();
  9167. };
  9168. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  9169. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  9170. }
  9171. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  9172. Engine.audioEngine = new BABYLON.AudioEngine();
  9173. }
  9174. // Prepare buffer pointers
  9175. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9176. this._currentBufferPointers[i] = new BufferPointer();
  9177. }
  9178. // Load WebVR Devices
  9179. if (options.autoEnableWebVR) {
  9180. this.initWebVR();
  9181. }
  9182. // Detect if we are running on a faulty buggy OS.
  9183. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  9184. // Detect if we are running on a faulty buggy desktop OS.
  9185. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  9186. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  9187. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  9188. }
  9189. Object.defineProperty(Engine, "LastCreatedEngine", {
  9190. get: function () {
  9191. if (Engine.Instances.length === 0) {
  9192. return null;
  9193. }
  9194. return Engine.Instances[Engine.Instances.length - 1];
  9195. },
  9196. enumerable: true,
  9197. configurable: true
  9198. });
  9199. Object.defineProperty(Engine, "LastCreatedScene", {
  9200. get: function () {
  9201. var lastCreatedEngine = Engine.LastCreatedEngine;
  9202. if (!lastCreatedEngine) {
  9203. return null;
  9204. }
  9205. if (lastCreatedEngine.scenes.length === 0) {
  9206. return null;
  9207. }
  9208. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  9209. },
  9210. enumerable: true,
  9211. configurable: true
  9212. });
  9213. /**
  9214. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  9215. */
  9216. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  9217. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  9218. var engine = Engine.Instances[engineIndex];
  9219. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  9220. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  9221. }
  9222. }
  9223. };
  9224. Object.defineProperty(Engine, "NEVER", {
  9225. get: function () {
  9226. return Engine._NEVER;
  9227. },
  9228. enumerable: true,
  9229. configurable: true
  9230. });
  9231. Object.defineProperty(Engine, "ALWAYS", {
  9232. get: function () {
  9233. return Engine._ALWAYS;
  9234. },
  9235. enumerable: true,
  9236. configurable: true
  9237. });
  9238. Object.defineProperty(Engine, "LESS", {
  9239. get: function () {
  9240. return Engine._LESS;
  9241. },
  9242. enumerable: true,
  9243. configurable: true
  9244. });
  9245. Object.defineProperty(Engine, "EQUAL", {
  9246. get: function () {
  9247. return Engine._EQUAL;
  9248. },
  9249. enumerable: true,
  9250. configurable: true
  9251. });
  9252. Object.defineProperty(Engine, "LEQUAL", {
  9253. get: function () {
  9254. return Engine._LEQUAL;
  9255. },
  9256. enumerable: true,
  9257. configurable: true
  9258. });
  9259. Object.defineProperty(Engine, "GREATER", {
  9260. get: function () {
  9261. return Engine._GREATER;
  9262. },
  9263. enumerable: true,
  9264. configurable: true
  9265. });
  9266. Object.defineProperty(Engine, "GEQUAL", {
  9267. get: function () {
  9268. return Engine._GEQUAL;
  9269. },
  9270. enumerable: true,
  9271. configurable: true
  9272. });
  9273. Object.defineProperty(Engine, "NOTEQUAL", {
  9274. get: function () {
  9275. return Engine._NOTEQUAL;
  9276. },
  9277. enumerable: true,
  9278. configurable: true
  9279. });
  9280. Object.defineProperty(Engine, "KEEP", {
  9281. get: function () {
  9282. return Engine._KEEP;
  9283. },
  9284. enumerable: true,
  9285. configurable: true
  9286. });
  9287. Object.defineProperty(Engine, "REPLACE", {
  9288. get: function () {
  9289. return Engine._REPLACE;
  9290. },
  9291. enumerable: true,
  9292. configurable: true
  9293. });
  9294. Object.defineProperty(Engine, "INCR", {
  9295. get: function () {
  9296. return Engine._INCR;
  9297. },
  9298. enumerable: true,
  9299. configurable: true
  9300. });
  9301. Object.defineProperty(Engine, "DECR", {
  9302. get: function () {
  9303. return Engine._DECR;
  9304. },
  9305. enumerable: true,
  9306. configurable: true
  9307. });
  9308. Object.defineProperty(Engine, "INVERT", {
  9309. get: function () {
  9310. return Engine._INVERT;
  9311. },
  9312. enumerable: true,
  9313. configurable: true
  9314. });
  9315. Object.defineProperty(Engine, "INCR_WRAP", {
  9316. get: function () {
  9317. return Engine._INCR_WRAP;
  9318. },
  9319. enumerable: true,
  9320. configurable: true
  9321. });
  9322. Object.defineProperty(Engine, "DECR_WRAP", {
  9323. get: function () {
  9324. return Engine._DECR_WRAP;
  9325. },
  9326. enumerable: true,
  9327. configurable: true
  9328. });
  9329. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  9330. get: function () {
  9331. return Engine._ALPHA_DISABLE;
  9332. },
  9333. enumerable: true,
  9334. configurable: true
  9335. });
  9336. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  9337. get: function () {
  9338. return Engine._ALPHA_ONEONE;
  9339. },
  9340. enumerable: true,
  9341. configurable: true
  9342. });
  9343. Object.defineProperty(Engine, "ALPHA_ADD", {
  9344. get: function () {
  9345. return Engine._ALPHA_ADD;
  9346. },
  9347. enumerable: true,
  9348. configurable: true
  9349. });
  9350. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  9351. get: function () {
  9352. return Engine._ALPHA_COMBINE;
  9353. },
  9354. enumerable: true,
  9355. configurable: true
  9356. });
  9357. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  9358. get: function () {
  9359. return Engine._ALPHA_SUBTRACT;
  9360. },
  9361. enumerable: true,
  9362. configurable: true
  9363. });
  9364. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  9365. get: function () {
  9366. return Engine._ALPHA_MULTIPLY;
  9367. },
  9368. enumerable: true,
  9369. configurable: true
  9370. });
  9371. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  9372. get: function () {
  9373. return Engine._ALPHA_MAXIMIZED;
  9374. },
  9375. enumerable: true,
  9376. configurable: true
  9377. });
  9378. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  9379. get: function () {
  9380. return Engine._ALPHA_PREMULTIPLIED;
  9381. },
  9382. enumerable: true,
  9383. configurable: true
  9384. });
  9385. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  9386. get: function () {
  9387. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  9388. },
  9389. enumerable: true,
  9390. configurable: true
  9391. });
  9392. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  9393. get: function () {
  9394. return Engine._ALPHA_INTERPOLATE;
  9395. },
  9396. enumerable: true,
  9397. configurable: true
  9398. });
  9399. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  9400. get: function () {
  9401. return Engine._ALPHA_SCREENMODE;
  9402. },
  9403. enumerable: true,
  9404. configurable: true
  9405. });
  9406. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  9407. get: function () {
  9408. return Engine._DELAYLOADSTATE_NONE;
  9409. },
  9410. enumerable: true,
  9411. configurable: true
  9412. });
  9413. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  9414. get: function () {
  9415. return Engine._DELAYLOADSTATE_LOADED;
  9416. },
  9417. enumerable: true,
  9418. configurable: true
  9419. });
  9420. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  9421. get: function () {
  9422. return Engine._DELAYLOADSTATE_LOADING;
  9423. },
  9424. enumerable: true,
  9425. configurable: true
  9426. });
  9427. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  9428. get: function () {
  9429. return Engine._DELAYLOADSTATE_NOTLOADED;
  9430. },
  9431. enumerable: true,
  9432. configurable: true
  9433. });
  9434. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  9435. get: function () {
  9436. return Engine._TEXTUREFORMAT_ALPHA;
  9437. },
  9438. enumerable: true,
  9439. configurable: true
  9440. });
  9441. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  9442. get: function () {
  9443. return Engine._TEXTUREFORMAT_LUMINANCE;
  9444. },
  9445. enumerable: true,
  9446. configurable: true
  9447. });
  9448. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  9449. get: function () {
  9450. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  9451. },
  9452. enumerable: true,
  9453. configurable: true
  9454. });
  9455. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  9456. get: function () {
  9457. return Engine._TEXTUREFORMAT_RGB;
  9458. },
  9459. enumerable: true,
  9460. configurable: true
  9461. });
  9462. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  9463. get: function () {
  9464. return Engine._TEXTUREFORMAT_RGBA;
  9465. },
  9466. enumerable: true,
  9467. configurable: true
  9468. });
  9469. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  9470. get: function () {
  9471. return Engine._TEXTURETYPE_UNSIGNED_INT;
  9472. },
  9473. enumerable: true,
  9474. configurable: true
  9475. });
  9476. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  9477. get: function () {
  9478. return Engine._TEXTURETYPE_FLOAT;
  9479. },
  9480. enumerable: true,
  9481. configurable: true
  9482. });
  9483. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  9484. get: function () {
  9485. return Engine._TEXTURETYPE_HALF_FLOAT;
  9486. },
  9487. enumerable: true,
  9488. configurable: true
  9489. });
  9490. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  9491. get: function () {
  9492. return Engine._SCALEMODE_FLOOR;
  9493. },
  9494. enumerable: true,
  9495. configurable: true
  9496. });
  9497. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  9498. get: function () {
  9499. return Engine._SCALEMODE_NEAREST;
  9500. },
  9501. enumerable: true,
  9502. configurable: true
  9503. });
  9504. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  9505. get: function () {
  9506. return Engine._SCALEMODE_CEILING;
  9507. },
  9508. enumerable: true,
  9509. configurable: true
  9510. });
  9511. Object.defineProperty(Engine, "Version", {
  9512. get: function () {
  9513. return "3.2.0-alpha2";
  9514. },
  9515. enumerable: true,
  9516. configurable: true
  9517. });
  9518. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  9519. get: function () {
  9520. return this._vrExclusivePointerMode;
  9521. },
  9522. enumerable: true,
  9523. configurable: true
  9524. });
  9525. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  9526. get: function () {
  9527. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  9528. },
  9529. enumerable: true,
  9530. configurable: true
  9531. });
  9532. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  9533. get: function () {
  9534. return this._webGLVersion < 2 || this.forcePOTTextures;
  9535. },
  9536. enumerable: true,
  9537. configurable: true
  9538. });
  9539. Object.defineProperty(Engine.prototype, "badOS", {
  9540. get: function () {
  9541. return this._badOS;
  9542. },
  9543. enumerable: true,
  9544. configurable: true
  9545. });
  9546. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  9547. get: function () {
  9548. return this._badDesktopOS;
  9549. },
  9550. enumerable: true,
  9551. configurable: true
  9552. });
  9553. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  9554. get: function () {
  9555. return this._performanceMonitor;
  9556. },
  9557. enumerable: true,
  9558. configurable: true
  9559. });
  9560. Object.defineProperty(Engine.prototype, "texturesSupported", {
  9561. get: function () {
  9562. return this._texturesSupported;
  9563. },
  9564. enumerable: true,
  9565. configurable: true
  9566. });
  9567. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  9568. get: function () {
  9569. return this._textureFormatInUse;
  9570. },
  9571. enumerable: true,
  9572. configurable: true
  9573. });
  9574. Object.defineProperty(Engine.prototype, "currentViewport", {
  9575. get: function () {
  9576. return this._cachedViewport;
  9577. },
  9578. enumerable: true,
  9579. configurable: true
  9580. });
  9581. Object.defineProperty(Engine.prototype, "emptyTexture", {
  9582. // Empty texture
  9583. get: function () {
  9584. if (!this._emptyTexture) {
  9585. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9586. }
  9587. return this._emptyTexture;
  9588. },
  9589. enumerable: true,
  9590. configurable: true
  9591. });
  9592. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  9593. get: function () {
  9594. if (!this._emptyTexture3D) {
  9595. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9596. }
  9597. return this._emptyTexture3D;
  9598. },
  9599. enumerable: true,
  9600. configurable: true
  9601. });
  9602. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  9603. get: function () {
  9604. if (!this._emptyCubeTexture) {
  9605. var faceData = new Uint8Array(4);
  9606. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  9607. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9608. }
  9609. return this._emptyCubeTexture;
  9610. },
  9611. enumerable: true,
  9612. configurable: true
  9613. });
  9614. Engine.prototype._rebuildInternalTextures = function () {
  9615. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  9616. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  9617. var internalTexture = currentState_1[_i];
  9618. internalTexture._rebuild();
  9619. }
  9620. };
  9621. Engine.prototype._rebuildEffects = function () {
  9622. for (var key in this._compiledEffects) {
  9623. var effect = this._compiledEffects[key];
  9624. effect._prepareEffect();
  9625. }
  9626. BABYLON.Effect.ResetCache();
  9627. };
  9628. Engine.prototype._rebuildBuffers = function () {
  9629. // Index / Vertex
  9630. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  9631. var scene = _a[_i];
  9632. scene.resetCachedMaterial();
  9633. scene._rebuildGeometries();
  9634. scene._rebuildTextures();
  9635. }
  9636. // Uniforms
  9637. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  9638. var uniformBuffer = _c[_b];
  9639. uniformBuffer._rebuild();
  9640. }
  9641. };
  9642. Engine.prototype._initGLContext = function () {
  9643. // Caps
  9644. this._caps = new EngineCapabilities();
  9645. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  9646. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  9647. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9648. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  9649. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9650. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  9651. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  9652. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  9653. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9654. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  9655. // Infos
  9656. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  9657. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  9658. if (rendererInfo != null) {
  9659. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  9660. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  9661. }
  9662. if (!this._glVendor) {
  9663. this._glVendor = "Unknown vendor";
  9664. }
  9665. if (!this._glRenderer) {
  9666. this._glRenderer = "Unknown renderer";
  9667. }
  9668. // Constants
  9669. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  9670. if (this._gl.RGBA16F !== 0x881A) {
  9671. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  9672. }
  9673. if (this._gl.RGBA32F !== 0x8814) {
  9674. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  9675. }
  9676. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  9677. this._gl.DEPTH24_STENCIL8 = 35056;
  9678. }
  9679. // Extensions
  9680. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  9681. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  9682. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  9683. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  9684. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  9685. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  9686. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  9687. 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');
  9688. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  9689. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  9690. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  9691. this._caps.highPrecisionShaderSupported = true;
  9692. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  9693. if (this._caps.timerQuery) {
  9694. if (this._webGLVersion === 1) {
  9695. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  9696. }
  9697. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  9698. }
  9699. // Checks if some of the format renders first to allow the use of webgl inspector.
  9700. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  9701. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  9702. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  9703. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  9704. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  9705. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  9706. if (this._webGLVersion > 1) {
  9707. this._gl.HALF_FLOAT_OES = 0x140B;
  9708. }
  9709. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  9710. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  9711. // Draw buffers
  9712. if (this._webGLVersion > 1) {
  9713. this._caps.drawBuffersExtension = true;
  9714. }
  9715. else {
  9716. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  9717. if (drawBuffersExtension !== null) {
  9718. this._caps.drawBuffersExtension = true;
  9719. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  9720. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  9721. for (var i = 0; i < 16; i++) {
  9722. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  9723. }
  9724. }
  9725. else {
  9726. this._caps.drawBuffersExtension = false;
  9727. }
  9728. }
  9729. // Depth Texture
  9730. if (this._webGLVersion > 1) {
  9731. this._caps.depthTextureExtension = true;
  9732. }
  9733. else {
  9734. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  9735. if (depthTextureExtension != null) {
  9736. this._caps.depthTextureExtension = true;
  9737. }
  9738. }
  9739. // Vertex array object
  9740. if (this._webGLVersion > 1) {
  9741. this._caps.vertexArrayObject = true;
  9742. }
  9743. else {
  9744. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  9745. if (vertexArrayObjectExtension != null) {
  9746. this._caps.vertexArrayObject = true;
  9747. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  9748. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  9749. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  9750. }
  9751. else {
  9752. this._caps.vertexArrayObject = false;
  9753. }
  9754. }
  9755. // Instances count
  9756. if (this._webGLVersion > 1) {
  9757. this._caps.instancedArrays = true;
  9758. }
  9759. else {
  9760. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  9761. if (instanceExtension != null) {
  9762. this._caps.instancedArrays = true;
  9763. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  9764. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  9765. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  9766. }
  9767. else {
  9768. this._caps.instancedArrays = false;
  9769. }
  9770. }
  9771. // Intelligently add supported compressed formats in order to check for.
  9772. // Check for ASTC support first as it is most powerful and to be very cross platform.
  9773. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  9774. // Likely no hardware which supports both PVR & DXT, so order matters little.
  9775. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  9776. if (this._caps.astc)
  9777. this.texturesSupported.push('-astc.ktx');
  9778. if (this._caps.s3tc)
  9779. this.texturesSupported.push('-dxt.ktx');
  9780. if (this._caps.pvrtc)
  9781. this.texturesSupported.push('-pvrtc.ktx');
  9782. if (this._caps.etc2)
  9783. this.texturesSupported.push('-etc2.ktx');
  9784. if (this._caps.etc1)
  9785. this.texturesSupported.push('-etc1.ktx');
  9786. if (this._gl.getShaderPrecisionFormat) {
  9787. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  9788. if (highp) {
  9789. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  9790. }
  9791. }
  9792. // Depth buffer
  9793. this.setDepthBuffer(true);
  9794. this.setDepthFunctionToLessOrEqual();
  9795. this.setDepthWrite(true);
  9796. // Texture maps
  9797. for (var slot = 0; slot < this._caps.maxCombinedTexturesImageUnits; slot++) {
  9798. this._nextFreeTextureSlots.push(slot);
  9799. }
  9800. };
  9801. Object.defineProperty(Engine.prototype, "webGLVersion", {
  9802. get: function () {
  9803. return this._webGLVersion;
  9804. },
  9805. enumerable: true,
  9806. configurable: true
  9807. });
  9808. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  9809. /**
  9810. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  9811. */
  9812. get: function () {
  9813. return this._isStencilEnable;
  9814. },
  9815. enumerable: true,
  9816. configurable: true
  9817. });
  9818. Engine.prototype._prepareWorkingCanvas = function () {
  9819. if (this._workingCanvas) {
  9820. return;
  9821. }
  9822. this._workingCanvas = document.createElement("canvas");
  9823. var context = this._workingCanvas.getContext("2d");
  9824. if (context) {
  9825. this._workingContext = context;
  9826. }
  9827. };
  9828. Engine.prototype.resetTextureCache = function () {
  9829. for (var key in this._boundTexturesCache) {
  9830. var boundTexture = this._boundTexturesCache[key];
  9831. if (boundTexture) {
  9832. this._removeDesignatedSlot(boundTexture);
  9833. }
  9834. this._boundTexturesCache[key] = null;
  9835. }
  9836. this._nextFreeTextureSlots = [];
  9837. for (var slot = 0; slot < this._caps.maxCombinedTexturesImageUnits; slot++) {
  9838. this._nextFreeTextureSlots.push(slot);
  9839. }
  9840. this._activeChannel = -1;
  9841. };
  9842. Engine.prototype.isDeterministicLockStep = function () {
  9843. return this._deterministicLockstep;
  9844. };
  9845. Engine.prototype.getLockstepMaxSteps = function () {
  9846. return this._lockstepMaxSteps;
  9847. };
  9848. Engine.prototype.getGlInfo = function () {
  9849. return {
  9850. vendor: this._glVendor,
  9851. renderer: this._glRenderer,
  9852. version: this._glVersion
  9853. };
  9854. };
  9855. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  9856. if (useScreen === void 0) { useScreen = false; }
  9857. var viewport = camera.viewport;
  9858. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  9859. };
  9860. Engine.prototype.getRenderWidth = function (useScreen) {
  9861. if (useScreen === void 0) { useScreen = false; }
  9862. if (!useScreen && this._currentRenderTarget) {
  9863. return this._currentRenderTarget.width;
  9864. }
  9865. return this._gl.drawingBufferWidth;
  9866. };
  9867. Engine.prototype.getRenderHeight = function (useScreen) {
  9868. if (useScreen === void 0) { useScreen = false; }
  9869. if (!useScreen && this._currentRenderTarget) {
  9870. return this._currentRenderTarget.height;
  9871. }
  9872. return this._gl.drawingBufferHeight;
  9873. };
  9874. Engine.prototype.getRenderingCanvas = function () {
  9875. return this._renderingCanvas;
  9876. };
  9877. Engine.prototype.getRenderingCanvasClientRect = function () {
  9878. if (!this._renderingCanvas) {
  9879. return null;
  9880. }
  9881. return this._renderingCanvas.getBoundingClientRect();
  9882. };
  9883. Engine.prototype.setHardwareScalingLevel = function (level) {
  9884. this._hardwareScalingLevel = level;
  9885. this.resize();
  9886. };
  9887. Engine.prototype.getHardwareScalingLevel = function () {
  9888. return this._hardwareScalingLevel;
  9889. };
  9890. Engine.prototype.getLoadedTexturesCache = function () {
  9891. return this._internalTexturesCache;
  9892. };
  9893. Engine.prototype.getCaps = function () {
  9894. return this._caps;
  9895. };
  9896. Object.defineProperty(Engine.prototype, "drawCalls", {
  9897. /** The number of draw calls submitted last frame */
  9898. get: function () {
  9899. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  9900. return 0;
  9901. },
  9902. enumerable: true,
  9903. configurable: true
  9904. });
  9905. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  9906. get: function () {
  9907. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  9908. return null;
  9909. },
  9910. enumerable: true,
  9911. configurable: true
  9912. });
  9913. Engine.prototype.getDepthFunction = function () {
  9914. return this._depthCullingState.depthFunc;
  9915. };
  9916. Engine.prototype.setDepthFunction = function (depthFunc) {
  9917. this._depthCullingState.depthFunc = depthFunc;
  9918. };
  9919. Engine.prototype.setDepthFunctionToGreater = function () {
  9920. this._depthCullingState.depthFunc = this._gl.GREATER;
  9921. };
  9922. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  9923. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  9924. };
  9925. Engine.prototype.setDepthFunctionToLess = function () {
  9926. this._depthCullingState.depthFunc = this._gl.LESS;
  9927. };
  9928. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  9929. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  9930. };
  9931. Engine.prototype.getStencilBuffer = function () {
  9932. return this._stencilState.stencilTest;
  9933. };
  9934. Engine.prototype.setStencilBuffer = function (enable) {
  9935. this._stencilState.stencilTest = enable;
  9936. };
  9937. Engine.prototype.getStencilMask = function () {
  9938. return this._stencilState.stencilMask;
  9939. };
  9940. Engine.prototype.setStencilMask = function (mask) {
  9941. this._stencilState.stencilMask = mask;
  9942. };
  9943. Engine.prototype.getStencilFunction = function () {
  9944. return this._stencilState.stencilFunc;
  9945. };
  9946. Engine.prototype.getStencilFunctionReference = function () {
  9947. return this._stencilState.stencilFuncRef;
  9948. };
  9949. Engine.prototype.getStencilFunctionMask = function () {
  9950. return this._stencilState.stencilFuncMask;
  9951. };
  9952. Engine.prototype.setStencilFunction = function (stencilFunc) {
  9953. this._stencilState.stencilFunc = stencilFunc;
  9954. };
  9955. Engine.prototype.setStencilFunctionReference = function (reference) {
  9956. this._stencilState.stencilFuncRef = reference;
  9957. };
  9958. Engine.prototype.setStencilFunctionMask = function (mask) {
  9959. this._stencilState.stencilFuncMask = mask;
  9960. };
  9961. Engine.prototype.getStencilOperationFail = function () {
  9962. return this._stencilState.stencilOpStencilFail;
  9963. };
  9964. Engine.prototype.getStencilOperationDepthFail = function () {
  9965. return this._stencilState.stencilOpDepthFail;
  9966. };
  9967. Engine.prototype.getStencilOperationPass = function () {
  9968. return this._stencilState.stencilOpStencilDepthPass;
  9969. };
  9970. Engine.prototype.setStencilOperationFail = function (operation) {
  9971. this._stencilState.stencilOpStencilFail = operation;
  9972. };
  9973. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  9974. this._stencilState.stencilOpDepthFail = operation;
  9975. };
  9976. Engine.prototype.setStencilOperationPass = function (operation) {
  9977. this._stencilState.stencilOpStencilDepthPass = operation;
  9978. };
  9979. Engine.prototype.setDitheringState = function (value) {
  9980. if (value) {
  9981. this._gl.enable(this._gl.DITHER);
  9982. }
  9983. else {
  9984. this._gl.disable(this._gl.DITHER);
  9985. }
  9986. };
  9987. Engine.prototype.setRasterizerState = function (value) {
  9988. if (value) {
  9989. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  9990. }
  9991. else {
  9992. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  9993. }
  9994. };
  9995. /**
  9996. * stop executing a render loop function and remove it from the execution array
  9997. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  9998. */
  9999. Engine.prototype.stopRenderLoop = function (renderFunction) {
  10000. if (!renderFunction) {
  10001. this._activeRenderLoops = [];
  10002. return;
  10003. }
  10004. var index = this._activeRenderLoops.indexOf(renderFunction);
  10005. if (index >= 0) {
  10006. this._activeRenderLoops.splice(index, 1);
  10007. }
  10008. };
  10009. Engine.prototype._renderLoop = function () {
  10010. if (!this._contextWasLost) {
  10011. var shouldRender = true;
  10012. if (!this.renderEvenInBackground && this._windowIsBackground) {
  10013. shouldRender = false;
  10014. }
  10015. if (shouldRender) {
  10016. // Start new frame
  10017. this.beginFrame();
  10018. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  10019. var renderFunction = this._activeRenderLoops[index];
  10020. renderFunction();
  10021. }
  10022. // Present
  10023. this.endFrame();
  10024. }
  10025. }
  10026. if (this._activeRenderLoops.length > 0) {
  10027. // Register new frame
  10028. var requester = null;
  10029. if (this._vrDisplay && this._vrDisplay.isPresenting)
  10030. requester = this._vrDisplay;
  10031. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  10032. }
  10033. else {
  10034. this._renderingQueueLaunched = false;
  10035. }
  10036. };
  10037. /**
  10038. * Register and execute a render loop. The engine can have more than one render function.
  10039. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  10040. * @example
  10041. * engine.runRenderLoop(function () {
  10042. * scene.render()
  10043. * })
  10044. */
  10045. Engine.prototype.runRenderLoop = function (renderFunction) {
  10046. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  10047. return;
  10048. }
  10049. this._activeRenderLoops.push(renderFunction);
  10050. if (!this._renderingQueueLaunched) {
  10051. this._renderingQueueLaunched = true;
  10052. this._bindedRenderFunction = this._renderLoop.bind(this);
  10053. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  10054. }
  10055. };
  10056. /**
  10057. * Toggle full screen mode.
  10058. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  10059. * @param {any} options - an options object to be sent to the requestFullscreen function
  10060. */
  10061. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  10062. if (this.isFullscreen) {
  10063. BABYLON.Tools.ExitFullscreen();
  10064. }
  10065. else {
  10066. this._pointerLockRequested = requestPointerLock;
  10067. if (this._renderingCanvas) {
  10068. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  10069. }
  10070. }
  10071. };
  10072. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  10073. if (stencil === void 0) { stencil = false; }
  10074. this.applyStates();
  10075. var mode = 0;
  10076. if (backBuffer && color) {
  10077. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  10078. mode |= this._gl.COLOR_BUFFER_BIT;
  10079. }
  10080. if (depth) {
  10081. this._gl.clearDepth(1.0);
  10082. mode |= this._gl.DEPTH_BUFFER_BIT;
  10083. }
  10084. if (stencil) {
  10085. this._gl.clearStencil(0);
  10086. mode |= this._gl.STENCIL_BUFFER_BIT;
  10087. }
  10088. this._gl.clear(mode);
  10089. };
  10090. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  10091. var gl = this._gl;
  10092. // Save state
  10093. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  10094. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  10095. // Change state
  10096. gl.enable(gl.SCISSOR_TEST);
  10097. gl.scissor(x, y, width, height);
  10098. // Clear
  10099. this.clear(clearColor, true, true, true);
  10100. // Restore state
  10101. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  10102. if (curScissor === true) {
  10103. gl.enable(gl.SCISSOR_TEST);
  10104. }
  10105. else {
  10106. gl.disable(gl.SCISSOR_TEST);
  10107. }
  10108. };
  10109. /**
  10110. * Set the WebGL's viewport
  10111. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  10112. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  10113. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  10114. */
  10115. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  10116. var width = requiredWidth || this.getRenderWidth();
  10117. var height = requiredHeight || this.getRenderHeight();
  10118. var x = viewport.x || 0;
  10119. var y = viewport.y || 0;
  10120. this._cachedViewport = viewport;
  10121. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  10122. };
  10123. /**
  10124. * Directly set the WebGL Viewport
  10125. * The x, y, width & height are directly passed to the WebGL call
  10126. * @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.
  10127. */
  10128. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  10129. var currentViewport = this._cachedViewport;
  10130. this._cachedViewport = null;
  10131. this._gl.viewport(x, y, width, height);
  10132. return currentViewport;
  10133. };
  10134. Engine.prototype.beginFrame = function () {
  10135. this.onBeginFrameObservable.notifyObservers(this);
  10136. this._measureFps();
  10137. };
  10138. Engine.prototype.endFrame = function () {
  10139. //force a flush in case we are using a bad OS.
  10140. if (this._badOS) {
  10141. this.flushFramebuffer();
  10142. }
  10143. //submit frame to the vr device, if enabled
  10144. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10145. // TODO: We should only submit the frame if we read frameData successfully.
  10146. this._vrDisplay.submitFrame();
  10147. }
  10148. this.onEndFrameObservable.notifyObservers(this);
  10149. };
  10150. /**
  10151. * resize the view according to the canvas' size.
  10152. * @example
  10153. * window.addEventListener("resize", function () {
  10154. * engine.resize();
  10155. * });
  10156. */
  10157. Engine.prototype.resize = function () {
  10158. // We're not resizing the size of the canvas while in VR mode & presenting
  10159. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  10160. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  10161. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  10162. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  10163. }
  10164. };
  10165. /**
  10166. * force a specific size of the canvas
  10167. * @param {number} width - the new canvas' width
  10168. * @param {number} height - the new canvas' height
  10169. */
  10170. Engine.prototype.setSize = function (width, height) {
  10171. if (!this._renderingCanvas) {
  10172. return;
  10173. }
  10174. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  10175. return;
  10176. }
  10177. this._renderingCanvas.width = width;
  10178. this._renderingCanvas.height = height;
  10179. for (var index = 0; index < this.scenes.length; index++) {
  10180. var scene = this.scenes[index];
  10181. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  10182. var cam = scene.cameras[camIndex];
  10183. cam._currentRenderId = 0;
  10184. }
  10185. }
  10186. if (this.onResizeObservable.hasObservers) {
  10187. this.onResizeObservable.notifyObservers(this);
  10188. }
  10189. };
  10190. // WebVR functions
  10191. Engine.prototype.isVRDevicePresent = function () {
  10192. return !!this._vrDisplay;
  10193. };
  10194. Engine.prototype.getVRDevice = function () {
  10195. return this._vrDisplay;
  10196. };
  10197. Engine.prototype.initWebVR = function () {
  10198. var _this = this;
  10199. var notifyObservers = function () {
  10200. var eventArgs = {
  10201. vrDisplay: _this._vrDisplay,
  10202. vrSupported: _this._vrSupported
  10203. };
  10204. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  10205. };
  10206. if (!this._onVrDisplayConnect) {
  10207. this._onVrDisplayConnect = function (event) {
  10208. _this._vrDisplay = event.display;
  10209. notifyObservers();
  10210. };
  10211. this._onVrDisplayDisconnect = function () {
  10212. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  10213. _this._vrDisplay = undefined;
  10214. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  10215. notifyObservers();
  10216. };
  10217. this._onVrDisplayPresentChange = function () {
  10218. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  10219. };
  10220. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  10221. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  10222. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  10223. }
  10224. this._getVRDisplays(notifyObservers);
  10225. return this.onVRDisplayChangedObservable;
  10226. };
  10227. Engine.prototype.enableVR = function () {
  10228. var _this = this;
  10229. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  10230. var onResolved = function () {
  10231. _this.onVRRequestPresentComplete.notifyObservers(true);
  10232. _this._onVRFullScreenTriggered();
  10233. };
  10234. var onRejected = function () {
  10235. _this.onVRRequestPresentComplete.notifyObservers(false);
  10236. };
  10237. this.onVRRequestPresentStart.notifyObservers(this);
  10238. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  10239. }
  10240. };
  10241. Engine.prototype.disableVR = function () {
  10242. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10243. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  10244. }
  10245. };
  10246. Engine.prototype._getVRDisplays = function (callback) {
  10247. var _this = this;
  10248. var getWebVRDevices = function (devices) {
  10249. _this._vrSupported = true;
  10250. // note that devices may actually be an empty array. This is fine;
  10251. // we expect this._vrDisplay to be undefined in this case.
  10252. return _this._vrDisplay = devices[0];
  10253. };
  10254. if (navigator.getVRDisplays) {
  10255. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  10256. // TODO: System CANNOT support WebVR, despite API presence.
  10257. _this._vrSupported = false;
  10258. callback();
  10259. });
  10260. }
  10261. else {
  10262. // TODO: Browser does not support WebVR
  10263. this._vrDisplay = undefined;
  10264. this._vrSupported = false;
  10265. callback();
  10266. }
  10267. };
  10268. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  10269. if (this._currentRenderTarget) {
  10270. this.unBindFramebuffer(this._currentRenderTarget);
  10271. }
  10272. this._currentRenderTarget = texture;
  10273. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  10274. var gl = this._gl;
  10275. if (texture.isCube) {
  10276. if (faceIndex === undefined) {
  10277. faceIndex = 0;
  10278. }
  10279. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  10280. }
  10281. if (this._cachedViewport && !forceFullscreenViewport) {
  10282. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  10283. }
  10284. else {
  10285. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  10286. }
  10287. this.wipeCaches();
  10288. };
  10289. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  10290. if (this._currentFramebuffer !== framebuffer) {
  10291. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  10292. this._currentFramebuffer = framebuffer;
  10293. }
  10294. };
  10295. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  10296. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10297. this._currentRenderTarget = null;
  10298. // If MSAA, we need to bitblt back to main texture
  10299. var gl = this._gl;
  10300. if (texture._MSAAFramebuffer) {
  10301. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  10302. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  10303. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10304. }
  10305. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10306. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  10307. gl.generateMipmap(gl.TEXTURE_2D);
  10308. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10309. }
  10310. if (onBeforeUnbind) {
  10311. if (texture._MSAAFramebuffer) {
  10312. // Bind the correct framebuffer
  10313. this.bindUnboundFramebuffer(texture._framebuffer);
  10314. }
  10315. onBeforeUnbind();
  10316. }
  10317. this.bindUnboundFramebuffer(null);
  10318. };
  10319. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  10320. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10321. this._currentRenderTarget = null;
  10322. // If MSAA, we need to bitblt back to main texture
  10323. var gl = this._gl;
  10324. if (textures[0]._MSAAFramebuffer) {
  10325. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  10326. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  10327. var attachments = textures[0]._attachments;
  10328. if (!attachments) {
  10329. attachments = new Array(textures.length);
  10330. textures[0]._attachments = attachments;
  10331. }
  10332. for (var i = 0; i < textures.length; i++) {
  10333. var texture = textures[i];
  10334. for (var j = 0; j < attachments.length; j++) {
  10335. attachments[j] = gl.NONE;
  10336. }
  10337. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10338. gl.readBuffer(attachments[i]);
  10339. gl.drawBuffers(attachments);
  10340. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10341. }
  10342. for (var i = 0; i < attachments.length; i++) {
  10343. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10344. }
  10345. gl.drawBuffers(attachments);
  10346. }
  10347. for (var i = 0; i < textures.length; i++) {
  10348. var texture = textures[i];
  10349. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10350. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10351. gl.generateMipmap(gl.TEXTURE_2D);
  10352. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10353. }
  10354. }
  10355. if (onBeforeUnbind) {
  10356. if (textures[0]._MSAAFramebuffer) {
  10357. // Bind the correct framebuffer
  10358. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  10359. }
  10360. onBeforeUnbind();
  10361. }
  10362. this.bindUnboundFramebuffer(null);
  10363. };
  10364. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  10365. if (texture.generateMipMaps) {
  10366. var gl = this._gl;
  10367. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  10368. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10369. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10370. }
  10371. };
  10372. Engine.prototype.flushFramebuffer = function () {
  10373. this._gl.flush();
  10374. };
  10375. Engine.prototype.restoreDefaultFramebuffer = function () {
  10376. if (this._currentRenderTarget) {
  10377. this.unBindFramebuffer(this._currentRenderTarget);
  10378. }
  10379. else {
  10380. this.bindUnboundFramebuffer(null);
  10381. }
  10382. if (this._cachedViewport) {
  10383. this.setViewport(this._cachedViewport);
  10384. }
  10385. this.wipeCaches();
  10386. };
  10387. // UBOs
  10388. Engine.prototype.createUniformBuffer = function (elements) {
  10389. var ubo = this._gl.createBuffer();
  10390. if (!ubo) {
  10391. throw new Error("Unable to create uniform buffer");
  10392. }
  10393. this.bindUniformBuffer(ubo);
  10394. if (elements instanceof Float32Array) {
  10395. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  10396. }
  10397. else {
  10398. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  10399. }
  10400. this.bindUniformBuffer(null);
  10401. ubo.references = 1;
  10402. return ubo;
  10403. };
  10404. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  10405. var ubo = this._gl.createBuffer();
  10406. if (!ubo) {
  10407. throw new Error("Unable to create dynamic uniform buffer");
  10408. }
  10409. this.bindUniformBuffer(ubo);
  10410. if (elements instanceof Float32Array) {
  10411. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  10412. }
  10413. else {
  10414. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  10415. }
  10416. this.bindUniformBuffer(null);
  10417. ubo.references = 1;
  10418. return ubo;
  10419. };
  10420. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  10421. this.bindUniformBuffer(uniformBuffer);
  10422. if (offset === undefined) {
  10423. offset = 0;
  10424. }
  10425. if (count === undefined) {
  10426. if (elements instanceof Float32Array) {
  10427. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  10428. }
  10429. else {
  10430. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  10431. }
  10432. }
  10433. else {
  10434. if (elements instanceof Float32Array) {
  10435. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  10436. }
  10437. else {
  10438. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  10439. }
  10440. }
  10441. this.bindUniformBuffer(null);
  10442. };
  10443. // VBOs
  10444. Engine.prototype._resetVertexBufferBinding = function () {
  10445. this.bindArrayBuffer(null);
  10446. this._cachedVertexBuffers = null;
  10447. };
  10448. Engine.prototype.createVertexBuffer = function (vertices) {
  10449. var vbo = this._gl.createBuffer();
  10450. if (!vbo) {
  10451. throw new Error("Unable to create vertex buffer");
  10452. }
  10453. this.bindArrayBuffer(vbo);
  10454. if (vertices instanceof Float32Array) {
  10455. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  10456. }
  10457. else {
  10458. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  10459. }
  10460. this._resetVertexBufferBinding();
  10461. vbo.references = 1;
  10462. return vbo;
  10463. };
  10464. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  10465. var vbo = this._gl.createBuffer();
  10466. if (!vbo) {
  10467. throw new Error("Unable to create dynamic vertex buffer");
  10468. }
  10469. this.bindArrayBuffer(vbo);
  10470. if (vertices instanceof Float32Array) {
  10471. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  10472. }
  10473. else {
  10474. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  10475. }
  10476. this._resetVertexBufferBinding();
  10477. vbo.references = 1;
  10478. return vbo;
  10479. };
  10480. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  10481. if (offset === void 0) { offset = 0; }
  10482. // Force cache update
  10483. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  10484. this.bindIndexBuffer(indexBuffer);
  10485. var arrayBuffer;
  10486. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  10487. arrayBuffer = indices;
  10488. }
  10489. else {
  10490. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  10491. }
  10492. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  10493. this._resetIndexBufferBinding();
  10494. };
  10495. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  10496. this.bindArrayBuffer(vertexBuffer);
  10497. if (offset === undefined) {
  10498. offset = 0;
  10499. }
  10500. if (count === undefined) {
  10501. if (vertices instanceof Float32Array) {
  10502. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  10503. }
  10504. else {
  10505. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  10506. }
  10507. }
  10508. else {
  10509. if (vertices instanceof Float32Array) {
  10510. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  10511. }
  10512. else {
  10513. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  10514. }
  10515. }
  10516. this._resetVertexBufferBinding();
  10517. };
  10518. Engine.prototype._resetIndexBufferBinding = function () {
  10519. this.bindIndexBuffer(null);
  10520. this._cachedIndexBuffer = null;
  10521. };
  10522. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  10523. var vbo = this._gl.createBuffer();
  10524. if (!vbo) {
  10525. throw new Error("Unable to create index buffer");
  10526. }
  10527. this.bindIndexBuffer(vbo);
  10528. // Check for 32 bits indices
  10529. var arrayBuffer;
  10530. var need32Bits = false;
  10531. if (indices instanceof Uint16Array) {
  10532. arrayBuffer = indices;
  10533. }
  10534. else {
  10535. //check 32 bit support
  10536. if (this._caps.uintIndices) {
  10537. if (indices instanceof Uint32Array) {
  10538. arrayBuffer = indices;
  10539. need32Bits = true;
  10540. }
  10541. else {
  10542. //number[] or Int32Array, check if 32 bit is necessary
  10543. for (var index = 0; index < indices.length; index++) {
  10544. if (indices[index] > 65535) {
  10545. need32Bits = true;
  10546. break;
  10547. }
  10548. }
  10549. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  10550. }
  10551. }
  10552. else {
  10553. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  10554. arrayBuffer = new Uint16Array(indices);
  10555. }
  10556. }
  10557. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  10558. this._resetIndexBufferBinding();
  10559. vbo.references = 1;
  10560. vbo.is32Bits = need32Bits;
  10561. return vbo;
  10562. };
  10563. Engine.prototype.bindArrayBuffer = function (buffer) {
  10564. if (!this._vaoRecordInProgress) {
  10565. this._unbindVertexArrayObject();
  10566. }
  10567. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  10568. };
  10569. Engine.prototype.bindUniformBuffer = function (buffer) {
  10570. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  10571. };
  10572. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  10573. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  10574. };
  10575. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  10576. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  10577. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  10578. };
  10579. ;
  10580. Engine.prototype.bindIndexBuffer = function (buffer) {
  10581. if (!this._vaoRecordInProgress) {
  10582. this._unbindVertexArrayObject();
  10583. }
  10584. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  10585. };
  10586. Engine.prototype.bindBuffer = function (buffer, target) {
  10587. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  10588. this._gl.bindBuffer(target, buffer);
  10589. this._currentBoundBuffer[target] = buffer;
  10590. }
  10591. };
  10592. Engine.prototype.updateArrayBuffer = function (data) {
  10593. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  10594. };
  10595. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  10596. var pointer = this._currentBufferPointers[indx];
  10597. var changed = false;
  10598. if (!pointer.active) {
  10599. changed = true;
  10600. pointer.active = true;
  10601. pointer.index = indx;
  10602. pointer.size = size;
  10603. pointer.type = type;
  10604. pointer.normalized = normalized;
  10605. pointer.stride = stride;
  10606. pointer.offset = offset;
  10607. pointer.buffer = buffer;
  10608. }
  10609. else {
  10610. if (pointer.buffer !== buffer) {
  10611. pointer.buffer = buffer;
  10612. changed = true;
  10613. }
  10614. if (pointer.size !== size) {
  10615. pointer.size = size;
  10616. changed = true;
  10617. }
  10618. if (pointer.type !== type) {
  10619. pointer.type = type;
  10620. changed = true;
  10621. }
  10622. if (pointer.normalized !== normalized) {
  10623. pointer.normalized = normalized;
  10624. changed = true;
  10625. }
  10626. if (pointer.stride !== stride) {
  10627. pointer.stride = stride;
  10628. changed = true;
  10629. }
  10630. if (pointer.offset !== offset) {
  10631. pointer.offset = offset;
  10632. changed = true;
  10633. }
  10634. }
  10635. if (changed || this._vaoRecordInProgress) {
  10636. this.bindArrayBuffer(buffer);
  10637. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  10638. }
  10639. };
  10640. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  10641. if (indexBuffer == null) {
  10642. return;
  10643. }
  10644. if (this._cachedIndexBuffer !== indexBuffer) {
  10645. this._cachedIndexBuffer = indexBuffer;
  10646. this.bindIndexBuffer(indexBuffer);
  10647. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  10648. }
  10649. };
  10650. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  10651. var attributes = effect.getAttributesNames();
  10652. if (!this._vaoRecordInProgress) {
  10653. this._unbindVertexArrayObject();
  10654. }
  10655. this.unbindAllAttributes();
  10656. for (var index = 0; index < attributes.length; index++) {
  10657. var order = effect.getAttributeLocation(index);
  10658. if (order >= 0) {
  10659. var vertexBuffer = vertexBuffers[attributes[index]];
  10660. if (!vertexBuffer) {
  10661. continue;
  10662. }
  10663. this._gl.enableVertexAttribArray(order);
  10664. if (!this._vaoRecordInProgress) {
  10665. this._vertexAttribArraysEnabled[order] = true;
  10666. }
  10667. var buffer = vertexBuffer.getBuffer();
  10668. if (buffer) {
  10669. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  10670. if (vertexBuffer.getIsInstanced()) {
  10671. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  10672. if (!this._vaoRecordInProgress) {
  10673. this._currentInstanceLocations.push(order);
  10674. this._currentInstanceBuffers.push(buffer);
  10675. }
  10676. }
  10677. }
  10678. }
  10679. }
  10680. };
  10681. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  10682. var vao = this._gl.createVertexArray();
  10683. this._vaoRecordInProgress = true;
  10684. this._gl.bindVertexArray(vao);
  10685. this._mustWipeVertexAttributes = true;
  10686. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  10687. this.bindIndexBuffer(indexBuffer);
  10688. this._vaoRecordInProgress = false;
  10689. this._gl.bindVertexArray(null);
  10690. return vao;
  10691. };
  10692. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  10693. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  10694. this._cachedVertexArrayObject = vertexArrayObject;
  10695. this._gl.bindVertexArray(vertexArrayObject);
  10696. this._cachedVertexBuffers = null;
  10697. this._cachedIndexBuffer = null;
  10698. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  10699. this._mustWipeVertexAttributes = true;
  10700. }
  10701. };
  10702. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  10703. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  10704. this._cachedVertexBuffers = vertexBuffer;
  10705. this._cachedEffectForVertexBuffers = effect;
  10706. var attributesCount = effect.getAttributesCount();
  10707. this._unbindVertexArrayObject();
  10708. this.unbindAllAttributes();
  10709. var offset = 0;
  10710. for (var index = 0; index < attributesCount; index++) {
  10711. if (index < vertexDeclaration.length) {
  10712. var order = effect.getAttributeLocation(index);
  10713. if (order >= 0) {
  10714. this._gl.enableVertexAttribArray(order);
  10715. this._vertexAttribArraysEnabled[order] = true;
  10716. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  10717. }
  10718. offset += vertexDeclaration[index] * 4;
  10719. }
  10720. }
  10721. }
  10722. this._bindIndexBufferWithCache(indexBuffer);
  10723. };
  10724. Engine.prototype._unbindVertexArrayObject = function () {
  10725. if (!this._cachedVertexArrayObject) {
  10726. return;
  10727. }
  10728. this._cachedVertexArrayObject = null;
  10729. this._gl.bindVertexArray(null);
  10730. };
  10731. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  10732. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  10733. this._cachedVertexBuffers = vertexBuffers;
  10734. this._cachedEffectForVertexBuffers = effect;
  10735. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  10736. }
  10737. this._bindIndexBufferWithCache(indexBuffer);
  10738. };
  10739. Engine.prototype.unbindInstanceAttributes = function () {
  10740. var boundBuffer;
  10741. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  10742. var instancesBuffer = this._currentInstanceBuffers[i];
  10743. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  10744. boundBuffer = instancesBuffer;
  10745. this.bindArrayBuffer(instancesBuffer);
  10746. }
  10747. var offsetLocation = this._currentInstanceLocations[i];
  10748. this._gl.vertexAttribDivisor(offsetLocation, 0);
  10749. }
  10750. this._currentInstanceBuffers.length = 0;
  10751. this._currentInstanceLocations.length = 0;
  10752. };
  10753. Engine.prototype.releaseVertexArrayObject = function (vao) {
  10754. this._gl.deleteVertexArray(vao);
  10755. };
  10756. Engine.prototype._releaseBuffer = function (buffer) {
  10757. buffer.references--;
  10758. if (buffer.references === 0) {
  10759. this._gl.deleteBuffer(buffer);
  10760. return true;
  10761. }
  10762. return false;
  10763. };
  10764. Engine.prototype.createInstancesBuffer = function (capacity) {
  10765. var buffer = this._gl.createBuffer();
  10766. if (!buffer) {
  10767. throw new Error("Unable to create instance buffer");
  10768. }
  10769. buffer.capacity = capacity;
  10770. this.bindArrayBuffer(buffer);
  10771. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  10772. return buffer;
  10773. };
  10774. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  10775. this._gl.deleteBuffer(buffer);
  10776. };
  10777. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  10778. this.bindArrayBuffer(instancesBuffer);
  10779. if (data) {
  10780. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  10781. }
  10782. if (offsetLocations[0].index !== undefined) {
  10783. var stride = 0;
  10784. for (var i = 0; i < offsetLocations.length; i++) {
  10785. var ai = offsetLocations[i];
  10786. stride += ai.attributeSize * 4;
  10787. }
  10788. for (var i = 0; i < offsetLocations.length; i++) {
  10789. var ai = offsetLocations[i];
  10790. if (!this._vertexAttribArraysEnabled[ai.index]) {
  10791. this._gl.enableVertexAttribArray(ai.index);
  10792. this._vertexAttribArraysEnabled[ai.index] = true;
  10793. }
  10794. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  10795. this._gl.vertexAttribDivisor(ai.index, 1);
  10796. this._currentInstanceLocations.push(ai.index);
  10797. this._currentInstanceBuffers.push(instancesBuffer);
  10798. }
  10799. }
  10800. else {
  10801. for (var index = 0; index < 4; index++) {
  10802. var offsetLocation = offsetLocations[index];
  10803. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  10804. this._gl.enableVertexAttribArray(offsetLocation);
  10805. this._vertexAttribArraysEnabled[offsetLocation] = true;
  10806. }
  10807. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  10808. this._gl.vertexAttribDivisor(offsetLocation, 1);
  10809. this._currentInstanceLocations.push(offsetLocation);
  10810. this._currentInstanceBuffers.push(instancesBuffer);
  10811. }
  10812. }
  10813. };
  10814. Engine.prototype.applyStates = function () {
  10815. this._depthCullingState.apply(this._gl);
  10816. this._stencilState.apply(this._gl);
  10817. this._alphaState.apply(this._gl);
  10818. };
  10819. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  10820. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  10821. };
  10822. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  10823. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  10824. };
  10825. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  10826. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  10827. };
  10828. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  10829. // Apply states
  10830. this.applyStates();
  10831. this._drawCalls.addCount(1, false);
  10832. // Render
  10833. var drawMode = this.DrawMode(fillMode);
  10834. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  10835. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  10836. if (instancesCount) {
  10837. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  10838. }
  10839. else {
  10840. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  10841. }
  10842. };
  10843. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  10844. // Apply states
  10845. this.applyStates();
  10846. this._drawCalls.addCount(1, false);
  10847. var drawMode = this.DrawMode(fillMode);
  10848. if (instancesCount) {
  10849. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  10850. }
  10851. else {
  10852. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  10853. }
  10854. };
  10855. Engine.prototype.DrawMode = function (fillMode) {
  10856. switch (fillMode) {
  10857. // Triangle views
  10858. case BABYLON.Material.TriangleFillMode:
  10859. return this._gl.TRIANGLES;
  10860. case BABYLON.Material.PointFillMode:
  10861. return this._gl.POINTS;
  10862. case BABYLON.Material.WireFrameFillMode:
  10863. return this._gl.LINES;
  10864. // Draw modes
  10865. case BABYLON.Material.PointListDrawMode:
  10866. return this._gl.POINTS;
  10867. case BABYLON.Material.LineListDrawMode:
  10868. return this._gl.LINES;
  10869. case BABYLON.Material.LineLoopDrawMode:
  10870. return this._gl.LINE_LOOP;
  10871. case BABYLON.Material.LineStripDrawMode:
  10872. return this._gl.LINE_STRIP;
  10873. case BABYLON.Material.TriangleStripDrawMode:
  10874. return this._gl.TRIANGLE_STRIP;
  10875. case BABYLON.Material.TriangleFanDrawMode:
  10876. return this._gl.TRIANGLE_FAN;
  10877. default:
  10878. return this._gl.TRIANGLES;
  10879. }
  10880. };
  10881. // Shaders
  10882. Engine.prototype._releaseEffect = function (effect) {
  10883. if (this._compiledEffects[effect._key]) {
  10884. delete this._compiledEffects[effect._key];
  10885. this._deleteProgram(effect.getProgram());
  10886. }
  10887. };
  10888. Engine.prototype._deleteProgram = function (program) {
  10889. if (program) {
  10890. program.__SPECTOR_rebuildProgram = null;
  10891. if (program.transformFeedback) {
  10892. this.deleteTransformFeedback(program.transformFeedback);
  10893. program.transformFeedback = null;
  10894. }
  10895. this._gl.deleteProgram(program);
  10896. }
  10897. };
  10898. /**
  10899. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  10900. * @param samplers An array of string used to represent textures
  10901. */
  10902. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  10903. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  10904. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  10905. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  10906. if (this._compiledEffects[name]) {
  10907. var compiledEffect = this._compiledEffects[name];
  10908. if (onCompiled && compiledEffect.isReady()) {
  10909. onCompiled(compiledEffect);
  10910. }
  10911. return compiledEffect;
  10912. }
  10913. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  10914. effect._key = name;
  10915. this._compiledEffects[name] = effect;
  10916. return effect;
  10917. };
  10918. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  10919. if (uniformsNames === void 0) { uniformsNames = []; }
  10920. if (samplers === void 0) { samplers = []; }
  10921. if (defines === void 0) { defines = ""; }
  10922. return this.createEffect({
  10923. vertex: "particles",
  10924. fragmentElement: fragmentName
  10925. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  10926. };
  10927. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  10928. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10929. context = context || this._gl;
  10930. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  10931. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  10932. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  10933. };
  10934. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  10935. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10936. context = context || this._gl;
  10937. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  10938. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  10939. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  10940. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  10941. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  10942. this.onAfterShaderCompilationObservable.notifyObservers(this);
  10943. return program;
  10944. };
  10945. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  10946. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10947. var shaderProgram = context.createProgram();
  10948. if (!shaderProgram) {
  10949. throw new Error("Unable to create program");
  10950. }
  10951. context.attachShader(shaderProgram, vertexShader);
  10952. context.attachShader(shaderProgram, fragmentShader);
  10953. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  10954. var transformFeedback = this.createTransformFeedback();
  10955. this.bindTransformFeedback(transformFeedback);
  10956. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  10957. shaderProgram.transformFeedback = transformFeedback;
  10958. }
  10959. context.linkProgram(shaderProgram);
  10960. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  10961. this.bindTransformFeedback(null);
  10962. }
  10963. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  10964. if (!linked) {
  10965. context.validateProgram(shaderProgram);
  10966. var error = context.getProgramInfoLog(shaderProgram);
  10967. if (error) {
  10968. throw new Error(error);
  10969. }
  10970. }
  10971. context.deleteShader(vertexShader);
  10972. context.deleteShader(fragmentShader);
  10973. return shaderProgram;
  10974. };
  10975. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  10976. var results = new Array();
  10977. for (var index = 0; index < uniformsNames.length; index++) {
  10978. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  10979. }
  10980. return results;
  10981. };
  10982. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  10983. var results = [];
  10984. for (var index = 0; index < attributesNames.length; index++) {
  10985. try {
  10986. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  10987. }
  10988. catch (e) {
  10989. results.push(-1);
  10990. }
  10991. }
  10992. return results;
  10993. };
  10994. Engine.prototype.enableEffect = function (effect) {
  10995. if (!effect) {
  10996. return;
  10997. }
  10998. // Use program
  10999. this.bindSamplers(effect);
  11000. this._currentEffect = effect;
  11001. if (effect.onBind) {
  11002. effect.onBind(effect);
  11003. }
  11004. effect.onBindObservable.notifyObservers(effect);
  11005. };
  11006. Engine.prototype.setIntArray = function (uniform, array) {
  11007. if (!uniform)
  11008. return;
  11009. this._gl.uniform1iv(uniform, array);
  11010. };
  11011. Engine.prototype.setIntArray2 = function (uniform, array) {
  11012. if (!uniform || array.length % 2 !== 0)
  11013. return;
  11014. this._gl.uniform2iv(uniform, array);
  11015. };
  11016. Engine.prototype.setIntArray3 = function (uniform, array) {
  11017. if (!uniform || array.length % 3 !== 0)
  11018. return;
  11019. this._gl.uniform3iv(uniform, array);
  11020. };
  11021. Engine.prototype.setIntArray4 = function (uniform, array) {
  11022. if (!uniform || array.length % 4 !== 0)
  11023. return;
  11024. this._gl.uniform4iv(uniform, array);
  11025. };
  11026. Engine.prototype.setFloatArray = function (uniform, array) {
  11027. if (!uniform)
  11028. return;
  11029. this._gl.uniform1fv(uniform, array);
  11030. };
  11031. Engine.prototype.setFloatArray2 = function (uniform, array) {
  11032. if (!uniform || array.length % 2 !== 0)
  11033. return;
  11034. this._gl.uniform2fv(uniform, array);
  11035. };
  11036. Engine.prototype.setFloatArray3 = function (uniform, array) {
  11037. if (!uniform || array.length % 3 !== 0)
  11038. return;
  11039. this._gl.uniform3fv(uniform, array);
  11040. };
  11041. Engine.prototype.setFloatArray4 = function (uniform, array) {
  11042. if (!uniform || array.length % 4 !== 0)
  11043. return;
  11044. this._gl.uniform4fv(uniform, array);
  11045. };
  11046. Engine.prototype.setArray = function (uniform, array) {
  11047. if (!uniform)
  11048. return;
  11049. this._gl.uniform1fv(uniform, array);
  11050. };
  11051. Engine.prototype.setArray2 = function (uniform, array) {
  11052. if (!uniform || array.length % 2 !== 0)
  11053. return;
  11054. this._gl.uniform2fv(uniform, array);
  11055. };
  11056. Engine.prototype.setArray3 = function (uniform, array) {
  11057. if (!uniform || array.length % 3 !== 0)
  11058. return;
  11059. this._gl.uniform3fv(uniform, array);
  11060. };
  11061. Engine.prototype.setArray4 = function (uniform, array) {
  11062. if (!uniform || array.length % 4 !== 0)
  11063. return;
  11064. this._gl.uniform4fv(uniform, array);
  11065. };
  11066. Engine.prototype.setMatrices = function (uniform, matrices) {
  11067. if (!uniform)
  11068. return;
  11069. this._gl.uniformMatrix4fv(uniform, false, matrices);
  11070. };
  11071. Engine.prototype.setMatrix = function (uniform, matrix) {
  11072. if (!uniform)
  11073. return;
  11074. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  11075. };
  11076. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  11077. if (!uniform)
  11078. return;
  11079. this._gl.uniformMatrix3fv(uniform, false, matrix);
  11080. };
  11081. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  11082. if (!uniform)
  11083. return;
  11084. this._gl.uniformMatrix2fv(uniform, false, matrix);
  11085. };
  11086. Engine.prototype.setInt = function (uniform, value) {
  11087. if (!uniform)
  11088. return;
  11089. this._gl.uniform1i(uniform, value);
  11090. };
  11091. Engine.prototype.setFloat = function (uniform, value) {
  11092. if (!uniform)
  11093. return;
  11094. this._gl.uniform1f(uniform, value);
  11095. };
  11096. Engine.prototype.setFloat2 = function (uniform, x, y) {
  11097. if (!uniform)
  11098. return;
  11099. this._gl.uniform2f(uniform, x, y);
  11100. };
  11101. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  11102. if (!uniform)
  11103. return;
  11104. this._gl.uniform3f(uniform, x, y, z);
  11105. };
  11106. Engine.prototype.setBool = function (uniform, bool) {
  11107. if (!uniform)
  11108. return;
  11109. this._gl.uniform1i(uniform, bool);
  11110. };
  11111. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  11112. if (!uniform)
  11113. return;
  11114. this._gl.uniform4f(uniform, x, y, z, w);
  11115. };
  11116. Engine.prototype.setColor3 = function (uniform, color3) {
  11117. if (!uniform)
  11118. return;
  11119. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  11120. };
  11121. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  11122. if (!uniform)
  11123. return;
  11124. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  11125. };
  11126. // States
  11127. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  11128. if (zOffset === void 0) { zOffset = 0; }
  11129. if (reverseSide === void 0) { reverseSide = false; }
  11130. // Culling
  11131. if (this._depthCullingState.cull !== culling || force) {
  11132. this._depthCullingState.cull = culling;
  11133. }
  11134. // Cull face
  11135. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  11136. if (this._depthCullingState.cullFace !== cullFace || force) {
  11137. this._depthCullingState.cullFace = cullFace;
  11138. }
  11139. // Z offset
  11140. this.setZOffset(zOffset);
  11141. // Front face
  11142. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  11143. if (this._depthCullingState.frontFace !== frontFace || force) {
  11144. this._depthCullingState.frontFace = frontFace;
  11145. }
  11146. };
  11147. Engine.prototype.setZOffset = function (value) {
  11148. this._depthCullingState.zOffset = value;
  11149. };
  11150. Engine.prototype.getZOffset = function () {
  11151. return this._depthCullingState.zOffset;
  11152. };
  11153. Engine.prototype.setDepthBuffer = function (enable) {
  11154. this._depthCullingState.depthTest = enable;
  11155. };
  11156. Engine.prototype.getDepthWrite = function () {
  11157. return this._depthCullingState.depthMask;
  11158. };
  11159. Engine.prototype.setDepthWrite = function (enable) {
  11160. this._depthCullingState.depthMask = enable;
  11161. };
  11162. Engine.prototype.setColorWrite = function (enable) {
  11163. this._gl.colorMask(enable, enable, enable, enable);
  11164. this._colorWrite = enable;
  11165. };
  11166. Engine.prototype.getColorWrite = function () {
  11167. return this._colorWrite;
  11168. };
  11169. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  11170. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  11171. };
  11172. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  11173. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  11174. if (this._alphaMode === mode) {
  11175. return;
  11176. }
  11177. switch (mode) {
  11178. case Engine.ALPHA_DISABLE:
  11179. this._alphaState.alphaBlend = false;
  11180. break;
  11181. case Engine.ALPHA_PREMULTIPLIED:
  11182. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11183. this._alphaState.alphaBlend = true;
  11184. break;
  11185. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  11186. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11187. this._alphaState.alphaBlend = true;
  11188. break;
  11189. case Engine.ALPHA_COMBINE:
  11190. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11191. this._alphaState.alphaBlend = true;
  11192. break;
  11193. case Engine.ALPHA_ONEONE:
  11194. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11195. this._alphaState.alphaBlend = true;
  11196. break;
  11197. case Engine.ALPHA_ADD:
  11198. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11199. this._alphaState.alphaBlend = true;
  11200. break;
  11201. case Engine.ALPHA_SUBTRACT:
  11202. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11203. this._alphaState.alphaBlend = true;
  11204. break;
  11205. case Engine.ALPHA_MULTIPLY:
  11206. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  11207. this._alphaState.alphaBlend = true;
  11208. break;
  11209. case Engine.ALPHA_MAXIMIZED:
  11210. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11211. this._alphaState.alphaBlend = true;
  11212. break;
  11213. case Engine.ALPHA_INTERPOLATE:
  11214. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  11215. this._alphaState.alphaBlend = true;
  11216. break;
  11217. case Engine.ALPHA_SCREENMODE:
  11218. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11219. this._alphaState.alphaBlend = true;
  11220. break;
  11221. }
  11222. if (!noDepthWriteChange) {
  11223. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  11224. }
  11225. this._alphaMode = mode;
  11226. };
  11227. Engine.prototype.getAlphaMode = function () {
  11228. return this._alphaMode;
  11229. };
  11230. Engine.prototype.setAlphaTesting = function (enable) {
  11231. this._alphaTest = enable;
  11232. };
  11233. Engine.prototype.getAlphaTesting = function () {
  11234. return !!this._alphaTest;
  11235. };
  11236. // Textures
  11237. Engine.prototype.wipeCaches = function (bruteForce) {
  11238. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  11239. return;
  11240. }
  11241. this._currentEffect = null;
  11242. // 6/8/2017: deltakosh: Should not be required anymore.
  11243. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  11244. if (bruteForce) {
  11245. this.resetTextureCache();
  11246. this._currentProgram = null;
  11247. this._stencilState.reset();
  11248. this._depthCullingState.reset();
  11249. this.setDepthFunctionToLessOrEqual();
  11250. this._alphaState.reset();
  11251. }
  11252. this._resetVertexBufferBinding();
  11253. this._cachedIndexBuffer = null;
  11254. this._cachedEffectForVertexBuffers = null;
  11255. this._unbindVertexArrayObject();
  11256. this.bindIndexBuffer(null);
  11257. };
  11258. /**
  11259. * Set the compressed texture format to use, based on the formats you have, and the formats
  11260. * supported by the hardware / browser.
  11261. *
  11262. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  11263. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  11264. * to API arguments needed to compressed textures. This puts the burden on the container
  11265. * generator to house the arcane code for determining these for current & future formats.
  11266. *
  11267. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  11268. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  11269. *
  11270. * Note: The result of this call is not taken into account when a texture is base64.
  11271. *
  11272. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  11273. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  11274. *
  11275. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  11276. * @returns The extension selected.
  11277. */
  11278. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  11279. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  11280. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  11281. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  11282. return this._textureFormatInUse = this._texturesSupported[i];
  11283. }
  11284. }
  11285. }
  11286. // actively set format to nothing, to allow this to be called more than once
  11287. // and possibly fail the 2nd time
  11288. this._textureFormatInUse = null;
  11289. return null;
  11290. };
  11291. Engine.prototype._createTexture = function () {
  11292. var texture = this._gl.createTexture();
  11293. if (!texture) {
  11294. throw new Error("Unable to create texture");
  11295. }
  11296. return texture;
  11297. };
  11298. /**
  11299. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  11300. * @param {string} urlArg- This contains one of the following:
  11301. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  11302. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  11303. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  11304. *
  11305. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  11306. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  11307. * @param {Scene} scene- Needed for loading to the correct scene.
  11308. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  11309. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  11310. * @param {callback} onError- Optional callback to be called upon failure.
  11311. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  11312. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  11313. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  11314. *
  11315. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  11316. */
  11317. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  11318. var _this = this;
  11319. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11320. if (onLoad === void 0) { onLoad = null; }
  11321. if (onError === void 0) { onError = null; }
  11322. if (buffer === void 0) { buffer = null; }
  11323. if (fallBack === void 0) { fallBack = null; }
  11324. if (format === void 0) { format = null; }
  11325. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  11326. var fromData = url.substr(0, 5) === "data:";
  11327. var fromBlob = url.substr(0, 5) === "blob:";
  11328. var isBase64 = fromData && url.indexOf("base64") !== -1;
  11329. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  11330. // establish the file extension, if possible
  11331. var lastDot = url.lastIndexOf('.');
  11332. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  11333. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  11334. var isTGA = (extension === ".tga");
  11335. // determine if a ktx file should be substituted
  11336. var isKTX = false;
  11337. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  11338. url = url.substring(0, lastDot) + this._textureFormatInUse;
  11339. isKTX = true;
  11340. }
  11341. if (scene) {
  11342. scene._addPendingData(texture);
  11343. }
  11344. texture.url = url;
  11345. texture.generateMipMaps = !noMipmap;
  11346. texture.samplingMode = samplingMode;
  11347. texture.invertY = invertY;
  11348. if (!this._doNotHandleContextLost) {
  11349. // Keep a link to the buffer only if we plan to handle context lost
  11350. texture._buffer = buffer;
  11351. }
  11352. var onLoadObserver = null;
  11353. if (onLoad && !fallBack) {
  11354. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  11355. }
  11356. if (!fallBack)
  11357. this._internalTexturesCache.push(texture);
  11358. var onerror = function (message, exception) {
  11359. if (scene) {
  11360. scene._removePendingData(texture);
  11361. }
  11362. if (onLoadObserver) {
  11363. texture.onLoadedObservable.remove(onLoadObserver);
  11364. }
  11365. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  11366. if (isKTX) {
  11367. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11368. }
  11369. else if (BABYLON.Tools.UseFallbackTexture) {
  11370. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11371. }
  11372. if (onError) {
  11373. onError(message || "Unknown error", exception);
  11374. }
  11375. };
  11376. var callback = null;
  11377. // processing for non-image formats
  11378. if (isKTX || isTGA || isDDS) {
  11379. if (isKTX) {
  11380. callback = function (data) {
  11381. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  11382. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  11383. ktx.uploadLevels(_this._gl, !noMipmap);
  11384. return false;
  11385. }, samplingMode);
  11386. };
  11387. }
  11388. else if (isTGA) {
  11389. callback = function (arrayBuffer) {
  11390. var data = new Uint8Array(arrayBuffer);
  11391. var header = BABYLON.TGATools.GetTGAHeader(data);
  11392. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  11393. BABYLON.TGATools.UploadContent(_this._gl, data);
  11394. return false;
  11395. }, samplingMode);
  11396. };
  11397. }
  11398. else if (isDDS) {
  11399. callback = function (data) {
  11400. var info = BABYLON.DDSTools.GetDDSInfo(data);
  11401. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  11402. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  11403. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  11404. return false;
  11405. }, samplingMode);
  11406. };
  11407. }
  11408. if (!buffer) {
  11409. this._loadFile(url, function (data) {
  11410. if (callback) {
  11411. callback(data);
  11412. }
  11413. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  11414. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  11415. });
  11416. }
  11417. else {
  11418. if (callback) {
  11419. callback(buffer);
  11420. }
  11421. }
  11422. // image format processing
  11423. }
  11424. else {
  11425. var onload = function (img) {
  11426. if (fromBlob && !_this._doNotHandleContextLost) {
  11427. // We need to store the image if we need to rebuild the texture
  11428. // in case of a webgl context lost
  11429. texture._buffer = img;
  11430. }
  11431. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  11432. var gl = _this._gl;
  11433. var isPot = (img.width === potWidth && img.height === potHeight);
  11434. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  11435. if (isPot) {
  11436. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  11437. return false;
  11438. }
  11439. // Using shaders to rescale because canvas.drawImage is lossy
  11440. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  11441. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  11442. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  11443. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11444. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  11445. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11446. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11447. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  11448. _this._releaseTexture(source);
  11449. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11450. continuationCallback();
  11451. });
  11452. return true;
  11453. }, samplingMode);
  11454. };
  11455. if (!fromData || isBase64)
  11456. if (buffer instanceof HTMLImageElement) {
  11457. onload(buffer);
  11458. }
  11459. else {
  11460. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11461. }
  11462. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  11463. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  11464. else
  11465. onload(buffer);
  11466. }
  11467. return texture;
  11468. };
  11469. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  11470. var _this = this;
  11471. var rtt = this.createRenderTargetTexture({
  11472. width: destination.width,
  11473. height: destination.height,
  11474. }, {
  11475. generateMipMaps: false,
  11476. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  11477. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  11478. generateDepthBuffer: false,
  11479. generateStencilBuffer: false
  11480. });
  11481. if (!this._rescalePostProcess) {
  11482. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  11483. }
  11484. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  11485. _this._rescalePostProcess.onApply = function (effect) {
  11486. effect._bindTexture("textureSampler", source);
  11487. };
  11488. var hostingScene = scene;
  11489. if (!hostingScene) {
  11490. hostingScene = _this.scenes[_this.scenes.length - 1];
  11491. }
  11492. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  11493. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  11494. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  11495. _this.unBindFramebuffer(rtt);
  11496. _this._releaseTexture(rtt);
  11497. if (onComplete) {
  11498. onComplete();
  11499. }
  11500. });
  11501. };
  11502. Engine.prototype._getInternalFormat = function (format) {
  11503. var internalFormat = this._gl.RGBA;
  11504. switch (format) {
  11505. case Engine.TEXTUREFORMAT_ALPHA:
  11506. internalFormat = this._gl.ALPHA;
  11507. break;
  11508. case Engine.TEXTUREFORMAT_LUMINANCE:
  11509. internalFormat = this._gl.LUMINANCE;
  11510. break;
  11511. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  11512. internalFormat = this._gl.LUMINANCE_ALPHA;
  11513. break;
  11514. case Engine.TEXTUREFORMAT_RGB:
  11515. internalFormat = this._gl.RGB;
  11516. break;
  11517. case Engine.TEXTUREFORMAT_RGBA:
  11518. internalFormat = this._gl.RGBA;
  11519. break;
  11520. }
  11521. return internalFormat;
  11522. };
  11523. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  11524. if (compression === void 0) { compression = null; }
  11525. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  11526. if (!texture) {
  11527. return;
  11528. }
  11529. var internalFormat = this._getInternalFormat(format);
  11530. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11531. var textureType = this._getWebGLTextureType(type);
  11532. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11533. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11534. if (!this._doNotHandleContextLost) {
  11535. texture._bufferView = data;
  11536. texture.format = format;
  11537. texture.type = type;
  11538. texture.invertY = invertY;
  11539. texture._compression = compression;
  11540. }
  11541. if (texture.width % 4 !== 0) {
  11542. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11543. }
  11544. if (compression && data) {
  11545. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  11546. }
  11547. else {
  11548. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  11549. }
  11550. if (texture.generateMipMaps) {
  11551. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11552. }
  11553. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11554. // this.resetTextureCache();
  11555. texture.isReady = true;
  11556. };
  11557. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  11558. if (compression === void 0) { compression = null; }
  11559. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  11560. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  11561. texture.baseWidth = width;
  11562. texture.baseHeight = height;
  11563. texture.width = width;
  11564. texture.height = height;
  11565. texture.format = format;
  11566. texture.generateMipMaps = generateMipMaps;
  11567. texture.samplingMode = samplingMode;
  11568. texture.invertY = invertY;
  11569. texture._compression = compression;
  11570. texture.type = type;
  11571. if (!this._doNotHandleContextLost) {
  11572. texture._bufferView = data;
  11573. }
  11574. this.updateRawTexture(texture, data, format, invertY, compression, type);
  11575. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11576. // Filters
  11577. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11578. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11579. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11580. if (generateMipMaps) {
  11581. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11582. }
  11583. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11584. this._internalTexturesCache.push(texture);
  11585. return texture;
  11586. };
  11587. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  11588. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  11589. texture.baseWidth = width;
  11590. texture.baseHeight = height;
  11591. if (generateMipMaps) {
  11592. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  11593. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  11594. }
  11595. // this.resetTextureCache();
  11596. texture.width = width;
  11597. texture.height = height;
  11598. texture.isReady = false;
  11599. texture.generateMipMaps = generateMipMaps;
  11600. texture.samplingMode = samplingMode;
  11601. this.updateTextureSamplingMode(samplingMode, texture);
  11602. this._internalTexturesCache.push(texture);
  11603. return texture;
  11604. };
  11605. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  11606. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  11607. if (texture.isCube) {
  11608. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  11609. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11610. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11611. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11612. }
  11613. else if (texture.is3D) {
  11614. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  11615. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11616. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11617. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11618. }
  11619. else {
  11620. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11621. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11622. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11623. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11624. }
  11625. texture.samplingMode = samplingMode;
  11626. };
  11627. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  11628. if (premulAlpha === void 0) { premulAlpha = false; }
  11629. if (!texture) {
  11630. return;
  11631. }
  11632. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11633. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  11634. if (premulAlpha) {
  11635. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  11636. }
  11637. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  11638. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  11639. if (texture.generateMipMaps) {
  11640. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11641. }
  11642. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11643. if (premulAlpha) {
  11644. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  11645. }
  11646. texture.isReady = true;
  11647. };
  11648. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  11649. if (!texture || texture._isDisabled) {
  11650. return;
  11651. }
  11652. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11653. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  11654. try {
  11655. // Testing video texture support
  11656. if (this._videoTextureSupported === undefined) {
  11657. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  11658. if (this._gl.getError() !== 0) {
  11659. this._videoTextureSupported = false;
  11660. }
  11661. else {
  11662. this._videoTextureSupported = true;
  11663. }
  11664. }
  11665. // Copy video through the current working canvas if video texture is not supported
  11666. if (!this._videoTextureSupported) {
  11667. if (!texture._workingCanvas) {
  11668. texture._workingCanvas = document.createElement("canvas");
  11669. var context = texture._workingCanvas.getContext("2d");
  11670. if (!context) {
  11671. throw new Error("Unable to get 2d context");
  11672. }
  11673. texture._workingContext = context;
  11674. texture._workingCanvas.width = texture.width;
  11675. texture._workingCanvas.height = texture.height;
  11676. }
  11677. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  11678. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  11679. }
  11680. else {
  11681. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  11682. }
  11683. if (texture.generateMipMaps) {
  11684. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11685. }
  11686. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11687. // this.resetTextureCache();
  11688. texture.isReady = true;
  11689. }
  11690. catch (ex) {
  11691. // Something unexpected
  11692. // Let's disable the texture
  11693. texture._isDisabled = true;
  11694. }
  11695. };
  11696. Engine.prototype.createRenderTargetTexture = function (size, options) {
  11697. var fullOptions = new RenderTargetCreationOptions();
  11698. if (options !== undefined && typeof options === "object") {
  11699. fullOptions.generateMipMaps = options.generateMipMaps;
  11700. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  11701. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  11702. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  11703. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  11704. }
  11705. else {
  11706. fullOptions.generateMipMaps = options;
  11707. fullOptions.generateDepthBuffer = true;
  11708. fullOptions.generateStencilBuffer = false;
  11709. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11710. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  11711. }
  11712. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  11713. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  11714. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11715. }
  11716. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  11717. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  11718. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11719. }
  11720. var gl = this._gl;
  11721. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  11722. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11723. var width = size.width || size;
  11724. var height = size.height || size;
  11725. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  11726. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  11727. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11728. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  11729. }
  11730. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11731. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11732. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11733. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11734. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  11735. // Create the framebuffer
  11736. var framebuffer = gl.createFramebuffer();
  11737. this.bindUnboundFramebuffer(framebuffer);
  11738. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11739. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  11740. if (fullOptions.generateMipMaps) {
  11741. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11742. }
  11743. // Unbind
  11744. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11745. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11746. this.bindUnboundFramebuffer(null);
  11747. texture._framebuffer = framebuffer;
  11748. texture.baseWidth = width;
  11749. texture.baseHeight = height;
  11750. texture.width = width;
  11751. texture.height = height;
  11752. texture.isReady = true;
  11753. texture.samples = 1;
  11754. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  11755. texture.samplingMode = fullOptions.samplingMode;
  11756. texture.type = fullOptions.type;
  11757. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  11758. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  11759. // this.resetTextureCache();
  11760. this._internalTexturesCache.push(texture);
  11761. return texture;
  11762. };
  11763. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  11764. var generateMipMaps = false;
  11765. var generateDepthBuffer = true;
  11766. var generateStencilBuffer = false;
  11767. var generateDepthTexture = false;
  11768. var textureCount = 1;
  11769. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  11770. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  11771. var types = [], samplingModes = [];
  11772. if (options !== undefined) {
  11773. generateMipMaps = options.generateMipMaps;
  11774. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  11775. generateStencilBuffer = options.generateStencilBuffer;
  11776. generateDepthTexture = options.generateDepthTexture;
  11777. textureCount = options.textureCount || 1;
  11778. if (options.types) {
  11779. types = options.types;
  11780. }
  11781. if (options.samplingModes) {
  11782. samplingModes = options.samplingModes;
  11783. }
  11784. }
  11785. var gl = this._gl;
  11786. // Create the framebuffer
  11787. var framebuffer = gl.createFramebuffer();
  11788. this.bindUnboundFramebuffer(framebuffer);
  11789. var width = size.width || size;
  11790. var height = size.height || size;
  11791. var textures = [];
  11792. var attachments = [];
  11793. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  11794. for (var i = 0; i < textureCount; i++) {
  11795. var samplingMode = samplingModes[i] || defaultSamplingMode;
  11796. var type = types[i] || defaultType;
  11797. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  11798. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  11799. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11800. }
  11801. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  11802. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  11803. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11804. }
  11805. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11806. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  11807. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11808. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  11809. }
  11810. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  11811. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11812. textures.push(texture);
  11813. attachments.push(attachment);
  11814. gl.activeTexture(gl["TEXTURE" + i]);
  11815. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  11816. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11817. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11818. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11819. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11820. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11821. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11822. if (generateMipMaps) {
  11823. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11824. }
  11825. // Unbind
  11826. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11827. texture._framebuffer = framebuffer;
  11828. texture._depthStencilBuffer = depthStencilBuffer;
  11829. texture.baseWidth = width;
  11830. texture.baseHeight = height;
  11831. texture.width = width;
  11832. texture.height = height;
  11833. texture.isReady = true;
  11834. texture.samples = 1;
  11835. texture.generateMipMaps = generateMipMaps;
  11836. texture.samplingMode = samplingMode;
  11837. texture.type = type;
  11838. texture._generateDepthBuffer = generateDepthBuffer;
  11839. texture._generateStencilBuffer = generateStencilBuffer;
  11840. texture._attachments = attachments;
  11841. this._internalTexturesCache.push(texture);
  11842. }
  11843. if (generateDepthTexture && this._caps.depthTextureExtension) {
  11844. // Depth texture
  11845. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  11846. gl.activeTexture(gl.TEXTURE0);
  11847. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  11848. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11849. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11850. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11851. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11852. 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);
  11853. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  11854. depthTexture._framebuffer = framebuffer;
  11855. depthTexture.baseWidth = width;
  11856. depthTexture.baseHeight = height;
  11857. depthTexture.width = width;
  11858. depthTexture.height = height;
  11859. depthTexture.isReady = true;
  11860. depthTexture.samples = 1;
  11861. depthTexture.generateMipMaps = generateMipMaps;
  11862. depthTexture.samplingMode = gl.NEAREST;
  11863. depthTexture._generateDepthBuffer = generateDepthBuffer;
  11864. depthTexture._generateStencilBuffer = generateStencilBuffer;
  11865. textures.push(depthTexture);
  11866. this._internalTexturesCache.push(depthTexture);
  11867. }
  11868. gl.drawBuffers(attachments);
  11869. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11870. this.bindUnboundFramebuffer(null);
  11871. this.resetTextureCache();
  11872. return textures;
  11873. };
  11874. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  11875. if (samples === void 0) { samples = 1; }
  11876. var depthStencilBuffer = null;
  11877. var gl = this._gl;
  11878. // Create the depth/stencil buffer
  11879. if (generateStencilBuffer) {
  11880. depthStencilBuffer = gl.createRenderbuffer();
  11881. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  11882. if (samples > 1) {
  11883. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  11884. }
  11885. else {
  11886. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  11887. }
  11888. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  11889. }
  11890. else if (generateDepthBuffer) {
  11891. depthStencilBuffer = gl.createRenderbuffer();
  11892. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  11893. if (samples > 1) {
  11894. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  11895. }
  11896. else {
  11897. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  11898. }
  11899. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  11900. }
  11901. return depthStencilBuffer;
  11902. };
  11903. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  11904. if (this.webGLVersion < 2 || !texture) {
  11905. return 1;
  11906. }
  11907. if (texture.samples === samples) {
  11908. return samples;
  11909. }
  11910. var gl = this._gl;
  11911. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  11912. // Dispose previous render buffers
  11913. if (texture._depthStencilBuffer) {
  11914. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11915. texture._depthStencilBuffer = null;
  11916. }
  11917. if (texture._MSAAFramebuffer) {
  11918. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11919. texture._MSAAFramebuffer = null;
  11920. }
  11921. if (texture._MSAARenderBuffer) {
  11922. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11923. texture._MSAARenderBuffer = null;
  11924. }
  11925. if (samples > 1) {
  11926. var framebuffer = gl.createFramebuffer();
  11927. if (!framebuffer) {
  11928. throw new Error("Unable to create multi sampled framebuffer");
  11929. }
  11930. texture._MSAAFramebuffer = framebuffer;
  11931. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  11932. var colorRenderbuffer = gl.createRenderbuffer();
  11933. if (!colorRenderbuffer) {
  11934. throw new Error("Unable to create multi sampled framebuffer");
  11935. }
  11936. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  11937. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  11938. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  11939. texture._MSAARenderBuffer = colorRenderbuffer;
  11940. }
  11941. else {
  11942. this.bindUnboundFramebuffer(texture._framebuffer);
  11943. }
  11944. texture.samples = samples;
  11945. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  11946. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11947. this.bindUnboundFramebuffer(null);
  11948. return samples;
  11949. };
  11950. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  11951. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  11952. return 1;
  11953. }
  11954. if (textures[0].samples === samples) {
  11955. return samples;
  11956. }
  11957. var gl = this._gl;
  11958. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  11959. // Dispose previous render buffers
  11960. if (textures[0]._depthStencilBuffer) {
  11961. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  11962. textures[0]._depthStencilBuffer = null;
  11963. }
  11964. if (textures[0]._MSAAFramebuffer) {
  11965. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  11966. textures[0]._MSAAFramebuffer = null;
  11967. }
  11968. for (var i = 0; i < textures.length; i++) {
  11969. if (textures[i]._MSAARenderBuffer) {
  11970. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  11971. textures[i]._MSAARenderBuffer = null;
  11972. }
  11973. }
  11974. if (samples > 1) {
  11975. var framebuffer = gl.createFramebuffer();
  11976. if (!framebuffer) {
  11977. throw new Error("Unable to create multi sampled framebuffer");
  11978. }
  11979. this.bindUnboundFramebuffer(framebuffer);
  11980. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  11981. var attachments = [];
  11982. for (var i = 0; i < textures.length; i++) {
  11983. var texture = textures[i];
  11984. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11985. var colorRenderbuffer = gl.createRenderbuffer();
  11986. if (!colorRenderbuffer) {
  11987. throw new Error("Unable to create multi sampled framebuffer");
  11988. }
  11989. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  11990. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  11991. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  11992. texture._MSAAFramebuffer = framebuffer;
  11993. texture._MSAARenderBuffer = colorRenderbuffer;
  11994. texture.samples = samples;
  11995. texture._depthStencilBuffer = depthStencilBuffer;
  11996. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11997. attachments.push(attachment);
  11998. }
  11999. gl.drawBuffers(attachments);
  12000. }
  12001. else {
  12002. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12003. }
  12004. this.bindUnboundFramebuffer(null);
  12005. return samples;
  12006. };
  12007. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  12008. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  12009. };
  12010. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  12011. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  12012. };
  12013. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  12014. var gl = this._gl;
  12015. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12016. var generateMipMaps = true;
  12017. var generateDepthBuffer = true;
  12018. var generateStencilBuffer = false;
  12019. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12020. if (options !== undefined) {
  12021. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  12022. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12023. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  12024. if (options.samplingMode !== undefined) {
  12025. samplingMode = options.samplingMode;
  12026. }
  12027. }
  12028. texture.isCube = true;
  12029. texture.generateMipMaps = generateMipMaps;
  12030. texture.samples = 1;
  12031. texture.samplingMode = samplingMode;
  12032. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12033. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12034. for (var face = 0; face < 6; face++) {
  12035. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  12036. }
  12037. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12038. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12039. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12040. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12041. // Create the framebuffer
  12042. var framebuffer = gl.createFramebuffer();
  12043. this.bindUnboundFramebuffer(framebuffer);
  12044. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  12045. // Mipmaps
  12046. if (texture.generateMipMaps) {
  12047. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12048. }
  12049. // Unbind
  12050. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12051. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12052. this.bindUnboundFramebuffer(null);
  12053. texture._framebuffer = framebuffer;
  12054. texture.width = size;
  12055. texture.height = size;
  12056. texture.isReady = true;
  12057. //this.resetTextureCache();
  12058. this._internalTexturesCache.push(texture);
  12059. return texture;
  12060. };
  12061. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  12062. var _this = this;
  12063. if (onLoad === void 0) { onLoad = null; }
  12064. if (onError === void 0) { onError = null; }
  12065. if (forcedExtension === void 0) { forcedExtension = null; }
  12066. var callback = function (loadData) {
  12067. if (!loadData) {
  12068. if (onLoad) {
  12069. onLoad(null);
  12070. }
  12071. return;
  12072. }
  12073. var texture = loadData.texture;
  12074. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  12075. texture._lodGenerationScale = scale;
  12076. texture._lodGenerationOffset = offset;
  12077. if (_this._caps.textureLOD) {
  12078. // Do not add extra process if texture lod is supported.
  12079. if (onLoad) {
  12080. onLoad(texture);
  12081. }
  12082. return;
  12083. }
  12084. var mipSlices = 3;
  12085. var gl = _this._gl;
  12086. var width = loadData.width;
  12087. if (!width) {
  12088. return;
  12089. }
  12090. var textures = [];
  12091. for (var i = 0; i < mipSlices; i++) {
  12092. //compute LOD from even spacing in smoothness (matching shader calculation)
  12093. var smoothness = i / (mipSlices - 1);
  12094. var roughness = 1 - smoothness;
  12095. var minLODIndex = offset; // roughness = 0
  12096. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  12097. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  12098. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  12099. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12100. glTextureFromLod.isCube = true;
  12101. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  12102. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12103. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12104. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12105. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12106. if (loadData.isDDS) {
  12107. var info = loadData.info;
  12108. var data = loadData.data;
  12109. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12110. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  12111. }
  12112. else {
  12113. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  12114. }
  12115. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12116. // Wrap in a base texture for easy binding.
  12117. var lodTexture = new BABYLON.BaseTexture(scene);
  12118. lodTexture.isCube = true;
  12119. lodTexture._texture = glTextureFromLod;
  12120. glTextureFromLod.isReady = true;
  12121. textures.push(lodTexture);
  12122. }
  12123. texture._lodTextureHigh = textures[2];
  12124. texture._lodTextureMid = textures[1];
  12125. texture._lodTextureLow = textures[0];
  12126. if (onLoad) {
  12127. onLoad(texture);
  12128. }
  12129. };
  12130. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  12131. };
  12132. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  12133. var _this = this;
  12134. if (onLoad === void 0) { onLoad = null; }
  12135. if (onError === void 0) { onError = null; }
  12136. if (forcedExtension === void 0) { forcedExtension = null; }
  12137. var gl = this._gl;
  12138. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  12139. texture.isCube = true;
  12140. texture.url = rootUrl;
  12141. texture.generateMipMaps = !noMipmap;
  12142. if (!this._doNotHandleContextLost) {
  12143. texture._extension = forcedExtension;
  12144. texture._files = files;
  12145. }
  12146. var isKTX = false;
  12147. var isDDS = false;
  12148. var lastDot = rootUrl.lastIndexOf('.');
  12149. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  12150. if (this._textureFormatInUse) {
  12151. extension = this._textureFormatInUse;
  12152. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  12153. isKTX = true;
  12154. }
  12155. else {
  12156. isDDS = (extension === ".dds");
  12157. }
  12158. var onerror = function (request, exception) {
  12159. if (onError && request) {
  12160. onError(request.status + " " + request.statusText, exception);
  12161. }
  12162. };
  12163. if (isKTX) {
  12164. this._loadFile(rootUrl, function (data) {
  12165. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  12166. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  12167. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12168. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  12169. ktx.uploadLevels(_this._gl, !noMipmap);
  12170. _this.setCubeMapTextureParams(gl, loadMipmap);
  12171. texture.width = ktx.pixelWidth;
  12172. texture.height = ktx.pixelHeight;
  12173. texture.isReady = true;
  12174. }, undefined, undefined, true, onerror);
  12175. }
  12176. else if (isDDS) {
  12177. if (files && files.length === 6) {
  12178. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  12179. var info;
  12180. var loadMipmap = false;
  12181. var width = 0;
  12182. for (var index = 0; index < imgs.length; index++) {
  12183. var data = imgs[index];
  12184. info = BABYLON.DDSTools.GetDDSInfo(data);
  12185. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12186. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12187. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12188. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  12189. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12190. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12191. }
  12192. texture.width = info.width;
  12193. texture.height = info.height;
  12194. texture.type = info.textureType;
  12195. width = info.width;
  12196. }
  12197. _this.setCubeMapTextureParams(gl, loadMipmap);
  12198. texture.isReady = true;
  12199. if (onLoad) {
  12200. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  12201. }
  12202. }, files, onError);
  12203. }
  12204. else {
  12205. this._loadFile(rootUrl, function (data) {
  12206. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12207. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12208. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12209. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12210. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  12211. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12212. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12213. }
  12214. _this.setCubeMapTextureParams(gl, loadMipmap);
  12215. texture.width = info.width;
  12216. texture.height = info.height;
  12217. texture.isReady = true;
  12218. texture.type = info.textureType;
  12219. if (onLoad) {
  12220. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  12221. }
  12222. }, undefined, undefined, true, onerror);
  12223. }
  12224. }
  12225. else {
  12226. if (!files) {
  12227. throw new Error("Cannot load cubemap because files were not defined");
  12228. }
  12229. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  12230. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  12231. var height = width;
  12232. _this._prepareWorkingCanvas();
  12233. if (!_this._workingCanvas || !_this._workingContext) {
  12234. return;
  12235. }
  12236. _this._workingCanvas.width = width;
  12237. _this._workingCanvas.height = height;
  12238. var faces = [
  12239. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  12240. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  12241. ];
  12242. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12243. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12244. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  12245. for (var index = 0; index < faces.length; index++) {
  12246. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  12247. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  12248. }
  12249. if (!noMipmap) {
  12250. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12251. }
  12252. _this.setCubeMapTextureParams(gl, !noMipmap);
  12253. texture.width = width;
  12254. texture.height = height;
  12255. texture.isReady = true;
  12256. if (format) {
  12257. texture.format = format;
  12258. }
  12259. texture.onLoadedObservable.notifyObservers(texture);
  12260. texture.onLoadedObservable.clear();
  12261. if (onLoad) {
  12262. onLoad();
  12263. }
  12264. }, files, onError);
  12265. }
  12266. this._internalTexturesCache.push(texture);
  12267. return texture;
  12268. };
  12269. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  12270. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12271. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  12272. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12273. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12274. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12275. // this.resetTextureCache();
  12276. };
  12277. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  12278. if (compression === void 0) { compression = null; }
  12279. if (level === void 0) { level = 0; }
  12280. texture._bufferViewArray = data;
  12281. texture.format = format;
  12282. texture.type = type;
  12283. texture.invertY = invertY;
  12284. texture._compression = compression;
  12285. var gl = this._gl;
  12286. var textureType = this._getWebGLTextureType(type);
  12287. var internalFormat = this._getInternalFormat(format);
  12288. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12289. var needConversion = false;
  12290. if (internalFormat === gl.RGB) {
  12291. internalFormat = gl.RGBA;
  12292. needConversion = true;
  12293. }
  12294. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12295. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12296. if (texture.width % 4 !== 0) {
  12297. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  12298. }
  12299. // Data are known to be in +X +Y +Z -X -Y -Z
  12300. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12301. var faceData = data[faceIndex];
  12302. if (compression) {
  12303. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  12304. }
  12305. else {
  12306. if (needConversion) {
  12307. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  12308. }
  12309. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  12310. }
  12311. }
  12312. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12313. if (isPot && texture.generateMipMaps && level === 0) {
  12314. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12315. }
  12316. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12317. // this.resetTextureCache();
  12318. texture.isReady = true;
  12319. };
  12320. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  12321. if (compression === void 0) { compression = null; }
  12322. var gl = this._gl;
  12323. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  12324. texture.isCube = true;
  12325. texture.generateMipMaps = generateMipMaps;
  12326. texture.format = format;
  12327. texture.type = type;
  12328. if (!this._doNotHandleContextLost) {
  12329. texture._bufferViewArray = data;
  12330. }
  12331. var textureType = this._getWebGLTextureType(type);
  12332. var internalFormat = this._getInternalFormat(format);
  12333. if (internalFormat === gl.RGB) {
  12334. internalFormat = gl.RGBA;
  12335. }
  12336. var width = size;
  12337. var height = width;
  12338. texture.width = width;
  12339. texture.height = height;
  12340. // Double check on POT to generate Mips.
  12341. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12342. if (!isPot) {
  12343. generateMipMaps = false;
  12344. }
  12345. // Upload data if needed. The texture won't be ready until then.
  12346. if (data) {
  12347. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  12348. }
  12349. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12350. // Filters
  12351. if (data && generateMipMaps) {
  12352. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12353. }
  12354. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  12355. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12356. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12357. }
  12358. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  12359. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12360. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12361. }
  12362. else {
  12363. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12364. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12365. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12366. }
  12367. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12368. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12369. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12370. return texture;
  12371. };
  12372. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  12373. var _this = this;
  12374. if (onLoad === void 0) { onLoad = null; }
  12375. if (onError === void 0) { onError = null; }
  12376. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12377. if (invertY === void 0) { invertY = false; }
  12378. var gl = this._gl;
  12379. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  12380. scene._addPendingData(texture);
  12381. texture.url = url;
  12382. this._internalTexturesCache.push(texture);
  12383. var onerror = function (request, exception) {
  12384. scene._removePendingData(texture);
  12385. if (onError && request) {
  12386. onError(request.status + " " + request.statusText, exception);
  12387. }
  12388. };
  12389. var internalCallback = function (data) {
  12390. var width = texture.width;
  12391. var faceDataArrays = callback(data);
  12392. if (!faceDataArrays) {
  12393. return;
  12394. }
  12395. if (mipmmapGenerator) {
  12396. var textureType = _this._getWebGLTextureType(type);
  12397. var internalFormat = _this._getInternalFormat(format);
  12398. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  12399. var needConversion = false;
  12400. if (internalFormat === gl.RGB) {
  12401. internalFormat = gl.RGBA;
  12402. needConversion = true;
  12403. }
  12404. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12405. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12406. var mipData = mipmmapGenerator(faceDataArrays);
  12407. for (var level = 0; level < mipData.length; level++) {
  12408. var mipSize = width >> level;
  12409. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12410. var mipFaceData = mipData[level][faceIndex];
  12411. if (needConversion) {
  12412. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  12413. }
  12414. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  12415. }
  12416. }
  12417. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12418. }
  12419. else {
  12420. texture.generateMipMaps = !noMipmap;
  12421. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  12422. }
  12423. texture.isReady = true;
  12424. // this.resetTextureCache();
  12425. scene._removePendingData(texture);
  12426. if (onLoad) {
  12427. onLoad();
  12428. }
  12429. };
  12430. this._loadFile(url, function (data) {
  12431. internalCallback(data);
  12432. }, undefined, scene.database, true, onerror);
  12433. return texture;
  12434. };
  12435. ;
  12436. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  12437. if (compression === void 0) { compression = null; }
  12438. var internalFormat = this._getInternalFormat(format);
  12439. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12440. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12441. if (!this._doNotHandleContextLost) {
  12442. texture._bufferView = data;
  12443. texture.format = format;
  12444. texture.invertY = invertY;
  12445. texture._compression = compression;
  12446. }
  12447. if (texture.width % 4 !== 0) {
  12448. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12449. }
  12450. if (compression && data) {
  12451. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  12452. }
  12453. else {
  12454. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  12455. }
  12456. if (texture.generateMipMaps) {
  12457. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  12458. }
  12459. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12460. // this.resetTextureCache();
  12461. texture.isReady = true;
  12462. };
  12463. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  12464. if (compression === void 0) { compression = null; }
  12465. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  12466. texture.baseWidth = width;
  12467. texture.baseHeight = height;
  12468. texture.baseDepth = depth;
  12469. texture.width = width;
  12470. texture.height = height;
  12471. texture.depth = depth;
  12472. texture.format = format;
  12473. texture.generateMipMaps = generateMipMaps;
  12474. texture.samplingMode = samplingMode;
  12475. texture.is3D = true;
  12476. if (!this._doNotHandleContextLost) {
  12477. texture._bufferView = data;
  12478. }
  12479. this.updateRawTexture3D(texture, data, format, invertY, compression);
  12480. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12481. // Filters
  12482. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  12483. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12484. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12485. if (generateMipMaps) {
  12486. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  12487. }
  12488. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12489. this._internalTexturesCache.push(texture);
  12490. return texture;
  12491. };
  12492. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  12493. var gl = this._gl;
  12494. if (!gl) {
  12495. return;
  12496. }
  12497. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  12498. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12499. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12500. if (!noMipmap && !isCompressed) {
  12501. gl.generateMipmap(gl.TEXTURE_2D);
  12502. }
  12503. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12504. // this.resetTextureCache();
  12505. if (scene) {
  12506. scene._removePendingData(texture);
  12507. }
  12508. texture.onLoadedObservable.notifyObservers(texture);
  12509. texture.onLoadedObservable.clear();
  12510. };
  12511. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  12512. var _this = this;
  12513. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12514. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  12515. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  12516. var gl = this._gl;
  12517. if (!gl) {
  12518. return;
  12519. }
  12520. if (!texture._webGLTexture) {
  12521. // this.resetTextureCache();
  12522. if (scene) {
  12523. scene._removePendingData(texture);
  12524. }
  12525. return;
  12526. }
  12527. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12528. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12529. texture.baseWidth = width;
  12530. texture.baseHeight = height;
  12531. texture.width = potWidth;
  12532. texture.height = potHeight;
  12533. texture.isReady = true;
  12534. if (processFunction(potWidth, potHeight, function () {
  12535. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  12536. })) {
  12537. // Returning as texture needs extra async steps
  12538. return;
  12539. }
  12540. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  12541. };
  12542. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  12543. // Create new RGBA data container.
  12544. var rgbaData;
  12545. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  12546. rgbaData = new Float32Array(width * height * 4);
  12547. }
  12548. else {
  12549. rgbaData = new Uint32Array(width * height * 4);
  12550. }
  12551. // Convert each pixel.
  12552. for (var x = 0; x < width; x++) {
  12553. for (var y = 0; y < height; y++) {
  12554. var index = (y * width + x) * 3;
  12555. var newIndex = (y * width + x) * 4;
  12556. // Map Old Value to new value.
  12557. rgbaData[newIndex + 0] = rgbData[index + 0];
  12558. rgbaData[newIndex + 1] = rgbData[index + 1];
  12559. rgbaData[newIndex + 2] = rgbData[index + 2];
  12560. // Add fully opaque alpha channel.
  12561. rgbaData[newIndex + 3] = 1;
  12562. }
  12563. }
  12564. return rgbaData;
  12565. };
  12566. Engine.prototype._releaseFramebufferObjects = function (texture) {
  12567. var gl = this._gl;
  12568. if (texture._framebuffer) {
  12569. gl.deleteFramebuffer(texture._framebuffer);
  12570. texture._framebuffer = null;
  12571. }
  12572. if (texture._depthStencilBuffer) {
  12573. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  12574. texture._depthStencilBuffer = null;
  12575. }
  12576. if (texture._MSAAFramebuffer) {
  12577. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  12578. texture._MSAAFramebuffer = null;
  12579. }
  12580. if (texture._MSAARenderBuffer) {
  12581. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  12582. texture._MSAARenderBuffer = null;
  12583. }
  12584. };
  12585. Engine.prototype._releaseTexture = function (texture) {
  12586. var gl = this._gl;
  12587. this._releaseFramebufferObjects(texture);
  12588. gl.deleteTexture(texture._webGLTexture);
  12589. // Unbind channels
  12590. this.unbindAllTextures();
  12591. var index = this._internalTexturesCache.indexOf(texture);
  12592. if (index !== -1) {
  12593. this._internalTexturesCache.splice(index, 1);
  12594. }
  12595. // Integrated fixed lod samplers.
  12596. if (texture._lodTextureHigh) {
  12597. texture._lodTextureHigh.dispose();
  12598. }
  12599. if (texture._lodTextureMid) {
  12600. texture._lodTextureMid.dispose();
  12601. }
  12602. if (texture._lodTextureLow) {
  12603. texture._lodTextureLow.dispose();
  12604. }
  12605. };
  12606. Engine.prototype.setProgram = function (program) {
  12607. if (this._currentProgram !== program) {
  12608. this._gl.useProgram(program);
  12609. this._currentProgram = program;
  12610. }
  12611. };
  12612. Engine.prototype.bindSamplers = function (effect) {
  12613. this.setProgram(effect.getProgram());
  12614. var samplers = effect.getSamplers();
  12615. for (var index = 0; index < samplers.length; index++) {
  12616. var uniform = effect.getUniform(samplers[index]);
  12617. if (uniform) {
  12618. this._boundUniforms[index] = uniform;
  12619. }
  12620. }
  12621. this._currentEffect = null;
  12622. };
  12623. Engine.prototype._activateTextureChannel = function (channel) {
  12624. if (this._activeChannel !== channel && channel > -1) {
  12625. this._gl.activeTexture(this._gl.TEXTURE0 + channel);
  12626. this._activeChannel = channel;
  12627. }
  12628. };
  12629. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  12630. var index = this._boundTexturesStack.indexOf(internalTexture);
  12631. if (index > -1 && index !== this._boundTexturesStack.length - 1) {
  12632. this._boundTexturesStack.splice(index, 1);
  12633. this._boundTexturesStack.push(internalTexture);
  12634. }
  12635. };
  12636. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  12637. var currentSlot = internalTexture._designatedSlot;
  12638. internalTexture._designatedSlot = -1;
  12639. var index = this._boundTexturesStack.indexOf(internalTexture);
  12640. if (index > -1) {
  12641. this._boundTexturesStack.splice(index, 1);
  12642. if (currentSlot > -1) {
  12643. this._boundTexturesCache[currentSlot] = null;
  12644. this._nextFreeTextureSlots.push(currentSlot);
  12645. }
  12646. }
  12647. return currentSlot;
  12648. };
  12649. Engine.prototype._bindTextureDirectly = function (target, texture, doNotBindUniformToTextureChannel) {
  12650. if (doNotBindUniformToTextureChannel === void 0) { doNotBindUniformToTextureChannel = false; }
  12651. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  12652. var isTextureForRendering = texture && texture._initialSlot > -1;
  12653. if (currentTextureBound !== texture) {
  12654. if (currentTextureBound) {
  12655. this._removeDesignatedSlot(currentTextureBound);
  12656. }
  12657. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  12658. if (this._activeChannel >= 0) {
  12659. this._boundTexturesCache[this._activeChannel] = texture;
  12660. if (isTextureForRendering) {
  12661. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  12662. if (slotIndex > -1) {
  12663. this._nextFreeTextureSlots.splice(slotIndex, 1);
  12664. }
  12665. this._boundTexturesStack.push(texture);
  12666. }
  12667. }
  12668. }
  12669. if (isTextureForRendering && this._activeChannel > -1) {
  12670. texture._designatedSlot = this._activeChannel;
  12671. if (!doNotBindUniformToTextureChannel) {
  12672. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  12673. }
  12674. }
  12675. };
  12676. Engine.prototype._bindTexture = function (channel, texture) {
  12677. if (channel < 0) {
  12678. return;
  12679. }
  12680. if (texture) {
  12681. channel = this._getCorrectTextureChannel(channel, texture);
  12682. }
  12683. this._activateTextureChannel(channel);
  12684. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  12685. };
  12686. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  12687. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  12688. };
  12689. Engine.prototype.unbindAllTextures = function () {
  12690. for (var channel = 0; channel < this._caps.maxCombinedTexturesImageUnits; channel++) {
  12691. this._activateTextureChannel(channel);
  12692. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12693. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12694. if (this.webGLVersion > 1) {
  12695. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12696. }
  12697. }
  12698. };
  12699. Engine.prototype.setTexture = function (channel, uniform, texture) {
  12700. if (channel < 0) {
  12701. return;
  12702. }
  12703. if (uniform) {
  12704. this._boundUniforms[channel] = uniform;
  12705. }
  12706. this._setTexture(channel, texture);
  12707. };
  12708. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  12709. if (!internalTexture) {
  12710. return -1;
  12711. }
  12712. internalTexture._initialSlot = channel;
  12713. if (channel !== internalTexture._designatedSlot) {
  12714. if (internalTexture._designatedSlot > -1) {
  12715. return internalTexture._designatedSlot;
  12716. }
  12717. else {
  12718. // No slot for this texture, let's pick a new one (if we find a free slot)
  12719. if (this._nextFreeTextureSlots.length) {
  12720. return this._nextFreeTextureSlots[0];
  12721. }
  12722. // We need to recycle the oldest bound texture, sorry.
  12723. this._textureCollisions.addCount(1, false);
  12724. return this._removeDesignatedSlot(this._boundTexturesStack[0]);
  12725. }
  12726. }
  12727. return channel;
  12728. };
  12729. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  12730. var uniform = this._boundUniforms[sourceSlot];
  12731. this._gl.uniform1i(uniform, destination);
  12732. };
  12733. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  12734. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  12735. // Not ready?
  12736. if (!texture) {
  12737. if (this._boundTexturesCache[channel] != null) {
  12738. this._activateTextureChannel(channel);
  12739. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12740. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12741. if (this.webGLVersion > 1) {
  12742. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12743. }
  12744. }
  12745. return false;
  12746. }
  12747. // Video
  12748. var alreadyActivated = false;
  12749. if (texture.video) {
  12750. this._activateTextureChannel(channel);
  12751. alreadyActivated = true;
  12752. texture.update();
  12753. }
  12754. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  12755. texture.delayLoad();
  12756. return false;
  12757. }
  12758. var internalTexture;
  12759. if (texture.isReady()) {
  12760. internalTexture = texture.getInternalTexture();
  12761. }
  12762. else if (texture.isCube) {
  12763. internalTexture = this.emptyCubeTexture;
  12764. }
  12765. else if (texture.is3D) {
  12766. internalTexture = this.emptyTexture3D;
  12767. }
  12768. else {
  12769. internalTexture = this.emptyTexture;
  12770. }
  12771. if (!isPartOfTextureArray) {
  12772. channel = this._getCorrectTextureChannel(channel, internalTexture);
  12773. }
  12774. if (this._boundTexturesCache[channel] === internalTexture) {
  12775. this._moveBoundTextureOnTop(internalTexture);
  12776. if (!isPartOfTextureArray) {
  12777. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  12778. }
  12779. return false;
  12780. }
  12781. if (!alreadyActivated) {
  12782. this._activateTextureChannel(channel);
  12783. }
  12784. if (internalTexture && internalTexture.is3D) {
  12785. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  12786. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  12787. internalTexture._cachedWrapU = texture.wrapU;
  12788. switch (texture.wrapU) {
  12789. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12790. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  12791. break;
  12792. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12793. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  12794. break;
  12795. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12796. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  12797. break;
  12798. }
  12799. }
  12800. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  12801. internalTexture._cachedWrapV = texture.wrapV;
  12802. switch (texture.wrapV) {
  12803. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12804. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  12805. break;
  12806. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12807. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  12808. break;
  12809. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12810. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  12811. break;
  12812. }
  12813. }
  12814. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  12815. internalTexture._cachedWrapR = texture.wrapR;
  12816. switch (texture.wrapV) {
  12817. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12818. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  12819. break;
  12820. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12821. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  12822. break;
  12823. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12824. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  12825. break;
  12826. }
  12827. }
  12828. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  12829. }
  12830. else if (internalTexture && internalTexture.isCube) {
  12831. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  12832. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  12833. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  12834. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  12835. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  12836. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  12837. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  12838. }
  12839. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  12840. }
  12841. else {
  12842. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  12843. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  12844. internalTexture._cachedWrapU = texture.wrapU;
  12845. switch (texture.wrapU) {
  12846. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12847. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  12848. break;
  12849. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12850. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  12851. break;
  12852. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12853. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  12854. break;
  12855. }
  12856. }
  12857. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  12858. internalTexture._cachedWrapV = texture.wrapV;
  12859. switch (texture.wrapV) {
  12860. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12861. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  12862. break;
  12863. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12864. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  12865. break;
  12866. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12867. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  12868. break;
  12869. }
  12870. }
  12871. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  12872. }
  12873. return true;
  12874. };
  12875. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  12876. if (channel < 0 || !uniform) {
  12877. return;
  12878. }
  12879. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  12880. this._textureUnits = new Int32Array(textures.length);
  12881. }
  12882. for (var i = 0; i < textures.length; i++) {
  12883. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  12884. }
  12885. this._gl.uniform1iv(uniform, this._textureUnits);
  12886. for (var index = 0; index < textures.length; index++) {
  12887. this._setTexture(this._textureUnits[index], textures[index], true);
  12888. }
  12889. };
  12890. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  12891. var internalTexture = texture.getInternalTexture();
  12892. if (!internalTexture) {
  12893. return;
  12894. }
  12895. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  12896. var value = texture.anisotropicFilteringLevel;
  12897. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  12898. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  12899. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  12900. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  12901. }
  12902. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  12903. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  12904. internalTexture._cachedAnisotropicFilteringLevel = value;
  12905. }
  12906. };
  12907. Engine.prototype.readPixels = function (x, y, width, height) {
  12908. var data = new Uint8Array(height * width * 4);
  12909. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  12910. return data;
  12911. };
  12912. /**
  12913. * Add an externaly attached data from its key.
  12914. * This method call will fail and return false, if such key already exists.
  12915. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  12916. * @param key the unique key that identifies the data
  12917. * @param data the data object to associate to the key for this Engine instance
  12918. * @return true if no such key were already present and the data was added successfully, false otherwise
  12919. */
  12920. Engine.prototype.addExternalData = function (key, data) {
  12921. if (!this._externalData) {
  12922. this._externalData = new BABYLON.StringDictionary();
  12923. }
  12924. return this._externalData.add(key, data);
  12925. };
  12926. /**
  12927. * Get an externaly attached data from its key
  12928. * @param key the unique key that identifies the data
  12929. * @return the associated data, if present (can be null), or undefined if not present
  12930. */
  12931. Engine.prototype.getExternalData = function (key) {
  12932. if (!this._externalData) {
  12933. this._externalData = new BABYLON.StringDictionary();
  12934. }
  12935. return this._externalData.get(key);
  12936. };
  12937. /**
  12938. * Get an externaly attached data from its key, create it using a factory if it's not already present
  12939. * @param key the unique key that identifies the data
  12940. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  12941. * @return the associated data, can be null if the factory returned null.
  12942. */
  12943. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  12944. if (!this._externalData) {
  12945. this._externalData = new BABYLON.StringDictionary();
  12946. }
  12947. return this._externalData.getOrAddWithFactory(key, factory);
  12948. };
  12949. /**
  12950. * Remove an externaly attached data from the Engine instance
  12951. * @param key the unique key that identifies the data
  12952. * @return true if the data was successfully removed, false if it doesn't exist
  12953. */
  12954. Engine.prototype.removeExternalData = function (key) {
  12955. if (!this._externalData) {
  12956. this._externalData = new BABYLON.StringDictionary();
  12957. }
  12958. return this._externalData.remove(key);
  12959. };
  12960. Engine.prototype.unbindAllAttributes = function () {
  12961. if (this._mustWipeVertexAttributes) {
  12962. this._mustWipeVertexAttributes = false;
  12963. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  12964. this._gl.disableVertexAttribArray(i);
  12965. this._vertexAttribArraysEnabled[i] = false;
  12966. this._currentBufferPointers[i].active = false;
  12967. }
  12968. return;
  12969. }
  12970. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  12971. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  12972. continue;
  12973. }
  12974. this._gl.disableVertexAttribArray(i);
  12975. this._vertexAttribArraysEnabled[i] = false;
  12976. this._currentBufferPointers[i].active = false;
  12977. }
  12978. };
  12979. Engine.prototype.releaseEffects = function () {
  12980. for (var name in this._compiledEffects) {
  12981. this._deleteProgram(this._compiledEffects[name]._program);
  12982. }
  12983. this._compiledEffects = {};
  12984. };
  12985. // Dispose
  12986. Engine.prototype.dispose = function () {
  12987. this.hideLoadingUI();
  12988. this.stopRenderLoop();
  12989. // Release postProcesses
  12990. while (this.postProcesses.length) {
  12991. this.postProcesses[0].dispose();
  12992. }
  12993. // Empty texture
  12994. if (this._emptyTexture) {
  12995. this._releaseTexture(this._emptyTexture);
  12996. this._emptyTexture = null;
  12997. }
  12998. if (this._emptyCubeTexture) {
  12999. this._releaseTexture(this._emptyCubeTexture);
  13000. this._emptyCubeTexture = null;
  13001. }
  13002. // Rescale PP
  13003. if (this._rescalePostProcess) {
  13004. this._rescalePostProcess.dispose();
  13005. }
  13006. // Release scenes
  13007. while (this.scenes.length) {
  13008. this.scenes[0].dispose();
  13009. }
  13010. // Release audio engine
  13011. if (Engine.audioEngine) {
  13012. Engine.audioEngine.dispose();
  13013. }
  13014. // Release effects
  13015. this.releaseEffects();
  13016. // Unbind
  13017. this.unbindAllAttributes();
  13018. if (this._dummyFramebuffer) {
  13019. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  13020. }
  13021. //WebVR
  13022. this.disableVR();
  13023. // Events
  13024. if (BABYLON.Tools.IsWindowObjectExist()) {
  13025. window.removeEventListener("blur", this._onBlur);
  13026. window.removeEventListener("focus", this._onFocus);
  13027. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  13028. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  13029. if (this._renderingCanvas) {
  13030. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  13031. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  13032. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  13033. if (!this._doNotHandleContextLost) {
  13034. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  13035. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  13036. }
  13037. }
  13038. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  13039. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  13040. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  13041. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  13042. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  13043. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  13044. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  13045. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  13046. if (this._onVrDisplayConnect) {
  13047. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13048. if (this._onVrDisplayDisconnect) {
  13049. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13050. }
  13051. if (this._onVrDisplayPresentChange) {
  13052. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13053. }
  13054. this._onVrDisplayConnect = null;
  13055. this._onVrDisplayDisconnect = null;
  13056. }
  13057. }
  13058. // Remove from Instances
  13059. var index = Engine.Instances.indexOf(this);
  13060. if (index >= 0) {
  13061. Engine.Instances.splice(index, 1);
  13062. }
  13063. this._workingCanvas = null;
  13064. this._workingContext = null;
  13065. this._currentBufferPointers = [];
  13066. this._renderingCanvas = null;
  13067. this._currentProgram = null;
  13068. this.onResizeObservable.clear();
  13069. this.onCanvasBlurObservable.clear();
  13070. this.onCanvasFocusObservable.clear();
  13071. this.onCanvasPointerOutObservable.clear();
  13072. this.onBeginFrameObservable.clear();
  13073. this.onEndFrameObservable.clear();
  13074. BABYLON.Effect.ResetCache();
  13075. // Abort active requests
  13076. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  13077. var request = _a[_i];
  13078. request.abort();
  13079. }
  13080. };
  13081. // Loading screen
  13082. Engine.prototype.displayLoadingUI = function () {
  13083. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13084. return;
  13085. }
  13086. var loadingScreen = this.loadingScreen;
  13087. if (loadingScreen) {
  13088. loadingScreen.displayLoadingUI();
  13089. }
  13090. };
  13091. Engine.prototype.hideLoadingUI = function () {
  13092. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13093. return;
  13094. }
  13095. var loadingScreen = this.loadingScreen;
  13096. if (loadingScreen) {
  13097. loadingScreen.hideLoadingUI();
  13098. }
  13099. };
  13100. Object.defineProperty(Engine.prototype, "loadingScreen", {
  13101. get: function () {
  13102. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  13103. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  13104. return this._loadingScreen;
  13105. },
  13106. set: function (loadingScreen) {
  13107. this._loadingScreen = loadingScreen;
  13108. },
  13109. enumerable: true,
  13110. configurable: true
  13111. });
  13112. Object.defineProperty(Engine.prototype, "loadingUIText", {
  13113. set: function (text) {
  13114. this.loadingScreen.loadingUIText = text;
  13115. },
  13116. enumerable: true,
  13117. configurable: true
  13118. });
  13119. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  13120. set: function (color) {
  13121. this.loadingScreen.loadingUIBackgroundColor = color;
  13122. },
  13123. enumerable: true,
  13124. configurable: true
  13125. });
  13126. Engine.prototype.attachContextLostEvent = function (callback) {
  13127. if (this._renderingCanvas) {
  13128. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  13129. }
  13130. };
  13131. Engine.prototype.attachContextRestoredEvent = function (callback) {
  13132. if (this._renderingCanvas) {
  13133. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  13134. }
  13135. };
  13136. Engine.prototype.getVertexShaderSource = function (program) {
  13137. var shaders = this._gl.getAttachedShaders(program);
  13138. if (!shaders) {
  13139. return null;
  13140. }
  13141. return this._gl.getShaderSource(shaders[0]);
  13142. };
  13143. Engine.prototype.getFragmentShaderSource = function (program) {
  13144. var shaders = this._gl.getAttachedShaders(program);
  13145. if (!shaders) {
  13146. return null;
  13147. }
  13148. return this._gl.getShaderSource(shaders[1]);
  13149. };
  13150. Engine.prototype.getError = function () {
  13151. return this._gl.getError();
  13152. };
  13153. // FPS
  13154. Engine.prototype.getFps = function () {
  13155. return this._fps;
  13156. };
  13157. Engine.prototype.getDeltaTime = function () {
  13158. return this._deltaTime;
  13159. };
  13160. Engine.prototype._measureFps = function () {
  13161. this._performanceMonitor.sampleFrame();
  13162. this._fps = this._performanceMonitor.averageFPS;
  13163. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  13164. };
  13165. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  13166. if (faceIndex === void 0) { faceIndex = -1; }
  13167. var gl = this._gl;
  13168. if (!this._dummyFramebuffer) {
  13169. var dummy = gl.createFramebuffer();
  13170. if (!dummy) {
  13171. throw new Error("Unable to create dummy framebuffer");
  13172. }
  13173. this._dummyFramebuffer = dummy;
  13174. }
  13175. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  13176. if (faceIndex > -1) {
  13177. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13178. }
  13179. else {
  13180. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13181. }
  13182. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  13183. var buffer;
  13184. switch (readType) {
  13185. case gl.UNSIGNED_BYTE:
  13186. buffer = new Uint8Array(4 * width * height);
  13187. readType = gl.UNSIGNED_BYTE;
  13188. break;
  13189. default:
  13190. buffer = new Float32Array(4 * width * height);
  13191. readType = gl.FLOAT;
  13192. break;
  13193. }
  13194. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  13195. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  13196. return buffer;
  13197. };
  13198. Engine.prototype._canRenderToFloatFramebuffer = function () {
  13199. if (this._webGLVersion > 1) {
  13200. return this._caps.colorBufferFloat;
  13201. }
  13202. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  13203. };
  13204. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  13205. if (this._webGLVersion > 1) {
  13206. return this._caps.colorBufferFloat;
  13207. }
  13208. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  13209. };
  13210. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  13211. Engine.prototype._canRenderToFramebuffer = function (type) {
  13212. var gl = this._gl;
  13213. //clear existing errors
  13214. while (gl.getError() !== gl.NO_ERROR) { }
  13215. var successful = true;
  13216. var texture = gl.createTexture();
  13217. gl.bindTexture(gl.TEXTURE_2D, texture);
  13218. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13219. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13220. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13221. var fb = gl.createFramebuffer();
  13222. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  13223. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  13224. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  13225. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  13226. successful = successful && (gl.getError() === gl.NO_ERROR);
  13227. //try render by clearing frame buffer's color buffer
  13228. if (successful) {
  13229. gl.clear(gl.COLOR_BUFFER_BIT);
  13230. successful = successful && (gl.getError() === gl.NO_ERROR);
  13231. }
  13232. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  13233. if (successful) {
  13234. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  13235. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13236. var readFormat = gl.RGBA;
  13237. var readType = gl.UNSIGNED_BYTE;
  13238. var buffer = new Uint8Array(4);
  13239. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  13240. successful = successful && (gl.getError() === gl.NO_ERROR);
  13241. }
  13242. //clean up
  13243. gl.deleteTexture(texture);
  13244. gl.deleteFramebuffer(fb);
  13245. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13246. //clear accumulated errors
  13247. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  13248. return successful;
  13249. };
  13250. Engine.prototype._getWebGLTextureType = function (type) {
  13251. if (type === Engine.TEXTURETYPE_FLOAT) {
  13252. return this._gl.FLOAT;
  13253. }
  13254. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13255. // Add Half Float Constant.
  13256. return this._gl.HALF_FLOAT_OES;
  13257. }
  13258. return this._gl.UNSIGNED_BYTE;
  13259. };
  13260. ;
  13261. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  13262. if (this._webGLVersion === 1) {
  13263. return this._gl.RGBA;
  13264. }
  13265. if (type === Engine.TEXTURETYPE_FLOAT) {
  13266. return this._gl.RGBA32F;
  13267. }
  13268. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13269. return this._gl.RGBA16F;
  13270. }
  13271. return this._gl.RGBA;
  13272. };
  13273. ;
  13274. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  13275. if (type === Engine.TEXTURETYPE_FLOAT) {
  13276. return this._gl.RGBA32F;
  13277. }
  13278. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13279. return this._gl.RGBA16F;
  13280. }
  13281. return this._gl.RGBA8;
  13282. };
  13283. ;
  13284. Engine.prototype.createQuery = function () {
  13285. return this._gl.createQuery();
  13286. };
  13287. Engine.prototype.deleteQuery = function (query) {
  13288. this._gl.deleteQuery(query);
  13289. return this;
  13290. };
  13291. Engine.prototype.isQueryResultAvailable = function (query) {
  13292. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  13293. };
  13294. Engine.prototype.getQueryResult = function (query) {
  13295. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  13296. };
  13297. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  13298. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13299. this._gl.beginQuery(glAlgorithm, query);
  13300. return this;
  13301. };
  13302. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  13303. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13304. this._gl.endQuery(glAlgorithm);
  13305. return this;
  13306. };
  13307. /* Time queries */
  13308. Engine.prototype._createTimeQuery = function () {
  13309. var timerQuery = this._caps.timerQuery;
  13310. if (timerQuery.createQueryEXT) {
  13311. return timerQuery.createQueryEXT();
  13312. }
  13313. return this.createQuery();
  13314. };
  13315. Engine.prototype._deleteTimeQuery = function (query) {
  13316. var timerQuery = this._caps.timerQuery;
  13317. if (timerQuery.deleteQueryEXT) {
  13318. timerQuery.deleteQueryEXT(query);
  13319. return;
  13320. }
  13321. this.deleteQuery(query);
  13322. };
  13323. Engine.prototype._getTimeQueryResult = function (query) {
  13324. var timerQuery = this._caps.timerQuery;
  13325. if (timerQuery.getQueryObjectEXT) {
  13326. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  13327. }
  13328. return this.getQueryResult(query);
  13329. };
  13330. Engine.prototype._getTimeQueryAvailability = function (query) {
  13331. var timerQuery = this._caps.timerQuery;
  13332. if (timerQuery.getQueryObjectEXT) {
  13333. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  13334. }
  13335. return this.isQueryResultAvailable(query);
  13336. };
  13337. Engine.prototype.startTimeQuery = function () {
  13338. var timerQuery = this._caps.timerQuery;
  13339. if (!timerQuery) {
  13340. return null;
  13341. }
  13342. var token = new BABYLON._TimeToken();
  13343. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13344. if (this._caps.canUseTimestampForTimerQuery) {
  13345. token._startTimeQuery = this._createTimeQuery();
  13346. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  13347. }
  13348. else {
  13349. if (this._currentNonTimestampToken) {
  13350. return this._currentNonTimestampToken;
  13351. }
  13352. token._timeElapsedQuery = this._createTimeQuery();
  13353. if (timerQuery.beginQueryEXT) {
  13354. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13355. }
  13356. else {
  13357. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13358. }
  13359. this._currentNonTimestampToken = token;
  13360. }
  13361. return token;
  13362. };
  13363. Engine.prototype.endTimeQuery = function (token) {
  13364. var timerQuery = this._caps.timerQuery;
  13365. if (!timerQuery || !token) {
  13366. return -1;
  13367. }
  13368. if (this._caps.canUseTimestampForTimerQuery) {
  13369. if (!token._startTimeQuery) {
  13370. return -1;
  13371. }
  13372. if (!token._endTimeQuery) {
  13373. token._endTimeQuery = this._createTimeQuery();
  13374. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  13375. }
  13376. }
  13377. else if (!token._timeElapsedQueryEnded) {
  13378. if (!token._timeElapsedQuery) {
  13379. return -1;
  13380. }
  13381. if (timerQuery.endQueryEXT) {
  13382. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  13383. }
  13384. else {
  13385. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  13386. }
  13387. token._timeElapsedQueryEnded = true;
  13388. }
  13389. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13390. var available = false;
  13391. if (token._endTimeQuery) {
  13392. available = this._getTimeQueryAvailability(token._endTimeQuery);
  13393. }
  13394. else if (token._timeElapsedQuery) {
  13395. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  13396. }
  13397. if (available && !disjoint) {
  13398. var result = 0;
  13399. if (this._caps.canUseTimestampForTimerQuery) {
  13400. if (!token._startTimeQuery || !token._endTimeQuery) {
  13401. return -1;
  13402. }
  13403. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  13404. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  13405. result = timeEnd - timeStart;
  13406. this._deleteTimeQuery(token._startTimeQuery);
  13407. this._deleteTimeQuery(token._endTimeQuery);
  13408. token._startTimeQuery = null;
  13409. token._endTimeQuery = null;
  13410. }
  13411. else {
  13412. if (!token._timeElapsedQuery) {
  13413. return -1;
  13414. }
  13415. result = this._getTimeQueryResult(token._timeElapsedQuery);
  13416. this._deleteTimeQuery(token._timeElapsedQuery);
  13417. token._timeElapsedQuery = null;
  13418. token._timeElapsedQueryEnded = false;
  13419. this._currentNonTimestampToken = null;
  13420. }
  13421. return result;
  13422. }
  13423. return -1;
  13424. };
  13425. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  13426. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  13427. };
  13428. // Transform feedback
  13429. Engine.prototype.createTransformFeedback = function () {
  13430. return this._gl.createTransformFeedback();
  13431. };
  13432. Engine.prototype.deleteTransformFeedback = function (value) {
  13433. this._gl.deleteTransformFeedback(value);
  13434. };
  13435. Engine.prototype.bindTransformFeedback = function (value) {
  13436. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  13437. };
  13438. Engine.prototype.beginTransformFeedback = function (usePoints) {
  13439. if (usePoints === void 0) { usePoints = true; }
  13440. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  13441. };
  13442. Engine.prototype.endTransformFeedback = function () {
  13443. this._gl.endTransformFeedback();
  13444. };
  13445. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  13446. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  13447. };
  13448. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  13449. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  13450. };
  13451. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  13452. var _this = this;
  13453. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  13454. this._activeRequests.push(request);
  13455. request.onCompleteObservable.add(function (request) {
  13456. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  13457. });
  13458. return request;
  13459. };
  13460. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  13461. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  13462. var onload = function (data) {
  13463. loadedFiles[index] = data;
  13464. loadedFiles._internalCount++;
  13465. if (loadedFiles._internalCount === 6) {
  13466. onfinish(loadedFiles);
  13467. }
  13468. };
  13469. var onerror = function (request, exception) {
  13470. if (onErrorCallBack && request) {
  13471. onErrorCallBack(request.status + " " + request.statusText, exception);
  13472. }
  13473. };
  13474. this._loadFile(url, onload, undefined, undefined, true, onerror);
  13475. };
  13476. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  13477. if (onError === void 0) { onError = null; }
  13478. var loadedFiles = [];
  13479. loadedFiles._internalCount = 0;
  13480. for (var index = 0; index < 6; index++) {
  13481. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  13482. }
  13483. };
  13484. // Statics
  13485. Engine.isSupported = function () {
  13486. try {
  13487. var tempcanvas = document.createElement("canvas");
  13488. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  13489. return gl != null && !!window.WebGLRenderingContext;
  13490. }
  13491. catch (e) {
  13492. return false;
  13493. }
  13494. };
  13495. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  13496. Engine.ExceptionList = [
  13497. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  13498. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] }
  13499. ];
  13500. Engine.Instances = new Array();
  13501. // Const statics
  13502. Engine._ALPHA_DISABLE = 0;
  13503. Engine._ALPHA_ADD = 1;
  13504. Engine._ALPHA_COMBINE = 2;
  13505. Engine._ALPHA_SUBTRACT = 3;
  13506. Engine._ALPHA_MULTIPLY = 4;
  13507. Engine._ALPHA_MAXIMIZED = 5;
  13508. Engine._ALPHA_ONEONE = 6;
  13509. Engine._ALPHA_PREMULTIPLIED = 7;
  13510. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  13511. Engine._ALPHA_INTERPOLATE = 9;
  13512. Engine._ALPHA_SCREENMODE = 10;
  13513. Engine._DELAYLOADSTATE_NONE = 0;
  13514. Engine._DELAYLOADSTATE_LOADED = 1;
  13515. Engine._DELAYLOADSTATE_LOADING = 2;
  13516. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  13517. Engine._TEXTUREFORMAT_ALPHA = 0;
  13518. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  13519. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  13520. Engine._TEXTUREFORMAT_RGB = 4;
  13521. Engine._TEXTUREFORMAT_RGBA = 5;
  13522. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  13523. Engine._TEXTURETYPE_FLOAT = 1;
  13524. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  13525. // Depht or Stencil test Constants.
  13526. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  13527. 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.
  13528. 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.
  13529. 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.
  13530. 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.
  13531. 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.
  13532. 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.
  13533. 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.
  13534. // Stencil Actions Constants.
  13535. Engine._KEEP = 0x1E00;
  13536. Engine._REPLACE = 0x1E01;
  13537. Engine._INCR = 0x1E02;
  13538. Engine._DECR = 0x1E03;
  13539. Engine._INVERT = 0x150A;
  13540. Engine._INCR_WRAP = 0x8507;
  13541. Engine._DECR_WRAP = 0x8508;
  13542. // Texture rescaling mode
  13543. Engine._SCALEMODE_FLOOR = 1;
  13544. Engine._SCALEMODE_NEAREST = 2;
  13545. Engine._SCALEMODE_CEILING = 3;
  13546. // Updatable statics so stick with vars here
  13547. Engine.CollisionsEpsilon = 0.001;
  13548. Engine.CodeRepository = "src/";
  13549. Engine.ShadersRepository = "src/Shaders/";
  13550. return Engine;
  13551. }());
  13552. BABYLON.Engine = Engine;
  13553. })(BABYLON || (BABYLON = {}));
  13554. //# sourceMappingURL=babylon.engine.js.map
  13555. var BABYLON;
  13556. (function (BABYLON) {
  13557. /**
  13558. * Node is the basic class for all scene objects (Mesh, Light Camera).
  13559. */
  13560. var Node = /** @class */ (function () {
  13561. /**
  13562. * @constructor
  13563. * @param {string} name - the name and id to be given to this node
  13564. * @param {BABYLON.Scene} the scene this node will be added to
  13565. */
  13566. function Node(name, scene) {
  13567. if (scene === void 0) { scene = null; }
  13568. this.state = "";
  13569. this.metadata = null;
  13570. this.doNotSerialize = false;
  13571. this.animations = new Array();
  13572. this._ranges = {};
  13573. this._isEnabled = true;
  13574. this._isReady = true;
  13575. this._currentRenderId = -1;
  13576. this._parentRenderId = -1;
  13577. /**
  13578. * An event triggered when the mesh is disposed.
  13579. * @type {BABYLON.Observable}
  13580. */
  13581. this.onDisposeObservable = new BABYLON.Observable();
  13582. // Behaviors
  13583. this._behaviors = new Array();
  13584. this.name = name;
  13585. this.id = name;
  13586. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  13587. this.uniqueId = this._scene.getUniqueId();
  13588. this._initCache();
  13589. }
  13590. Object.defineProperty(Node.prototype, "parent", {
  13591. get: function () {
  13592. return this._parentNode;
  13593. },
  13594. set: function (parent) {
  13595. if (this._parentNode === parent) {
  13596. return;
  13597. }
  13598. // Remove self from list of children of parent
  13599. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  13600. var index = this._parentNode._children.indexOf(this);
  13601. if (index !== -1) {
  13602. this._parentNode._children.splice(index, 1);
  13603. }
  13604. }
  13605. // Store new parent
  13606. this._parentNode = parent;
  13607. // Add as child to new parent
  13608. if (this._parentNode) {
  13609. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  13610. this._parentNode._children = new Array();
  13611. }
  13612. this._parentNode._children.push(this);
  13613. }
  13614. },
  13615. enumerable: true,
  13616. configurable: true
  13617. });
  13618. Node.prototype.getClassName = function () {
  13619. return "Node";
  13620. };
  13621. Object.defineProperty(Node.prototype, "onDispose", {
  13622. set: function (callback) {
  13623. if (this._onDisposeObserver) {
  13624. this.onDisposeObservable.remove(this._onDisposeObserver);
  13625. }
  13626. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  13627. },
  13628. enumerable: true,
  13629. configurable: true
  13630. });
  13631. Node.prototype.getScene = function () {
  13632. return this._scene;
  13633. };
  13634. Node.prototype.getEngine = function () {
  13635. return this._scene.getEngine();
  13636. };
  13637. Node.prototype.addBehavior = function (behavior) {
  13638. var _this = this;
  13639. var index = this._behaviors.indexOf(behavior);
  13640. if (index !== -1) {
  13641. return this;
  13642. }
  13643. behavior.init();
  13644. if (this._scene.isLoading) {
  13645. // We defer the attach when the scene will be loaded
  13646. var observer = this._scene.onDataLoadedObservable.add(function () {
  13647. behavior.attach(_this);
  13648. setTimeout(function () {
  13649. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  13650. _this._scene.onDataLoadedObservable.remove(observer);
  13651. }, 0);
  13652. });
  13653. }
  13654. else {
  13655. behavior.attach(this);
  13656. }
  13657. this._behaviors.push(behavior);
  13658. return this;
  13659. };
  13660. Node.prototype.removeBehavior = function (behavior) {
  13661. var index = this._behaviors.indexOf(behavior);
  13662. if (index === -1) {
  13663. return this;
  13664. }
  13665. this._behaviors[index].detach();
  13666. this._behaviors.splice(index, 1);
  13667. return this;
  13668. };
  13669. Object.defineProperty(Node.prototype, "behaviors", {
  13670. get: function () {
  13671. return this._behaviors;
  13672. },
  13673. enumerable: true,
  13674. configurable: true
  13675. });
  13676. Node.prototype.getBehaviorByName = function (name) {
  13677. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  13678. var behavior = _a[_i];
  13679. if (behavior.name === name) {
  13680. return behavior;
  13681. }
  13682. }
  13683. return null;
  13684. };
  13685. // override it in derived class
  13686. Node.prototype.getWorldMatrix = function () {
  13687. return BABYLON.Matrix.Identity();
  13688. };
  13689. // override it in derived class if you add new variables to the cache
  13690. // and call the parent class method
  13691. Node.prototype._initCache = function () {
  13692. this._cache = {};
  13693. this._cache.parent = undefined;
  13694. };
  13695. Node.prototype.updateCache = function (force) {
  13696. if (!force && this.isSynchronized())
  13697. return;
  13698. this._cache.parent = this.parent;
  13699. this._updateCache();
  13700. };
  13701. // override it in derived class if you add new variables to the cache
  13702. // and call the parent class method if !ignoreParentClass
  13703. Node.prototype._updateCache = function (ignoreParentClass) {
  13704. };
  13705. // override it in derived class if you add new variables to the cache
  13706. Node.prototype._isSynchronized = function () {
  13707. return true;
  13708. };
  13709. Node.prototype._markSyncedWithParent = function () {
  13710. if (this.parent) {
  13711. this._parentRenderId = this.parent._currentRenderId;
  13712. }
  13713. };
  13714. Node.prototype.isSynchronizedWithParent = function () {
  13715. if (!this.parent) {
  13716. return true;
  13717. }
  13718. if (this._parentRenderId !== this.parent._currentRenderId) {
  13719. return false;
  13720. }
  13721. return this.parent.isSynchronized();
  13722. };
  13723. Node.prototype.isSynchronized = function (updateCache) {
  13724. var check = this.hasNewParent();
  13725. check = check || !this.isSynchronizedWithParent();
  13726. check = check || !this._isSynchronized();
  13727. if (updateCache)
  13728. this.updateCache(true);
  13729. return !check;
  13730. };
  13731. Node.prototype.hasNewParent = function (update) {
  13732. if (this._cache.parent === this.parent)
  13733. return false;
  13734. if (update)
  13735. this._cache.parent = this.parent;
  13736. return true;
  13737. };
  13738. /**
  13739. * Is this node ready to be used/rendered
  13740. * @return {boolean} is it ready
  13741. */
  13742. Node.prototype.isReady = function () {
  13743. return this._isReady;
  13744. };
  13745. /**
  13746. * Is this node enabled.
  13747. * 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.
  13748. * @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.
  13749. * @return {boolean} whether this node (and its parent) is enabled.
  13750. * @see setEnabled
  13751. */
  13752. Node.prototype.isEnabled = function (checkAncestors) {
  13753. if (checkAncestors === void 0) { checkAncestors = true; }
  13754. if (checkAncestors === false) {
  13755. return this._isEnabled;
  13756. }
  13757. if (this._isEnabled === false) {
  13758. return false;
  13759. }
  13760. if (this.parent !== undefined && this.parent !== null) {
  13761. return this.parent.isEnabled(checkAncestors);
  13762. }
  13763. return true;
  13764. };
  13765. /**
  13766. * Set the enabled state of this node.
  13767. * @param {boolean} value - the new enabled state
  13768. * @see isEnabled
  13769. */
  13770. Node.prototype.setEnabled = function (value) {
  13771. this._isEnabled = value;
  13772. };
  13773. /**
  13774. * Is this node a descendant of the given node.
  13775. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  13776. * @param {BABYLON.Node} ancestor - The parent node to inspect
  13777. * @see parent
  13778. */
  13779. Node.prototype.isDescendantOf = function (ancestor) {
  13780. if (this.parent) {
  13781. if (this.parent === ancestor) {
  13782. return true;
  13783. }
  13784. return this.parent.isDescendantOf(ancestor);
  13785. }
  13786. return false;
  13787. };
  13788. /**
  13789. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  13790. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  13791. * @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.
  13792. * @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.
  13793. */
  13794. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  13795. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  13796. if (!this._children) {
  13797. return;
  13798. }
  13799. for (var index = 0; index < this._children.length; index++) {
  13800. var item = this._children[index];
  13801. if (!predicate || predicate(item)) {
  13802. results.push(item);
  13803. }
  13804. if (!directDescendantsOnly) {
  13805. item._getDescendants(results, false, predicate);
  13806. }
  13807. }
  13808. };
  13809. /**
  13810. * Will return all nodes that have this node as ascendant.
  13811. * @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.
  13812. * @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.
  13813. * @return {BABYLON.Node[]} all children nodes of all types.
  13814. */
  13815. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  13816. var results = new Array();
  13817. this._getDescendants(results, directDescendantsOnly, predicate);
  13818. return results;
  13819. };
  13820. /**
  13821. * Get all child-meshes of this node.
  13822. */
  13823. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  13824. var results = [];
  13825. this._getDescendants(results, directDescendantsOnly, function (node) {
  13826. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  13827. });
  13828. return results;
  13829. };
  13830. /**
  13831. * Get all child-transformNodes of this node.
  13832. */
  13833. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  13834. var results = [];
  13835. this._getDescendants(results, directDescendantsOnly, function (node) {
  13836. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  13837. });
  13838. return results;
  13839. };
  13840. /**
  13841. * Get all direct children of this node.
  13842. */
  13843. Node.prototype.getChildren = function (predicate) {
  13844. return this.getDescendants(true, predicate);
  13845. };
  13846. Node.prototype._setReady = function (state) {
  13847. if (state === this._isReady) {
  13848. return;
  13849. }
  13850. if (!state) {
  13851. this._isReady = false;
  13852. return;
  13853. }
  13854. this._isReady = true;
  13855. if (this.onReady) {
  13856. this.onReady(this);
  13857. }
  13858. };
  13859. Node.prototype.getAnimationByName = function (name) {
  13860. for (var i = 0; i < this.animations.length; i++) {
  13861. var animation = this.animations[i];
  13862. if (animation.name === name) {
  13863. return animation;
  13864. }
  13865. }
  13866. return null;
  13867. };
  13868. Node.prototype.createAnimationRange = function (name, from, to) {
  13869. // check name not already in use
  13870. if (!this._ranges[name]) {
  13871. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  13872. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  13873. if (this.animations[i]) {
  13874. this.animations[i].createRange(name, from, to);
  13875. }
  13876. }
  13877. }
  13878. };
  13879. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  13880. if (deleteFrames === void 0) { deleteFrames = true; }
  13881. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  13882. if (this.animations[i]) {
  13883. this.animations[i].deleteRange(name, deleteFrames);
  13884. }
  13885. }
  13886. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  13887. };
  13888. Node.prototype.getAnimationRange = function (name) {
  13889. return this._ranges[name];
  13890. };
  13891. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  13892. var range = this.getAnimationRange(name);
  13893. if (!range) {
  13894. return;
  13895. }
  13896. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  13897. };
  13898. Node.prototype.serializeAnimationRanges = function () {
  13899. var serializationRanges = [];
  13900. for (var name in this._ranges) {
  13901. var localRange = this._ranges[name];
  13902. if (!localRange) {
  13903. continue;
  13904. }
  13905. var range = {};
  13906. range.name = name;
  13907. range.from = localRange.from;
  13908. range.to = localRange.to;
  13909. serializationRanges.push(range);
  13910. }
  13911. return serializationRanges;
  13912. };
  13913. // override it in derived class
  13914. Node.prototype.computeWorldMatrix = function (force) {
  13915. return BABYLON.Matrix.Identity();
  13916. };
  13917. Node.prototype.dispose = function () {
  13918. this.parent = null;
  13919. // Callback
  13920. this.onDisposeObservable.notifyObservers(this);
  13921. this.onDisposeObservable.clear();
  13922. // Behaviors
  13923. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  13924. var behavior = _a[_i];
  13925. behavior.detach();
  13926. }
  13927. this._behaviors = [];
  13928. };
  13929. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  13930. if (parsedNode.ranges) {
  13931. for (var index = 0; index < parsedNode.ranges.length; index++) {
  13932. var data = parsedNode.ranges[index];
  13933. node.createAnimationRange(data.name, data.from, data.to);
  13934. }
  13935. }
  13936. };
  13937. __decorate([
  13938. BABYLON.serialize()
  13939. ], Node.prototype, "name", void 0);
  13940. __decorate([
  13941. BABYLON.serialize()
  13942. ], Node.prototype, "id", void 0);
  13943. __decorate([
  13944. BABYLON.serialize()
  13945. ], Node.prototype, "uniqueId", void 0);
  13946. __decorate([
  13947. BABYLON.serialize()
  13948. ], Node.prototype, "state", void 0);
  13949. __decorate([
  13950. BABYLON.serialize()
  13951. ], Node.prototype, "metadata", void 0);
  13952. return Node;
  13953. }());
  13954. BABYLON.Node = Node;
  13955. })(BABYLON || (BABYLON = {}));
  13956. //# sourceMappingURL=babylon.node.js.map
  13957. var BABYLON;
  13958. (function (BABYLON) {
  13959. var BoundingSphere = /** @class */ (function () {
  13960. function BoundingSphere(minimum, maximum) {
  13961. this.minimum = minimum;
  13962. this.maximum = maximum;
  13963. this._tempRadiusVector = BABYLON.Vector3.Zero();
  13964. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  13965. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  13966. this.radius = distance * 0.5;
  13967. this.centerWorld = BABYLON.Vector3.Zero();
  13968. this._update(BABYLON.Matrix.Identity());
  13969. }
  13970. // Methods
  13971. BoundingSphere.prototype._update = function (world) {
  13972. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  13973. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  13974. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  13975. };
  13976. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  13977. for (var i = 0; i < 6; i++) {
  13978. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  13979. return false;
  13980. }
  13981. return true;
  13982. };
  13983. BoundingSphere.prototype.intersectsPoint = function (point) {
  13984. var x = this.centerWorld.x - point.x;
  13985. var y = this.centerWorld.y - point.y;
  13986. var z = this.centerWorld.z - point.z;
  13987. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  13988. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  13989. return false;
  13990. return true;
  13991. };
  13992. // Statics
  13993. BoundingSphere.Intersects = function (sphere0, sphere1) {
  13994. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  13995. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  13996. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  13997. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  13998. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  13999. return false;
  14000. return true;
  14001. };
  14002. return BoundingSphere;
  14003. }());
  14004. BABYLON.BoundingSphere = BoundingSphere;
  14005. })(BABYLON || (BABYLON = {}));
  14006. //# sourceMappingURL=babylon.boundingSphere.js.map
  14007. var BABYLON;
  14008. (function (BABYLON) {
  14009. var BoundingBox = /** @class */ (function () {
  14010. function BoundingBox(minimum, maximum) {
  14011. this.minimum = minimum;
  14012. this.maximum = maximum;
  14013. this.vectors = new Array();
  14014. this.vectorsWorld = new Array();
  14015. // Bounding vectors
  14016. this.vectors.push(this.minimum.clone());
  14017. this.vectors.push(this.maximum.clone());
  14018. this.vectors.push(this.minimum.clone());
  14019. this.vectors[2].x = this.maximum.x;
  14020. this.vectors.push(this.minimum.clone());
  14021. this.vectors[3].y = this.maximum.y;
  14022. this.vectors.push(this.minimum.clone());
  14023. this.vectors[4].z = this.maximum.z;
  14024. this.vectors.push(this.maximum.clone());
  14025. this.vectors[5].z = this.minimum.z;
  14026. this.vectors.push(this.maximum.clone());
  14027. this.vectors[6].x = this.minimum.x;
  14028. this.vectors.push(this.maximum.clone());
  14029. this.vectors[7].y = this.minimum.y;
  14030. // OBB
  14031. this.center = this.maximum.add(this.minimum).scale(0.5);
  14032. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  14033. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  14034. // World
  14035. for (var index = 0; index < this.vectors.length; index++) {
  14036. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  14037. }
  14038. this.minimumWorld = BABYLON.Vector3.Zero();
  14039. this.maximumWorld = BABYLON.Vector3.Zero();
  14040. this.centerWorld = BABYLON.Vector3.Zero();
  14041. this.extendSizeWorld = BABYLON.Vector3.Zero();
  14042. this._update(BABYLON.Matrix.Identity());
  14043. }
  14044. // Methods
  14045. BoundingBox.prototype.getWorldMatrix = function () {
  14046. return this._worldMatrix;
  14047. };
  14048. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  14049. this._worldMatrix.copyFrom(matrix);
  14050. return this;
  14051. };
  14052. BoundingBox.prototype._update = function (world) {
  14053. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  14054. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  14055. for (var index = 0; index < this.vectors.length; index++) {
  14056. var v = this.vectorsWorld[index];
  14057. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  14058. if (v.x < this.minimumWorld.x)
  14059. this.minimumWorld.x = v.x;
  14060. if (v.y < this.minimumWorld.y)
  14061. this.minimumWorld.y = v.y;
  14062. if (v.z < this.minimumWorld.z)
  14063. this.minimumWorld.z = v.z;
  14064. if (v.x > this.maximumWorld.x)
  14065. this.maximumWorld.x = v.x;
  14066. if (v.y > this.maximumWorld.y)
  14067. this.maximumWorld.y = v.y;
  14068. if (v.z > this.maximumWorld.z)
  14069. this.maximumWorld.z = v.z;
  14070. }
  14071. // Extend
  14072. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  14073. this.extendSizeWorld.scaleInPlace(0.5);
  14074. // OBB
  14075. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  14076. this.centerWorld.scaleInPlace(0.5);
  14077. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  14078. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  14079. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  14080. this._worldMatrix = world;
  14081. };
  14082. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  14083. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  14084. };
  14085. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14086. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  14087. };
  14088. BoundingBox.prototype.intersectsPoint = function (point) {
  14089. var delta = -BABYLON.Epsilon;
  14090. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  14091. return false;
  14092. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  14093. return false;
  14094. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  14095. return false;
  14096. return true;
  14097. };
  14098. BoundingBox.prototype.intersectsSphere = function (sphere) {
  14099. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  14100. };
  14101. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  14102. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  14103. return false;
  14104. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  14105. return false;
  14106. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  14107. return false;
  14108. return true;
  14109. };
  14110. // Statics
  14111. BoundingBox.Intersects = function (box0, box1) {
  14112. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  14113. return false;
  14114. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  14115. return false;
  14116. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  14117. return false;
  14118. return true;
  14119. };
  14120. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  14121. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  14122. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  14123. return (num <= (sphereRadius * sphereRadius));
  14124. };
  14125. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  14126. for (var p = 0; p < 6; p++) {
  14127. for (var i = 0; i < 8; i++) {
  14128. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14129. return false;
  14130. }
  14131. }
  14132. }
  14133. return true;
  14134. };
  14135. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  14136. for (var p = 0; p < 6; p++) {
  14137. var inCount = 8;
  14138. for (var i = 0; i < 8; i++) {
  14139. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14140. --inCount;
  14141. }
  14142. else {
  14143. break;
  14144. }
  14145. }
  14146. if (inCount === 0)
  14147. return false;
  14148. }
  14149. return true;
  14150. };
  14151. return BoundingBox;
  14152. }());
  14153. BABYLON.BoundingBox = BoundingBox;
  14154. })(BABYLON || (BABYLON = {}));
  14155. //# sourceMappingURL=babylon.boundingBox.js.map
  14156. var BABYLON;
  14157. (function (BABYLON) {
  14158. var computeBoxExtents = function (axis, box) {
  14159. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  14160. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  14161. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  14162. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  14163. var r = r0 + r1 + r2;
  14164. return {
  14165. min: p - r,
  14166. max: p + r
  14167. };
  14168. };
  14169. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  14170. var axisOverlap = function (axis, box0, box1) {
  14171. var result0 = computeBoxExtents(axis, box0);
  14172. var result1 = computeBoxExtents(axis, box1);
  14173. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  14174. };
  14175. var BoundingInfo = /** @class */ (function () {
  14176. function BoundingInfo(minimum, maximum) {
  14177. this.minimum = minimum;
  14178. this.maximum = maximum;
  14179. this._isLocked = false;
  14180. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  14181. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  14182. }
  14183. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  14184. get: function () {
  14185. return this._isLocked;
  14186. },
  14187. set: function (value) {
  14188. this._isLocked = value;
  14189. },
  14190. enumerable: true,
  14191. configurable: true
  14192. });
  14193. // Methods
  14194. BoundingInfo.prototype.update = function (world) {
  14195. if (this._isLocked) {
  14196. return;
  14197. }
  14198. this.boundingBox._update(world);
  14199. this.boundingSphere._update(world);
  14200. };
  14201. /**
  14202. * Recreate the bounding info to be centered around a specific point given a specific extend.
  14203. * @param center New center of the bounding info
  14204. * @param extend New extend of the bounding info
  14205. */
  14206. BoundingInfo.prototype.centerOn = function (center, extend) {
  14207. this.minimum = center.subtract(extend);
  14208. this.maximum = center.add(extend);
  14209. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  14210. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  14211. return this;
  14212. };
  14213. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  14214. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  14215. return false;
  14216. return this.boundingBox.isInFrustum(frustumPlanes);
  14217. };
  14218. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  14219. /**
  14220. * Gets the world distance between the min and max points of the bounding box
  14221. */
  14222. get: function () {
  14223. var boundingBox = this.boundingBox;
  14224. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  14225. return size.length();
  14226. },
  14227. enumerable: true,
  14228. configurable: true
  14229. });
  14230. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14231. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  14232. };
  14233. BoundingInfo.prototype._checkCollision = function (collider) {
  14234. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  14235. };
  14236. BoundingInfo.prototype.intersectsPoint = function (point) {
  14237. if (!this.boundingSphere.centerWorld) {
  14238. return false;
  14239. }
  14240. if (!this.boundingSphere.intersectsPoint(point)) {
  14241. return false;
  14242. }
  14243. if (!this.boundingBox.intersectsPoint(point)) {
  14244. return false;
  14245. }
  14246. return true;
  14247. };
  14248. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  14249. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  14250. return false;
  14251. }
  14252. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  14253. return false;
  14254. }
  14255. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  14256. return false;
  14257. }
  14258. if (!precise) {
  14259. return true;
  14260. }
  14261. var box0 = this.boundingBox;
  14262. var box1 = boundingInfo.boundingBox;
  14263. if (!axisOverlap(box0.directions[0], box0, box1))
  14264. return false;
  14265. if (!axisOverlap(box0.directions[1], box0, box1))
  14266. return false;
  14267. if (!axisOverlap(box0.directions[2], box0, box1))
  14268. return false;
  14269. if (!axisOverlap(box1.directions[0], box0, box1))
  14270. return false;
  14271. if (!axisOverlap(box1.directions[1], box0, box1))
  14272. return false;
  14273. if (!axisOverlap(box1.directions[2], box0, box1))
  14274. return false;
  14275. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  14276. return false;
  14277. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  14278. return false;
  14279. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  14280. return false;
  14281. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  14282. return false;
  14283. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  14284. return false;
  14285. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  14286. return false;
  14287. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  14288. return false;
  14289. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  14290. return false;
  14291. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  14292. return false;
  14293. return true;
  14294. };
  14295. return BoundingInfo;
  14296. }());
  14297. BABYLON.BoundingInfo = BoundingInfo;
  14298. })(BABYLON || (BABYLON = {}));
  14299. //# sourceMappingURL=babylon.boundingInfo.js.map
  14300. var BABYLON;
  14301. (function (BABYLON) {
  14302. var TransformNode = /** @class */ (function (_super) {
  14303. __extends(TransformNode, _super);
  14304. function TransformNode(name, scene, isPure) {
  14305. if (scene === void 0) { scene = null; }
  14306. if (isPure === void 0) { isPure = true; }
  14307. var _this = _super.call(this, name, scene) || this;
  14308. // Properties
  14309. _this._rotation = BABYLON.Vector3.Zero();
  14310. _this._scaling = BABYLON.Vector3.One();
  14311. _this._isDirty = false;
  14312. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  14313. _this.scalingDeterminant = 1;
  14314. _this.infiniteDistance = false;
  14315. _this.position = BABYLON.Vector3.Zero();
  14316. _this._localWorld = BABYLON.Matrix.Zero();
  14317. _this._worldMatrix = BABYLON.Matrix.Zero();
  14318. _this._worldMatrixDeterminant = 0;
  14319. _this._absolutePosition = BABYLON.Vector3.Zero();
  14320. _this._pivotMatrix = BABYLON.Matrix.Identity();
  14321. _this._postMultiplyPivotMatrix = false;
  14322. _this._isWorldMatrixFrozen = false;
  14323. /**
  14324. * An event triggered after the world matrix is updated
  14325. * @type {BABYLON.Observable}
  14326. */
  14327. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  14328. _this._nonUniformScaling = false;
  14329. if (isPure) {
  14330. _this.getScene().addTransformNode(_this);
  14331. }
  14332. return _this;
  14333. }
  14334. Object.defineProperty(TransformNode.prototype, "rotation", {
  14335. /**
  14336. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  14337. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  14338. * Default : (0.0, 0.0, 0.0)
  14339. */
  14340. get: function () {
  14341. return this._rotation;
  14342. },
  14343. set: function (newRotation) {
  14344. this._rotation = newRotation;
  14345. },
  14346. enumerable: true,
  14347. configurable: true
  14348. });
  14349. Object.defineProperty(TransformNode.prototype, "scaling", {
  14350. /**
  14351. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14352. * Default : (1.0, 1.0, 1.0)
  14353. */
  14354. get: function () {
  14355. return this._scaling;
  14356. },
  14357. /**
  14358. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14359. * Default : (1.0, 1.0, 1.0)
  14360. */
  14361. set: function (newScaling) {
  14362. this._scaling = newScaling;
  14363. },
  14364. enumerable: true,
  14365. configurable: true
  14366. });
  14367. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  14368. /**
  14369. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  14370. * It's null by default.
  14371. * 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)
  14372. */
  14373. get: function () {
  14374. return this._rotationQuaternion;
  14375. },
  14376. set: function (quaternion) {
  14377. this._rotationQuaternion = quaternion;
  14378. //reset the rotation vector.
  14379. if (quaternion && this.rotation.length()) {
  14380. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  14381. }
  14382. },
  14383. enumerable: true,
  14384. configurable: true
  14385. });
  14386. /**
  14387. * Returns the latest update of the World matrix
  14388. * Returns a Matrix.
  14389. */
  14390. TransformNode.prototype.getWorldMatrix = function () {
  14391. if (this._currentRenderId !== this.getScene().getRenderId()) {
  14392. this.computeWorldMatrix();
  14393. }
  14394. return this._worldMatrix;
  14395. };
  14396. /**
  14397. * Returns the latest update of the World matrix determinant.
  14398. */
  14399. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  14400. if (this._currentRenderId !== this.getScene().getRenderId()) {
  14401. this.computeWorldMatrix();
  14402. }
  14403. return this._worldMatrixDeterminant;
  14404. };
  14405. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  14406. /**
  14407. * Returns directly the latest state of the mesh World matrix.
  14408. * A Matrix is returned.
  14409. */
  14410. get: function () {
  14411. return this._worldMatrix;
  14412. },
  14413. enumerable: true,
  14414. configurable: true
  14415. });
  14416. /**
  14417. * Copies the paramater passed Matrix into the mesh Pose matrix.
  14418. * Returns the AbstractMesh.
  14419. */
  14420. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  14421. this._poseMatrix.copyFrom(matrix);
  14422. return this;
  14423. };
  14424. /**
  14425. * Returns the mesh Pose matrix.
  14426. * Returned object : Matrix
  14427. */
  14428. TransformNode.prototype.getPoseMatrix = function () {
  14429. return this._poseMatrix;
  14430. };
  14431. TransformNode.prototype._isSynchronized = function () {
  14432. if (this._isDirty) {
  14433. return false;
  14434. }
  14435. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  14436. return false;
  14437. if (this._cache.pivotMatrixUpdated) {
  14438. return false;
  14439. }
  14440. if (this.infiniteDistance) {
  14441. return false;
  14442. }
  14443. if (!this._cache.position.equals(this.position))
  14444. return false;
  14445. if (this.rotationQuaternion) {
  14446. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  14447. return false;
  14448. }
  14449. if (!this._cache.rotation.equals(this.rotation))
  14450. return false;
  14451. if (!this._cache.scaling.equals(this.scaling))
  14452. return false;
  14453. return true;
  14454. };
  14455. TransformNode.prototype._initCache = function () {
  14456. _super.prototype._initCache.call(this);
  14457. this._cache.localMatrixUpdated = false;
  14458. this._cache.position = BABYLON.Vector3.Zero();
  14459. this._cache.scaling = BABYLON.Vector3.Zero();
  14460. this._cache.rotation = BABYLON.Vector3.Zero();
  14461. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  14462. this._cache.billboardMode = -1;
  14463. };
  14464. TransformNode.prototype.markAsDirty = function (property) {
  14465. if (property === "rotation") {
  14466. this.rotationQuaternion = null;
  14467. }
  14468. this._currentRenderId = Number.MAX_VALUE;
  14469. this._isDirty = true;
  14470. return this;
  14471. };
  14472. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  14473. /**
  14474. * Returns the current mesh absolute position.
  14475. * Retuns a Vector3.
  14476. */
  14477. get: function () {
  14478. return this._absolutePosition;
  14479. },
  14480. enumerable: true,
  14481. configurable: true
  14482. });
  14483. /**
  14484. * Sets a new pivot matrix to the mesh.
  14485. * Returns the AbstractMesh.
  14486. */
  14487. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  14488. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  14489. this._pivotMatrix = matrix.clone();
  14490. this._cache.pivotMatrixUpdated = true;
  14491. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  14492. if (this._postMultiplyPivotMatrix) {
  14493. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  14494. }
  14495. return this;
  14496. };
  14497. /**
  14498. * Returns the mesh pivot matrix.
  14499. * Default : Identity.
  14500. * A Matrix is returned.
  14501. */
  14502. TransformNode.prototype.getPivotMatrix = function () {
  14503. return this._pivotMatrix;
  14504. };
  14505. /**
  14506. * Prevents the World matrix to be computed any longer.
  14507. * Returns the AbstractMesh.
  14508. */
  14509. TransformNode.prototype.freezeWorldMatrix = function () {
  14510. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  14511. this.computeWorldMatrix(true);
  14512. this._isWorldMatrixFrozen = true;
  14513. return this;
  14514. };
  14515. /**
  14516. * Allows back the World matrix computation.
  14517. * Returns the AbstractMesh.
  14518. */
  14519. TransformNode.prototype.unfreezeWorldMatrix = function () {
  14520. this._isWorldMatrixFrozen = false;
  14521. this.computeWorldMatrix(true);
  14522. return this;
  14523. };
  14524. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  14525. /**
  14526. * True if the World matrix has been frozen.
  14527. * Returns a boolean.
  14528. */
  14529. get: function () {
  14530. return this._isWorldMatrixFrozen;
  14531. },
  14532. enumerable: true,
  14533. configurable: true
  14534. });
  14535. /**
  14536. * Retuns the mesh absolute position in the World.
  14537. * Returns a Vector3.
  14538. */
  14539. TransformNode.prototype.getAbsolutePosition = function () {
  14540. this.computeWorldMatrix();
  14541. return this._absolutePosition;
  14542. };
  14543. /**
  14544. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  14545. * Returns the AbstractMesh.
  14546. */
  14547. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  14548. if (!absolutePosition) {
  14549. return this;
  14550. }
  14551. var absolutePositionX;
  14552. var absolutePositionY;
  14553. var absolutePositionZ;
  14554. if (absolutePosition.x === undefined) {
  14555. if (arguments.length < 3) {
  14556. return this;
  14557. }
  14558. absolutePositionX = arguments[0];
  14559. absolutePositionY = arguments[1];
  14560. absolutePositionZ = arguments[2];
  14561. }
  14562. else {
  14563. absolutePositionX = absolutePosition.x;
  14564. absolutePositionY = absolutePosition.y;
  14565. absolutePositionZ = absolutePosition.z;
  14566. }
  14567. if (this.parent) {
  14568. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  14569. invertParentWorldMatrix.invert();
  14570. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  14571. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  14572. }
  14573. else {
  14574. this.position.x = absolutePositionX;
  14575. this.position.y = absolutePositionY;
  14576. this.position.z = absolutePositionZ;
  14577. }
  14578. return this;
  14579. };
  14580. /**
  14581. * Sets the mesh position in its local space.
  14582. * Returns the AbstractMesh.
  14583. */
  14584. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  14585. this.computeWorldMatrix();
  14586. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  14587. return this;
  14588. };
  14589. /**
  14590. * Returns the mesh position in the local space from the current World matrix values.
  14591. * Returns a new Vector3.
  14592. */
  14593. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  14594. this.computeWorldMatrix();
  14595. var invLocalWorldMatrix = this._localWorld.clone();
  14596. invLocalWorldMatrix.invert();
  14597. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  14598. };
  14599. /**
  14600. * Translates the mesh along the passed Vector3 in its local space.
  14601. * Returns the AbstractMesh.
  14602. */
  14603. TransformNode.prototype.locallyTranslate = function (vector3) {
  14604. this.computeWorldMatrix(true);
  14605. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  14606. return this;
  14607. };
  14608. /**
  14609. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  14610. * @param targetPoint the position (must be in same space as current mesh) to look at
  14611. * @param yawCor optional yaw (y-axis) correction in radians
  14612. * @param pitchCor optional pitch (x-axis) correction in radians
  14613. * @param rollCor optional roll (z-axis) correction in radians
  14614. * @param space the choosen space of the target
  14615. * @returns the TransformNode.
  14616. */
  14617. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  14618. if (yawCor === void 0) { yawCor = 0; }
  14619. if (pitchCor === void 0) { pitchCor = 0; }
  14620. if (rollCor === void 0) { rollCor = 0; }
  14621. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14622. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  14623. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  14624. targetPoint.subtractToRef(pos, dv);
  14625. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  14626. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  14627. var pitch = Math.atan2(dv.y, len);
  14628. if (this.rotationQuaternion) {
  14629. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  14630. }
  14631. else {
  14632. this.rotation.x = pitch + pitchCor;
  14633. this.rotation.y = yaw + yawCor;
  14634. this.rotation.z = rollCor;
  14635. }
  14636. return this;
  14637. };
  14638. /**
  14639. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  14640. * This Vector3 is expressed in the World space.
  14641. */
  14642. TransformNode.prototype.getDirection = function (localAxis) {
  14643. var result = BABYLON.Vector3.Zero();
  14644. this.getDirectionToRef(localAxis, result);
  14645. return result;
  14646. };
  14647. /**
  14648. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  14649. * localAxis is expressed in the mesh local space.
  14650. * result is computed in the Wordl space from the mesh World matrix.
  14651. * Returns the AbstractMesh.
  14652. */
  14653. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  14654. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14655. return this;
  14656. };
  14657. TransformNode.prototype.setPivotPoint = function (point, space) {
  14658. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14659. if (this.getScene().getRenderId() == 0) {
  14660. this.computeWorldMatrix(true);
  14661. }
  14662. var wm = this.getWorldMatrix();
  14663. if (space == BABYLON.Space.WORLD) {
  14664. var tmat = BABYLON.Tmp.Matrix[0];
  14665. wm.invertToRef(tmat);
  14666. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  14667. }
  14668. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  14669. this._pivotMatrix.m[12] = -point.x;
  14670. this._pivotMatrix.m[13] = -point.y;
  14671. this._pivotMatrix.m[14] = -point.z;
  14672. this._cache.pivotMatrixUpdated = true;
  14673. return this;
  14674. };
  14675. /**
  14676. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  14677. */
  14678. TransformNode.prototype.getPivotPoint = function () {
  14679. var point = BABYLON.Vector3.Zero();
  14680. this.getPivotPointToRef(point);
  14681. return point;
  14682. };
  14683. /**
  14684. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  14685. * Returns the AbstractMesh.
  14686. */
  14687. TransformNode.prototype.getPivotPointToRef = function (result) {
  14688. result.x = -this._pivotMatrix.m[12];
  14689. result.y = -this._pivotMatrix.m[13];
  14690. result.z = -this._pivotMatrix.m[14];
  14691. return this;
  14692. };
  14693. /**
  14694. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  14695. */
  14696. TransformNode.prototype.getAbsolutePivotPoint = function () {
  14697. var point = BABYLON.Vector3.Zero();
  14698. this.getAbsolutePivotPointToRef(point);
  14699. return point;
  14700. };
  14701. /**
  14702. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  14703. * Returns the AbstractMesh.
  14704. */
  14705. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  14706. result.x = this._pivotMatrix.m[12];
  14707. result.y = this._pivotMatrix.m[13];
  14708. result.z = this._pivotMatrix.m[14];
  14709. this.getPivotPointToRef(result);
  14710. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  14711. return this;
  14712. };
  14713. /**
  14714. * Defines the passed node as the parent of the current node.
  14715. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  14716. * Returns the TransformNode.
  14717. */
  14718. TransformNode.prototype.setParent = function (node) {
  14719. if (node === null) {
  14720. var rotation = BABYLON.Tmp.Quaternion[0];
  14721. var position = BABYLON.Tmp.Vector3[0];
  14722. var scale = BABYLON.Tmp.Vector3[1];
  14723. if (this.parent && this.parent.computeWorldMatrix) {
  14724. this.parent.computeWorldMatrix(true);
  14725. }
  14726. this.computeWorldMatrix(true);
  14727. this.getWorldMatrix().decompose(scale, rotation, position);
  14728. if (this.rotationQuaternion) {
  14729. this.rotationQuaternion.copyFrom(rotation);
  14730. }
  14731. else {
  14732. rotation.toEulerAnglesToRef(this.rotation);
  14733. }
  14734. this.scaling.x = scale.x;
  14735. this.scaling.y = scale.y;
  14736. this.scaling.z = scale.z;
  14737. this.position.x = position.x;
  14738. this.position.y = position.y;
  14739. this.position.z = position.z;
  14740. }
  14741. else {
  14742. var rotation = BABYLON.Tmp.Quaternion[0];
  14743. var position = BABYLON.Tmp.Vector3[0];
  14744. var scale = BABYLON.Tmp.Vector3[1];
  14745. var diffMatrix = BABYLON.Tmp.Matrix[0];
  14746. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  14747. this.computeWorldMatrix(true);
  14748. node.computeWorldMatrix(true);
  14749. node.getWorldMatrix().invertToRef(invParentMatrix);
  14750. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  14751. diffMatrix.decompose(scale, rotation, position);
  14752. if (this.rotationQuaternion) {
  14753. this.rotationQuaternion.copyFrom(rotation);
  14754. }
  14755. else {
  14756. rotation.toEulerAnglesToRef(this.rotation);
  14757. }
  14758. this.position.x = position.x;
  14759. this.position.y = position.y;
  14760. this.position.z = position.z;
  14761. this.scaling.x = scale.x;
  14762. this.scaling.y = scale.y;
  14763. this.scaling.z = scale.z;
  14764. }
  14765. this.parent = node;
  14766. return this;
  14767. };
  14768. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  14769. get: function () {
  14770. return this._nonUniformScaling;
  14771. },
  14772. enumerable: true,
  14773. configurable: true
  14774. });
  14775. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  14776. if (this._nonUniformScaling === value) {
  14777. return false;
  14778. }
  14779. this._nonUniformScaling = true;
  14780. return true;
  14781. };
  14782. /**
  14783. * Attach the current TransformNode to another TransformNode associated with a bone
  14784. * @param bone Bone affecting the TransformNode
  14785. * @param affectedTransformNode TransformNode associated with the bone
  14786. */
  14787. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  14788. this._transformToBoneReferal = affectedTransformNode;
  14789. this.parent = bone;
  14790. if (bone.getWorldMatrix().determinant() < 0) {
  14791. this.scalingDeterminant *= -1;
  14792. }
  14793. return this;
  14794. };
  14795. TransformNode.prototype.detachFromBone = function () {
  14796. if (!this.parent) {
  14797. return this;
  14798. }
  14799. if (this.parent.getWorldMatrix().determinant() < 0) {
  14800. this.scalingDeterminant *= -1;
  14801. }
  14802. this._transformToBoneReferal = null;
  14803. this.parent = null;
  14804. return this;
  14805. };
  14806. /**
  14807. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  14808. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  14809. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  14810. * The passed axis is also normalized.
  14811. * Returns the AbstractMesh.
  14812. */
  14813. TransformNode.prototype.rotate = function (axis, amount, space) {
  14814. axis.normalize();
  14815. if (!this.rotationQuaternion) {
  14816. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14817. this.rotation = BABYLON.Vector3.Zero();
  14818. }
  14819. var rotationQuaternion;
  14820. if (!space || space === BABYLON.Space.LOCAL) {
  14821. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  14822. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  14823. }
  14824. else {
  14825. if (this.parent) {
  14826. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  14827. invertParentWorldMatrix.invert();
  14828. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  14829. }
  14830. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  14831. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  14832. }
  14833. return this;
  14834. };
  14835. /**
  14836. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  14837. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  14838. * The passed axis is also normalized.
  14839. * Returns the AbstractMesh.
  14840. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  14841. */
  14842. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  14843. axis.normalize();
  14844. if (!this.rotationQuaternion) {
  14845. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14846. this.rotation.copyFromFloats(0, 0, 0);
  14847. }
  14848. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  14849. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  14850. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  14851. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  14852. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  14853. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  14854. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  14855. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  14856. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  14857. return this;
  14858. };
  14859. /**
  14860. * Translates the mesh along the axis vector for the passed distance in the given space.
  14861. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  14862. * Returns the AbstractMesh.
  14863. */
  14864. TransformNode.prototype.translate = function (axis, distance, space) {
  14865. var displacementVector = axis.scale(distance);
  14866. if (!space || space === BABYLON.Space.LOCAL) {
  14867. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  14868. this.setPositionWithLocalVector(tempV3);
  14869. }
  14870. else {
  14871. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  14872. }
  14873. return this;
  14874. };
  14875. /**
  14876. * Adds a rotation step to the mesh current rotation.
  14877. * x, y, z are Euler angles expressed in radians.
  14878. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  14879. * This means this rotation is made in the mesh local space only.
  14880. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  14881. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  14882. * ```javascript
  14883. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  14884. * ```
  14885. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  14886. * 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.
  14887. * Returns the AbstractMesh.
  14888. */
  14889. TransformNode.prototype.addRotation = function (x, y, z) {
  14890. var rotationQuaternion;
  14891. if (this.rotationQuaternion) {
  14892. rotationQuaternion = this.rotationQuaternion;
  14893. }
  14894. else {
  14895. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  14896. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  14897. }
  14898. var accumulation = BABYLON.Tmp.Quaternion[0];
  14899. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  14900. rotationQuaternion.multiplyInPlace(accumulation);
  14901. if (!this.rotationQuaternion) {
  14902. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  14903. }
  14904. return this;
  14905. };
  14906. /**
  14907. * Computes the mesh World matrix and returns it.
  14908. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  14909. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  14910. * If the parameter `force`is set to `true`, the actual computation is done.
  14911. * Returns the mesh World Matrix.
  14912. */
  14913. TransformNode.prototype.computeWorldMatrix = function (force) {
  14914. if (this._isWorldMatrixFrozen) {
  14915. return this._worldMatrix;
  14916. }
  14917. if (!force && this.isSynchronized(true)) {
  14918. return this._worldMatrix;
  14919. }
  14920. this._cache.position.copyFrom(this.position);
  14921. this._cache.scaling.copyFrom(this.scaling);
  14922. this._cache.pivotMatrixUpdated = false;
  14923. this._cache.billboardMode = this.billboardMode;
  14924. this._currentRenderId = this.getScene().getRenderId();
  14925. this._isDirty = false;
  14926. // Scaling
  14927. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  14928. // Rotation
  14929. //rotate, if quaternion is set and rotation was used
  14930. if (this.rotationQuaternion) {
  14931. var len = this.rotation.length();
  14932. if (len) {
  14933. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  14934. this.rotation.copyFromFloats(0, 0, 0);
  14935. }
  14936. }
  14937. if (this.rotationQuaternion) {
  14938. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  14939. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14940. }
  14941. else {
  14942. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  14943. this._cache.rotation.copyFrom(this.rotation);
  14944. }
  14945. // Translation
  14946. var camera = this.getScene().activeCamera;
  14947. if (this.infiniteDistance && !this.parent && camera) {
  14948. var cameraWorldMatrix = camera.getWorldMatrix();
  14949. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  14950. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  14951. }
  14952. else {
  14953. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  14954. }
  14955. // Composing transformations
  14956. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  14957. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  14958. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  14959. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  14960. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  14961. // Need to decompose each rotation here
  14962. var currentPosition = BABYLON.Tmp.Vector3[3];
  14963. if (this.parent && this.parent.getWorldMatrix) {
  14964. if (this._transformToBoneReferal) {
  14965. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14966. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  14967. }
  14968. else {
  14969. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  14970. }
  14971. }
  14972. else {
  14973. currentPosition.copyFrom(this.position);
  14974. }
  14975. currentPosition.subtractInPlace(camera.globalPosition);
  14976. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  14977. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  14978. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  14979. }
  14980. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  14981. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  14982. }
  14983. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  14984. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  14985. }
  14986. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  14987. }
  14988. else {
  14989. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  14990. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  14991. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  14992. }
  14993. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  14994. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  14995. }
  14996. // Local world
  14997. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  14998. // Parent
  14999. if (this.parent && this.parent.getWorldMatrix) {
  15000. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  15001. if (this._transformToBoneReferal) {
  15002. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15003. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  15004. }
  15005. else {
  15006. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  15007. }
  15008. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  15009. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  15010. this._worldMatrix.copyFrom(this._localWorld);
  15011. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  15012. }
  15013. else {
  15014. if (this._transformToBoneReferal) {
  15015. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15016. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  15017. }
  15018. else {
  15019. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  15020. }
  15021. }
  15022. this._markSyncedWithParent();
  15023. }
  15024. else {
  15025. this._worldMatrix.copyFrom(this._localWorld);
  15026. }
  15027. // Post multiply inverse of pivotMatrix
  15028. if (this._postMultiplyPivotMatrix) {
  15029. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  15030. }
  15031. // Normal matrix
  15032. if (this.scaling.isNonUniform) {
  15033. this._updateNonUniformScalingState(true);
  15034. }
  15035. else if (this.parent && this.parent._nonUniformScaling) {
  15036. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  15037. }
  15038. else {
  15039. this._updateNonUniformScalingState(false);
  15040. }
  15041. this._afterComputeWorldMatrix();
  15042. // Absolute position
  15043. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  15044. // Callbacks
  15045. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  15046. if (!this._poseMatrix) {
  15047. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  15048. }
  15049. // Cache the determinant
  15050. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  15051. return this._worldMatrix;
  15052. };
  15053. TransformNode.prototype._afterComputeWorldMatrix = function () {
  15054. };
  15055. /**
  15056. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  15057. * @param func: callback function to add
  15058. *
  15059. * Returns the TransformNode.
  15060. */
  15061. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  15062. this.onAfterWorldMatrixUpdateObservable.add(func);
  15063. return this;
  15064. };
  15065. /**
  15066. * Removes a registered callback function.
  15067. * Returns the TransformNode.
  15068. */
  15069. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  15070. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  15071. return this;
  15072. };
  15073. /**
  15074. * Clone the current transform node
  15075. * Returns the new transform node
  15076. * @param name Name of the new clone
  15077. * @param newParent New parent for the clone
  15078. * @param doNotCloneChildren Do not clone children hierarchy
  15079. */
  15080. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15081. var _this = this;
  15082. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  15083. result.name = name;
  15084. result.id = name;
  15085. if (newParent) {
  15086. result.parent = newParent;
  15087. }
  15088. if (!doNotCloneChildren) {
  15089. // Children
  15090. var directDescendants = this.getDescendants(true);
  15091. for (var index = 0; index < directDescendants.length; index++) {
  15092. var child = directDescendants[index];
  15093. if (child.clone) {
  15094. child.clone(name + "." + child.name, result);
  15095. }
  15096. }
  15097. }
  15098. return result;
  15099. };
  15100. TransformNode.prototype.serialize = function (currentSerializationObject) {
  15101. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  15102. serializationObject.type = this.getClassName();
  15103. // Parent
  15104. if (this.parent) {
  15105. serializationObject.parentId = this.parent.id;
  15106. }
  15107. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  15108. serializationObject.tags = BABYLON.Tags.GetTags(this);
  15109. }
  15110. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  15111. serializationObject.isEnabled = this.isEnabled();
  15112. // Parent
  15113. if (this.parent) {
  15114. serializationObject.parentId = this.parent.id;
  15115. }
  15116. return serializationObject;
  15117. };
  15118. // Statics
  15119. /**
  15120. * Returns a new TransformNode object parsed from the source provided.
  15121. * The parameter `parsedMesh` is the source.
  15122. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  15123. */
  15124. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  15125. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  15126. if (BABYLON.Tags) {
  15127. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  15128. }
  15129. if (parsedTransformNode.localMatrix) {
  15130. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  15131. }
  15132. else if (parsedTransformNode.pivotMatrix) {
  15133. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  15134. }
  15135. transformNode.setEnabled(parsedTransformNode.isEnabled);
  15136. // Parent
  15137. if (parsedTransformNode.parentId) {
  15138. transformNode._waitingParentId = parsedTransformNode.parentId;
  15139. }
  15140. return transformNode;
  15141. };
  15142. /**
  15143. * Disposes the TransformNode.
  15144. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15145. * Returns nothing.
  15146. */
  15147. TransformNode.prototype.dispose = function (doNotRecurse) {
  15148. // Animations
  15149. this.getScene().stopAnimation(this);
  15150. // Remove from scene
  15151. this.getScene().removeTransformNode(this);
  15152. this._cache = {};
  15153. if (!doNotRecurse) {
  15154. // Children
  15155. var objects = this.getDescendants(true);
  15156. for (var index = 0; index < objects.length; index++) {
  15157. objects[index].dispose();
  15158. }
  15159. }
  15160. else {
  15161. var childMeshes = this.getChildMeshes(true);
  15162. for (index = 0; index < childMeshes.length; index++) {
  15163. var child = childMeshes[index];
  15164. child.parent = null;
  15165. child.computeWorldMatrix(true);
  15166. }
  15167. }
  15168. this.onAfterWorldMatrixUpdateObservable.clear();
  15169. _super.prototype.dispose.call(this);
  15170. };
  15171. // Statics
  15172. TransformNode.BILLBOARDMODE_NONE = 0;
  15173. TransformNode.BILLBOARDMODE_X = 1;
  15174. TransformNode.BILLBOARDMODE_Y = 2;
  15175. TransformNode.BILLBOARDMODE_Z = 4;
  15176. TransformNode.BILLBOARDMODE_ALL = 7;
  15177. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15178. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  15179. __decorate([
  15180. BABYLON.serializeAsVector3()
  15181. ], TransformNode.prototype, "_rotation", void 0);
  15182. __decorate([
  15183. BABYLON.serializeAsQuaternion()
  15184. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  15185. __decorate([
  15186. BABYLON.serializeAsVector3()
  15187. ], TransformNode.prototype, "_scaling", void 0);
  15188. __decorate([
  15189. BABYLON.serialize()
  15190. ], TransformNode.prototype, "billboardMode", void 0);
  15191. __decorate([
  15192. BABYLON.serialize()
  15193. ], TransformNode.prototype, "scalingDeterminant", void 0);
  15194. __decorate([
  15195. BABYLON.serialize()
  15196. ], TransformNode.prototype, "infiniteDistance", void 0);
  15197. __decorate([
  15198. BABYLON.serializeAsVector3()
  15199. ], TransformNode.prototype, "position", void 0);
  15200. return TransformNode;
  15201. }(BABYLON.Node));
  15202. BABYLON.TransformNode = TransformNode;
  15203. })(BABYLON || (BABYLON = {}));
  15204. //# sourceMappingURL=babylon.transformNode.js.map
  15205. var BABYLON;
  15206. (function (BABYLON) {
  15207. var AbstractMesh = /** @class */ (function (_super) {
  15208. __extends(AbstractMesh, _super);
  15209. // Constructor
  15210. function AbstractMesh(name, scene) {
  15211. if (scene === void 0) { scene = null; }
  15212. var _this = _super.call(this, name, scene, false) || this;
  15213. _this._facetNb = 0; // facet number
  15214. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  15215. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  15216. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  15217. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  15218. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  15219. _this._subDiv = {
  15220. max: 1,
  15221. X: 1,
  15222. Y: 1,
  15223. Z: 1
  15224. };
  15225. _this._facetDepthSort = false; // is the facet depth sort to be computed
  15226. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  15227. // Events
  15228. /**
  15229. * An event triggered when this mesh collides with another one
  15230. * @type {BABYLON.Observable}
  15231. */
  15232. _this.onCollideObservable = new BABYLON.Observable();
  15233. /**
  15234. * An event triggered when the collision's position changes
  15235. * @type {BABYLON.Observable}
  15236. */
  15237. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  15238. /**
  15239. * An event triggered when material is changed
  15240. * @type {BABYLON.Observable}
  15241. */
  15242. _this.onMaterialChangedObservable = new BABYLON.Observable();
  15243. // Properties
  15244. _this.definedFacingForward = true; // orientation for POV movement & rotation
  15245. /**
  15246. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  15247. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  15248. * or
  15249. * 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.
  15250. * for more info check WebGl documentations
  15251. */
  15252. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  15253. /**
  15254. * 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:
  15255. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  15256. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  15257. * 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.
  15258. */
  15259. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  15260. /**
  15261. * 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.
  15262. * The default value is -1 which means don't break the query and wait till the result.
  15263. */
  15264. _this.occlusionRetryCount = -1;
  15265. _this._occlusionInternalRetryCounter = 0;
  15266. _this._isOccluded = false;
  15267. _this._isOcclusionQueryInProgress = false;
  15268. _this.visibility = 1.0;
  15269. _this.alphaIndex = Number.MAX_VALUE;
  15270. _this.isVisible = true;
  15271. _this.isPickable = true;
  15272. _this.showBoundingBox = false;
  15273. _this.showSubMeshesBoundingBox = false;
  15274. _this.isBlocker = false;
  15275. _this.enablePointerMoveEvents = false;
  15276. _this.renderingGroupId = 0;
  15277. _this._receiveShadows = false;
  15278. _this.renderOutline = false;
  15279. _this.outlineColor = BABYLON.Color3.Red();
  15280. _this.outlineWidth = 0.02;
  15281. _this.renderOverlay = false;
  15282. _this.overlayColor = BABYLON.Color3.Red();
  15283. _this.overlayAlpha = 0.5;
  15284. _this._hasVertexAlpha = false;
  15285. _this._useVertexColors = true;
  15286. _this._computeBonesUsingShaders = true;
  15287. _this._numBoneInfluencers = 4;
  15288. _this._applyFog = true;
  15289. _this.useOctreeForRenderingSelection = true;
  15290. _this.useOctreeForPicking = true;
  15291. _this.useOctreeForCollisions = true;
  15292. _this._layerMask = 0x0FFFFFFF;
  15293. /**
  15294. * True if the mesh must be rendered in any case.
  15295. */
  15296. _this.alwaysSelectAsActiveMesh = false;
  15297. /**
  15298. * This scene's action manager
  15299. * @type {BABYLON.ActionManager}
  15300. */
  15301. _this.actionManager = null;
  15302. // Physics
  15303. _this.physicsImpostor = null;
  15304. // Collisions
  15305. _this._checkCollisions = false;
  15306. _this._collisionMask = -1;
  15307. _this._collisionGroup = -1;
  15308. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  15309. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  15310. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15311. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15312. // Edges
  15313. _this.edgesWidth = 1;
  15314. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  15315. // Cache
  15316. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  15317. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  15318. _this._isDisposed = false;
  15319. _this._renderId = 0;
  15320. _this._intersectionsInProgress = new Array();
  15321. _this._unIndexed = false;
  15322. _this._lightSources = new Array();
  15323. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15324. if (collidedMesh === void 0) { collidedMesh = null; }
  15325. //TODO move this to the collision coordinator!
  15326. if (_this.getScene().workerCollisions)
  15327. newPosition.multiplyInPlace(_this._collider._radius);
  15328. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  15329. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  15330. _this.position.addInPlace(_this._diffPositionForCollisions);
  15331. }
  15332. if (collidedMesh) {
  15333. _this.onCollideObservable.notifyObservers(collidedMesh);
  15334. }
  15335. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  15336. };
  15337. _this.getScene().addMesh(_this);
  15338. _this._resyncLightSources();
  15339. return _this;
  15340. }
  15341. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  15342. get: function () {
  15343. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  15344. },
  15345. enumerable: true,
  15346. configurable: true
  15347. });
  15348. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  15349. get: function () {
  15350. return BABYLON.TransformNode.BILLBOARDMODE_X;
  15351. },
  15352. enumerable: true,
  15353. configurable: true
  15354. });
  15355. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  15356. get: function () {
  15357. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  15358. },
  15359. enumerable: true,
  15360. configurable: true
  15361. });
  15362. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  15363. get: function () {
  15364. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  15365. },
  15366. enumerable: true,
  15367. configurable: true
  15368. });
  15369. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  15370. get: function () {
  15371. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  15372. },
  15373. enumerable: true,
  15374. configurable: true
  15375. });
  15376. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  15377. /**
  15378. * Read-only : the number of facets in the mesh
  15379. */
  15380. get: function () {
  15381. return this._facetNb;
  15382. },
  15383. enumerable: true,
  15384. configurable: true
  15385. });
  15386. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  15387. /**
  15388. * The number (integer) of subdivisions per axis in the partioning space
  15389. */
  15390. get: function () {
  15391. return this._partitioningSubdivisions;
  15392. },
  15393. set: function (nb) {
  15394. this._partitioningSubdivisions = nb;
  15395. },
  15396. enumerable: true,
  15397. configurable: true
  15398. });
  15399. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  15400. /**
  15401. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  15402. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  15403. */
  15404. get: function () {
  15405. return this._partitioningBBoxRatio;
  15406. },
  15407. set: function (ratio) {
  15408. this._partitioningBBoxRatio = ratio;
  15409. },
  15410. enumerable: true,
  15411. configurable: true
  15412. });
  15413. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  15414. /**
  15415. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  15416. * Works only for updatable meshes.
  15417. * Doesn't work with multi-materials.
  15418. */
  15419. get: function () {
  15420. return this._facetDepthSort;
  15421. },
  15422. set: function (sort) {
  15423. this._facetDepthSort = sort;
  15424. },
  15425. enumerable: true,
  15426. configurable: true
  15427. });
  15428. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  15429. /**
  15430. * The location (Vector3) where the facet depth sort must be computed from.
  15431. * By default, the active camera position.
  15432. * Used only when facet depth sort is enabled.
  15433. */
  15434. get: function () {
  15435. return this._facetDepthSortFrom;
  15436. },
  15437. set: function (location) {
  15438. this._facetDepthSortFrom = location;
  15439. },
  15440. enumerable: true,
  15441. configurable: true
  15442. });
  15443. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  15444. /**
  15445. * Read-only boolean : is the feature facetData enabled ?
  15446. */
  15447. get: function () {
  15448. return this._facetDataEnabled;
  15449. },
  15450. enumerable: true,
  15451. configurable: true
  15452. });
  15453. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  15454. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  15455. return false;
  15456. }
  15457. this._markSubMeshesAsMiscDirty();
  15458. return true;
  15459. };
  15460. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  15461. set: function (callback) {
  15462. if (this._onCollideObserver) {
  15463. this.onCollideObservable.remove(this._onCollideObserver);
  15464. }
  15465. this._onCollideObserver = this.onCollideObservable.add(callback);
  15466. },
  15467. enumerable: true,
  15468. configurable: true
  15469. });
  15470. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  15471. set: function (callback) {
  15472. if (this._onCollisionPositionChangeObserver) {
  15473. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  15474. }
  15475. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  15476. },
  15477. enumerable: true,
  15478. configurable: true
  15479. });
  15480. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  15481. /**
  15482. * 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.
  15483. */
  15484. get: function () {
  15485. return this._isOccluded;
  15486. },
  15487. set: function (value) {
  15488. this._isOccluded = value;
  15489. },
  15490. enumerable: true,
  15491. configurable: true
  15492. });
  15493. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  15494. /**
  15495. * Flag to check the progress status of the query
  15496. */
  15497. get: function () {
  15498. return this._isOcclusionQueryInProgress;
  15499. },
  15500. enumerable: true,
  15501. configurable: true
  15502. });
  15503. Object.defineProperty(AbstractMesh.prototype, "material", {
  15504. get: function () {
  15505. return this._material;
  15506. },
  15507. set: function (value) {
  15508. if (this._material === value) {
  15509. return;
  15510. }
  15511. this._material = value;
  15512. if (this.onMaterialChangedObservable.hasObservers) {
  15513. this.onMaterialChangedObservable.notifyObservers(this);
  15514. }
  15515. if (!this.subMeshes) {
  15516. return;
  15517. }
  15518. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15519. var subMesh = _a[_i];
  15520. subMesh.setEffect(null);
  15521. }
  15522. },
  15523. enumerable: true,
  15524. configurable: true
  15525. });
  15526. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  15527. get: function () {
  15528. return this._receiveShadows;
  15529. },
  15530. set: function (value) {
  15531. if (this._receiveShadows === value) {
  15532. return;
  15533. }
  15534. this._receiveShadows = value;
  15535. this._markSubMeshesAsLightDirty();
  15536. },
  15537. enumerable: true,
  15538. configurable: true
  15539. });
  15540. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  15541. get: function () {
  15542. return this._hasVertexAlpha;
  15543. },
  15544. set: function (value) {
  15545. if (this._hasVertexAlpha === value) {
  15546. return;
  15547. }
  15548. this._hasVertexAlpha = value;
  15549. this._markSubMeshesAsAttributesDirty();
  15550. },
  15551. enumerable: true,
  15552. configurable: true
  15553. });
  15554. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  15555. get: function () {
  15556. return this._useVertexColors;
  15557. },
  15558. set: function (value) {
  15559. if (this._useVertexColors === value) {
  15560. return;
  15561. }
  15562. this._useVertexColors = value;
  15563. this._markSubMeshesAsAttributesDirty();
  15564. },
  15565. enumerable: true,
  15566. configurable: true
  15567. });
  15568. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  15569. get: function () {
  15570. return this._computeBonesUsingShaders;
  15571. },
  15572. set: function (value) {
  15573. if (this._computeBonesUsingShaders === value) {
  15574. return;
  15575. }
  15576. this._computeBonesUsingShaders = value;
  15577. this._markSubMeshesAsAttributesDirty();
  15578. },
  15579. enumerable: true,
  15580. configurable: true
  15581. });
  15582. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  15583. get: function () {
  15584. return this._numBoneInfluencers;
  15585. },
  15586. set: function (value) {
  15587. if (this._numBoneInfluencers === value) {
  15588. return;
  15589. }
  15590. this._numBoneInfluencers = value;
  15591. this._markSubMeshesAsAttributesDirty();
  15592. },
  15593. enumerable: true,
  15594. configurable: true
  15595. });
  15596. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  15597. get: function () {
  15598. return this._applyFog;
  15599. },
  15600. set: function (value) {
  15601. if (this._applyFog === value) {
  15602. return;
  15603. }
  15604. this._applyFog = value;
  15605. this._markSubMeshesAsMiscDirty();
  15606. },
  15607. enumerable: true,
  15608. configurable: true
  15609. });
  15610. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  15611. get: function () {
  15612. return this._layerMask;
  15613. },
  15614. set: function (value) {
  15615. if (value === this._layerMask) {
  15616. return;
  15617. }
  15618. this._layerMask = value;
  15619. this._resyncLightSources();
  15620. },
  15621. enumerable: true,
  15622. configurable: true
  15623. });
  15624. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  15625. get: function () {
  15626. return this._collisionMask;
  15627. },
  15628. set: function (mask) {
  15629. this._collisionMask = !isNaN(mask) ? mask : -1;
  15630. },
  15631. enumerable: true,
  15632. configurable: true
  15633. });
  15634. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  15635. get: function () {
  15636. return this._collisionGroup;
  15637. },
  15638. set: function (mask) {
  15639. this._collisionGroup = !isNaN(mask) ? mask : -1;
  15640. },
  15641. enumerable: true,
  15642. configurable: true
  15643. });
  15644. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  15645. get: function () {
  15646. return null;
  15647. },
  15648. enumerable: true,
  15649. configurable: true
  15650. });
  15651. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  15652. get: function () {
  15653. return this._skeleton;
  15654. },
  15655. set: function (value) {
  15656. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  15657. this._skeleton._unregisterMeshWithPoseMatrix(this);
  15658. }
  15659. if (value && value.needInitialSkinMatrix) {
  15660. value._registerMeshWithPoseMatrix(this);
  15661. }
  15662. this._skeleton = value;
  15663. if (!this._skeleton) {
  15664. this._bonesTransformMatrices = null;
  15665. }
  15666. this._markSubMeshesAsAttributesDirty();
  15667. },
  15668. enumerable: true,
  15669. configurable: true
  15670. });
  15671. /**
  15672. * Boolean : true if the mesh has been disposed.
  15673. */
  15674. AbstractMesh.prototype.isDisposed = function () {
  15675. return this._isDisposed;
  15676. };
  15677. /**
  15678. * Returns the string "AbstractMesh"
  15679. */
  15680. AbstractMesh.prototype.getClassName = function () {
  15681. return "AbstractMesh";
  15682. };
  15683. /**
  15684. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15685. */
  15686. AbstractMesh.prototype.toString = function (fullDetails) {
  15687. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  15688. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  15689. if (this._skeleton) {
  15690. ret += ", skeleton: " + this._skeleton.name;
  15691. }
  15692. if (fullDetails) {
  15693. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  15694. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  15695. }
  15696. return ret;
  15697. };
  15698. AbstractMesh.prototype._rebuild = function () {
  15699. if (this._occlusionQuery) {
  15700. this._occlusionQuery = null;
  15701. }
  15702. if (this._edgesRenderer) {
  15703. this._edgesRenderer._rebuild();
  15704. }
  15705. if (!this.subMeshes) {
  15706. return;
  15707. }
  15708. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15709. var subMesh = _a[_i];
  15710. subMesh._rebuild();
  15711. }
  15712. };
  15713. AbstractMesh.prototype._resyncLightSources = function () {
  15714. this._lightSources.length = 0;
  15715. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  15716. var light = _a[_i];
  15717. if (!light.isEnabled()) {
  15718. continue;
  15719. }
  15720. if (light.canAffectMesh(this)) {
  15721. this._lightSources.push(light);
  15722. }
  15723. }
  15724. this._markSubMeshesAsLightDirty();
  15725. };
  15726. AbstractMesh.prototype._resyncLighSource = function (light) {
  15727. var isIn = light.isEnabled() && light.canAffectMesh(this);
  15728. var index = this._lightSources.indexOf(light);
  15729. if (index === -1) {
  15730. if (!isIn) {
  15731. return;
  15732. }
  15733. this._lightSources.push(light);
  15734. }
  15735. else {
  15736. if (isIn) {
  15737. return;
  15738. }
  15739. this._lightSources.splice(index, 1);
  15740. }
  15741. this._markSubMeshesAsLightDirty();
  15742. };
  15743. AbstractMesh.prototype._removeLightSource = function (light) {
  15744. var index = this._lightSources.indexOf(light);
  15745. if (index === -1) {
  15746. return;
  15747. }
  15748. this._lightSources.splice(index, 1);
  15749. };
  15750. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  15751. if (!this.subMeshes) {
  15752. return;
  15753. }
  15754. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15755. var subMesh = _a[_i];
  15756. if (subMesh._materialDefines) {
  15757. func(subMesh._materialDefines);
  15758. }
  15759. }
  15760. };
  15761. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  15762. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  15763. };
  15764. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  15765. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  15766. };
  15767. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  15768. if (!this.subMeshes) {
  15769. return;
  15770. }
  15771. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15772. var subMesh = _a[_i];
  15773. var material = subMesh.getMaterial();
  15774. if (material) {
  15775. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  15776. }
  15777. }
  15778. };
  15779. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  15780. /**
  15781. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15782. * Default : (1.0, 1.0, 1.0)
  15783. */
  15784. get: function () {
  15785. return this._scaling;
  15786. },
  15787. /**
  15788. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15789. * Default : (1.0, 1.0, 1.0)
  15790. */
  15791. set: function (newScaling) {
  15792. this._scaling = newScaling;
  15793. if (this.physicsImpostor) {
  15794. this.physicsImpostor.forceUpdate();
  15795. }
  15796. },
  15797. enumerable: true,
  15798. configurable: true
  15799. });
  15800. // Methods
  15801. /**
  15802. * Disables the mesh edger rendering mode.
  15803. * Returns the AbstractMesh.
  15804. */
  15805. AbstractMesh.prototype.disableEdgesRendering = function () {
  15806. if (this._edgesRenderer) {
  15807. this._edgesRenderer.dispose();
  15808. this._edgesRenderer = null;
  15809. }
  15810. return this;
  15811. };
  15812. /**
  15813. * Enables the edge rendering mode on the mesh.
  15814. * This mode makes the mesh edges visible.
  15815. * Returns the AbstractMesh.
  15816. */
  15817. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  15818. if (epsilon === void 0) { epsilon = 0.95; }
  15819. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  15820. this.disableEdgesRendering();
  15821. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  15822. return this;
  15823. };
  15824. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  15825. /**
  15826. * Returns true if the mesh is blocked. Used by the class Mesh.
  15827. * Returns the boolean `false` by default.
  15828. */
  15829. get: function () {
  15830. return false;
  15831. },
  15832. enumerable: true,
  15833. configurable: true
  15834. });
  15835. /**
  15836. * Returns the mesh itself by default, used by the class Mesh.
  15837. * Returned type : AbstractMesh
  15838. */
  15839. AbstractMesh.prototype.getLOD = function (camera) {
  15840. return this;
  15841. };
  15842. /**
  15843. * Returns 0 by default, used by the class Mesh.
  15844. * Returns an integer.
  15845. */
  15846. AbstractMesh.prototype.getTotalVertices = function () {
  15847. return 0;
  15848. };
  15849. /**
  15850. * Returns null by default, used by the class Mesh.
  15851. * Returned type : integer array
  15852. */
  15853. AbstractMesh.prototype.getIndices = function () {
  15854. return null;
  15855. };
  15856. /**
  15857. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  15858. * Returned type : float array or Float32Array
  15859. */
  15860. AbstractMesh.prototype.getVerticesData = function (kind) {
  15861. return null;
  15862. };
  15863. /**
  15864. * Sets the vertex data of the mesh geometry for the requested `kind`.
  15865. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  15866. * The `data` are either a numeric array either a Float32Array.
  15867. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  15868. * 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).
  15869. * Note that a new underlying VertexBuffer object is created each call.
  15870. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  15871. *
  15872. * Possible `kind` values :
  15873. * - BABYLON.VertexBuffer.PositionKind
  15874. * - BABYLON.VertexBuffer.UVKind
  15875. * - BABYLON.VertexBuffer.UV2Kind
  15876. * - BABYLON.VertexBuffer.UV3Kind
  15877. * - BABYLON.VertexBuffer.UV4Kind
  15878. * - BABYLON.VertexBuffer.UV5Kind
  15879. * - BABYLON.VertexBuffer.UV6Kind
  15880. * - BABYLON.VertexBuffer.ColorKind
  15881. * - BABYLON.VertexBuffer.MatricesIndicesKind
  15882. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  15883. * - BABYLON.VertexBuffer.MatricesWeightsKind
  15884. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  15885. *
  15886. * Returns the Mesh.
  15887. */
  15888. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  15889. return this;
  15890. };
  15891. /**
  15892. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  15893. * If the mesh has no geometry, it is simply returned as it is.
  15894. * The `data` are either a numeric array either a Float32Array.
  15895. * No new underlying VertexBuffer object is created.
  15896. * 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.
  15897. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  15898. *
  15899. * Possible `kind` values :
  15900. * - BABYLON.VertexBuffer.PositionKind
  15901. * - BABYLON.VertexBuffer.UVKind
  15902. * - BABYLON.VertexBuffer.UV2Kind
  15903. * - BABYLON.VertexBuffer.UV3Kind
  15904. * - BABYLON.VertexBuffer.UV4Kind
  15905. * - BABYLON.VertexBuffer.UV5Kind
  15906. * - BABYLON.VertexBuffer.UV6Kind
  15907. * - BABYLON.VertexBuffer.ColorKind
  15908. * - BABYLON.VertexBuffer.MatricesIndicesKind
  15909. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  15910. * - BABYLON.VertexBuffer.MatricesWeightsKind
  15911. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  15912. *
  15913. * Returns the Mesh.
  15914. */
  15915. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  15916. return this;
  15917. };
  15918. /**
  15919. * Sets the mesh indices.
  15920. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  15921. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  15922. * This method creates a new index buffer each call.
  15923. * Returns the Mesh.
  15924. */
  15925. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  15926. return this;
  15927. };
  15928. /** Returns false by default, used by the class Mesh.
  15929. * Returns a boolean
  15930. */
  15931. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  15932. return false;
  15933. };
  15934. /**
  15935. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  15936. * Returns a BoundingInfo
  15937. */
  15938. AbstractMesh.prototype.getBoundingInfo = function () {
  15939. if (this._masterMesh) {
  15940. return this._masterMesh.getBoundingInfo();
  15941. }
  15942. if (!this._boundingInfo) {
  15943. // this._boundingInfo is being created here
  15944. this._updateBoundingInfo();
  15945. }
  15946. // cannot be null.
  15947. return this._boundingInfo;
  15948. };
  15949. /**
  15950. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  15951. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  15952. */
  15953. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  15954. if (includeDescendants === void 0) { includeDescendants = true; }
  15955. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  15956. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  15957. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  15958. if (maxDimension === 0) {
  15959. return this;
  15960. }
  15961. var scale = 1 / maxDimension;
  15962. this.scaling.scaleInPlace(scale);
  15963. return this;
  15964. };
  15965. /**
  15966. * Sets a mesh new object BoundingInfo.
  15967. * Returns the AbstractMesh.
  15968. */
  15969. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  15970. this._boundingInfo = boundingInfo;
  15971. return this;
  15972. };
  15973. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  15974. get: function () {
  15975. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  15976. },
  15977. enumerable: true,
  15978. configurable: true
  15979. });
  15980. AbstractMesh.prototype._preActivate = function () {
  15981. };
  15982. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  15983. };
  15984. AbstractMesh.prototype._activate = function (renderId) {
  15985. this._renderId = renderId;
  15986. };
  15987. /**
  15988. * Returns the latest update of the World matrix
  15989. * Returns a Matrix.
  15990. */
  15991. AbstractMesh.prototype.getWorldMatrix = function () {
  15992. if (this._masterMesh) {
  15993. return this._masterMesh.getWorldMatrix();
  15994. }
  15995. return _super.prototype.getWorldMatrix.call(this);
  15996. };
  15997. /**
  15998. * Returns the latest update of the World matrix determinant.
  15999. */
  16000. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  16001. if (this._masterMesh) {
  16002. return this._masterMesh._getWorldMatrixDeterminant();
  16003. }
  16004. return _super.prototype._getWorldMatrixDeterminant.call(this);
  16005. };
  16006. // ================================== Point of View Movement =================================
  16007. /**
  16008. * Perform relative position change from the point of view of behind the front of the mesh.
  16009. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16010. * Supports definition of mesh facing forward or backward.
  16011. * @param {number} amountRight
  16012. * @param {number} amountUp
  16013. * @param {number} amountForward
  16014. *
  16015. * Returns the AbstractMesh.
  16016. */
  16017. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  16018. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  16019. return this;
  16020. };
  16021. /**
  16022. * Calculate relative position change from the point of view of behind the front of the mesh.
  16023. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16024. * Supports definition of mesh facing forward or backward.
  16025. * @param {number} amountRight
  16026. * @param {number} amountUp
  16027. * @param {number} amountForward
  16028. *
  16029. * Returns a new Vector3.
  16030. */
  16031. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  16032. var rotMatrix = new BABYLON.Matrix();
  16033. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16034. rotQuaternion.toRotationMatrix(rotMatrix);
  16035. var translationDelta = BABYLON.Vector3.Zero();
  16036. var defForwardMult = this.definedFacingForward ? -1 : 1;
  16037. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  16038. return translationDelta;
  16039. };
  16040. // ================================== Point of View Rotation =================================
  16041. /**
  16042. * Perform relative rotation change from the point of view of behind the front of the mesh.
  16043. * Supports definition of mesh facing forward or backward.
  16044. * @param {number} flipBack
  16045. * @param {number} twirlClockwise
  16046. * @param {number} tiltRight
  16047. *
  16048. * Returns the AbstractMesh.
  16049. */
  16050. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16051. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  16052. return this;
  16053. };
  16054. /**
  16055. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  16056. * Supports definition of mesh facing forward or backward.
  16057. * @param {number} flipBack
  16058. * @param {number} twirlClockwise
  16059. * @param {number} tiltRight
  16060. *
  16061. * Returns a new Vector3.
  16062. */
  16063. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16064. var defForwardMult = this.definedFacingForward ? 1 : -1;
  16065. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  16066. };
  16067. /**
  16068. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  16069. * @param includeDescendants Include bounding info from descendants as well (true by default).
  16070. */
  16071. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  16072. if (includeDescendants === void 0) { includeDescendants = true; }
  16073. this.computeWorldMatrix(true);
  16074. var min;
  16075. var max;
  16076. var boundingInfo = this.getBoundingInfo();
  16077. if (!this.subMeshes) {
  16078. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16079. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16080. }
  16081. else {
  16082. min = boundingInfo.boundingBox.minimumWorld;
  16083. max = boundingInfo.boundingBox.maximumWorld;
  16084. }
  16085. if (includeDescendants) {
  16086. var descendants = this.getDescendants(false);
  16087. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  16088. var descendant = descendants_1[_i];
  16089. var childMesh = descendant;
  16090. childMesh.computeWorldMatrix(true);
  16091. //make sure we have the needed params to get mix and max
  16092. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  16093. continue;
  16094. }
  16095. var childBoundingInfo = childMesh.getBoundingInfo();
  16096. var boundingBox = childBoundingInfo.boundingBox;
  16097. var minBox = boundingBox.minimumWorld;
  16098. var maxBox = boundingBox.maximumWorld;
  16099. BABYLON.Tools.CheckExtends(minBox, min, max);
  16100. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16101. }
  16102. }
  16103. return {
  16104. min: min,
  16105. max: max
  16106. };
  16107. };
  16108. /**
  16109. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  16110. * Returns the AbstractMesh.
  16111. */
  16112. AbstractMesh.prototype._updateBoundingInfo = function () {
  16113. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  16114. this._boundingInfo.update(this.worldMatrixFromCache);
  16115. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16116. return this;
  16117. };
  16118. /**
  16119. * Update a mesh's children BoundingInfo objects only.
  16120. * Returns the AbstractMesh.
  16121. */
  16122. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  16123. if (!this.subMeshes) {
  16124. return this;
  16125. }
  16126. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  16127. var subMesh = this.subMeshes[subIndex];
  16128. if (!subMesh.IsGlobal) {
  16129. subMesh.updateBoundingInfo(matrix);
  16130. }
  16131. }
  16132. return this;
  16133. };
  16134. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  16135. // Bounding info
  16136. this._updateBoundingInfo();
  16137. };
  16138. /**
  16139. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  16140. * A mesh is in the frustum if its bounding box intersects the frustum.
  16141. * Boolean returned.
  16142. */
  16143. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  16144. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  16145. };
  16146. /**
  16147. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  16148. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  16149. * Boolean returned.
  16150. */
  16151. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16152. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  16153. ;
  16154. };
  16155. /**
  16156. * True if the mesh intersects another mesh or a SolidParticle object.
  16157. * 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)
  16158. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  16159. * Returns a boolean.
  16160. */
  16161. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  16162. if (precise === void 0) { precise = false; }
  16163. if (!this._boundingInfo || !mesh._boundingInfo) {
  16164. return false;
  16165. }
  16166. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  16167. return true;
  16168. }
  16169. if (includeDescendants) {
  16170. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  16171. var child = _a[_i];
  16172. if (child.intersectsMesh(mesh, precise, true)) {
  16173. return true;
  16174. }
  16175. }
  16176. }
  16177. return false;
  16178. };
  16179. /**
  16180. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  16181. * Returns a boolean.
  16182. */
  16183. AbstractMesh.prototype.intersectsPoint = function (point) {
  16184. if (!this._boundingInfo) {
  16185. return false;
  16186. }
  16187. return this._boundingInfo.intersectsPoint(point);
  16188. };
  16189. AbstractMesh.prototype.getPhysicsImpostor = function () {
  16190. return this.physicsImpostor;
  16191. };
  16192. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  16193. if (camera === void 0) { camera = null; }
  16194. if (!camera) {
  16195. camera = this.getScene().activeCamera;
  16196. }
  16197. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  16198. };
  16199. /**
  16200. * Returns the distance from the mesh to the active camera.
  16201. * Returns a float.
  16202. */
  16203. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  16204. if (camera === void 0) { camera = null; }
  16205. if (!camera) {
  16206. camera = this.getScene().activeCamera;
  16207. }
  16208. return this.absolutePosition.subtract(camera.position).length();
  16209. };
  16210. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  16211. if (!this.physicsImpostor) {
  16212. return this;
  16213. }
  16214. this.physicsImpostor.applyImpulse(force, contactPoint);
  16215. return this;
  16216. };
  16217. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  16218. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  16219. return this;
  16220. }
  16221. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  16222. mainPivot: pivot1,
  16223. connectedPivot: pivot2,
  16224. nativeParams: options
  16225. });
  16226. return this;
  16227. };
  16228. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  16229. // Collisions
  16230. /**
  16231. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  16232. * Default `false`.
  16233. */
  16234. get: function () {
  16235. return this._checkCollisions;
  16236. },
  16237. set: function (collisionEnabled) {
  16238. this._checkCollisions = collisionEnabled;
  16239. if (this.getScene().workerCollisions) {
  16240. this.getScene().collisionCoordinator.onMeshUpdated(this);
  16241. }
  16242. },
  16243. enumerable: true,
  16244. configurable: true
  16245. });
  16246. Object.defineProperty(AbstractMesh.prototype, "collider", {
  16247. /**
  16248. * Gets Collider object used to compute collisions (not physics)
  16249. */
  16250. get: function () {
  16251. return this._collider;
  16252. },
  16253. enumerable: true,
  16254. configurable: true
  16255. });
  16256. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  16257. var globalPosition = this.getAbsolutePosition();
  16258. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  16259. if (!this._collider) {
  16260. this._collider = new BABYLON.Collider();
  16261. }
  16262. this._collider._radius = this.ellipsoid;
  16263. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  16264. return this;
  16265. };
  16266. // Submeshes octree
  16267. /**
  16268. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  16269. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  16270. * Returns an Octree of submeshes.
  16271. */
  16272. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  16273. if (maxCapacity === void 0) { maxCapacity = 64; }
  16274. if (maxDepth === void 0) { maxDepth = 2; }
  16275. if (!this._submeshesOctree) {
  16276. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  16277. }
  16278. this.computeWorldMatrix(true);
  16279. var boundingInfo = this.getBoundingInfo();
  16280. // Update octree
  16281. var bbox = boundingInfo.boundingBox;
  16282. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  16283. return this._submeshesOctree;
  16284. };
  16285. // Collisions
  16286. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  16287. this._generatePointsArray();
  16288. if (!this._positions) {
  16289. return this;
  16290. }
  16291. // Transformation
  16292. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  16293. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  16294. subMesh._lastColliderWorldVertices = [];
  16295. subMesh._trianglePlanes = [];
  16296. var start = subMesh.verticesStart;
  16297. var end = (subMesh.verticesStart + subMesh.verticesCount);
  16298. for (var i = start; i < end; i++) {
  16299. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  16300. }
  16301. }
  16302. // Collide
  16303. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  16304. if (collider.collisionFound) {
  16305. collider.collidedMesh = this;
  16306. }
  16307. return this;
  16308. };
  16309. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  16310. var subMeshes;
  16311. var len;
  16312. // Octrees
  16313. if (this._submeshesOctree && this.useOctreeForCollisions) {
  16314. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  16315. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  16316. len = intersections.length;
  16317. subMeshes = intersections.data;
  16318. }
  16319. else {
  16320. subMeshes = this.subMeshes;
  16321. len = subMeshes.length;
  16322. }
  16323. for (var index = 0; index < len; index++) {
  16324. var subMesh = subMeshes[index];
  16325. // Bounding test
  16326. if (len > 1 && !subMesh._checkCollision(collider))
  16327. continue;
  16328. this._collideForSubMesh(subMesh, transformMatrix, collider);
  16329. }
  16330. return this;
  16331. };
  16332. AbstractMesh.prototype._checkCollision = function (collider) {
  16333. // Bounding box test
  16334. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  16335. return this;
  16336. // Transformation matrix
  16337. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  16338. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  16339. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  16340. return this;
  16341. };
  16342. // Picking
  16343. AbstractMesh.prototype._generatePointsArray = function () {
  16344. return false;
  16345. };
  16346. /**
  16347. * Checks if the passed Ray intersects with the mesh.
  16348. * Returns an object PickingInfo.
  16349. */
  16350. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  16351. var pickingInfo = new BABYLON.PickingInfo();
  16352. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  16353. return pickingInfo;
  16354. }
  16355. if (!this._generatePointsArray()) {
  16356. return pickingInfo;
  16357. }
  16358. var intersectInfo = null;
  16359. // Octrees
  16360. var subMeshes;
  16361. var len;
  16362. if (this._submeshesOctree && this.useOctreeForPicking) {
  16363. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  16364. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  16365. len = intersections.length;
  16366. subMeshes = intersections.data;
  16367. }
  16368. else {
  16369. subMeshes = this.subMeshes;
  16370. len = subMeshes.length;
  16371. }
  16372. for (var index = 0; index < len; index++) {
  16373. var subMesh = subMeshes[index];
  16374. // Bounding test
  16375. if (len > 1 && !subMesh.canIntersects(ray))
  16376. continue;
  16377. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  16378. if (currentIntersectInfo) {
  16379. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16380. intersectInfo = currentIntersectInfo;
  16381. intersectInfo.subMeshId = index;
  16382. if (fastCheck) {
  16383. break;
  16384. }
  16385. }
  16386. }
  16387. }
  16388. if (intersectInfo) {
  16389. // Get picked point
  16390. var world = this.getWorldMatrix();
  16391. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  16392. var direction = ray.direction.clone();
  16393. direction = direction.scale(intersectInfo.distance);
  16394. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  16395. var pickedPoint = worldOrigin.add(worldDirection);
  16396. // Return result
  16397. pickingInfo.hit = true;
  16398. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  16399. pickingInfo.pickedPoint = pickedPoint;
  16400. pickingInfo.pickedMesh = this;
  16401. pickingInfo.bu = intersectInfo.bu || 0;
  16402. pickingInfo.bv = intersectInfo.bv || 0;
  16403. pickingInfo.faceId = intersectInfo.faceId;
  16404. pickingInfo.subMeshId = intersectInfo.subMeshId;
  16405. return pickingInfo;
  16406. }
  16407. return pickingInfo;
  16408. };
  16409. /**
  16410. * Clones the mesh, used by the class Mesh.
  16411. * Just returns `null` for an AbstractMesh.
  16412. */
  16413. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16414. return null;
  16415. };
  16416. /**
  16417. * Disposes all the mesh submeshes.
  16418. * Returns the AbstractMesh.
  16419. */
  16420. AbstractMesh.prototype.releaseSubMeshes = function () {
  16421. if (this.subMeshes) {
  16422. while (this.subMeshes.length) {
  16423. this.subMeshes[0].dispose();
  16424. }
  16425. }
  16426. else {
  16427. this.subMeshes = new Array();
  16428. }
  16429. return this;
  16430. };
  16431. /**
  16432. * Disposes the AbstractMesh.
  16433. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  16434. * Returns nothing.
  16435. */
  16436. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16437. var _this = this;
  16438. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16439. var index;
  16440. // Action manager
  16441. if (this.actionManager !== undefined && this.actionManager !== null) {
  16442. this.actionManager.dispose();
  16443. this.actionManager = null;
  16444. }
  16445. // Skeleton
  16446. this.skeleton = null;
  16447. // Physics
  16448. if (this.physicsImpostor) {
  16449. this.physicsImpostor.dispose();
  16450. }
  16451. // Intersections in progress
  16452. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  16453. var other = this._intersectionsInProgress[index];
  16454. var pos = other._intersectionsInProgress.indexOf(this);
  16455. other._intersectionsInProgress.splice(pos, 1);
  16456. }
  16457. this._intersectionsInProgress = [];
  16458. // Lights
  16459. var lights = this.getScene().lights;
  16460. lights.forEach(function (light) {
  16461. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  16462. if (meshIndex !== -1) {
  16463. light.includedOnlyMeshes.splice(meshIndex, 1);
  16464. }
  16465. meshIndex = light.excludedMeshes.indexOf(_this);
  16466. if (meshIndex !== -1) {
  16467. light.excludedMeshes.splice(meshIndex, 1);
  16468. }
  16469. // Shadow generators
  16470. var generator = light.getShadowGenerator();
  16471. if (generator) {
  16472. var shadowMap = generator.getShadowMap();
  16473. if (shadowMap && shadowMap.renderList) {
  16474. meshIndex = shadowMap.renderList.indexOf(_this);
  16475. if (meshIndex !== -1) {
  16476. shadowMap.renderList.splice(meshIndex, 1);
  16477. }
  16478. }
  16479. }
  16480. });
  16481. // Edges
  16482. if (this._edgesRenderer) {
  16483. this._edgesRenderer.dispose();
  16484. this._edgesRenderer = null;
  16485. }
  16486. // SubMeshes
  16487. if (this.getClassName() !== "InstancedMesh") {
  16488. this.releaseSubMeshes();
  16489. }
  16490. // Octree
  16491. var sceneOctree = this.getScene().selectionOctree;
  16492. if (sceneOctree !== undefined && sceneOctree !== null) {
  16493. var index = sceneOctree.dynamicContent.indexOf(this);
  16494. if (index !== -1) {
  16495. sceneOctree.dynamicContent.splice(index, 1);
  16496. }
  16497. }
  16498. // Query
  16499. var engine = this.getScene().getEngine();
  16500. if (this._occlusionQuery) {
  16501. this._isOcclusionQueryInProgress = false;
  16502. engine.deleteQuery(this._occlusionQuery);
  16503. this._occlusionQuery = null;
  16504. }
  16505. // Engine
  16506. engine.wipeCaches();
  16507. // Remove from scene
  16508. this.getScene().removeMesh(this);
  16509. if (disposeMaterialAndTextures) {
  16510. if (this.material) {
  16511. this.material.dispose(false, true);
  16512. }
  16513. }
  16514. if (!doNotRecurse) {
  16515. // Particles
  16516. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  16517. if (this.getScene().particleSystems[index].emitter === this) {
  16518. this.getScene().particleSystems[index].dispose();
  16519. index--;
  16520. }
  16521. }
  16522. }
  16523. // facet data
  16524. if (this._facetDataEnabled) {
  16525. this.disableFacetData();
  16526. }
  16527. this.onAfterWorldMatrixUpdateObservable.clear();
  16528. this.onCollideObservable.clear();
  16529. this.onCollisionPositionChangeObservable.clear();
  16530. this._isDisposed = true;
  16531. _super.prototype.dispose.call(this, doNotRecurse);
  16532. };
  16533. /**
  16534. * Adds the passed mesh as a child to the current mesh.
  16535. * Returns the AbstractMesh.
  16536. */
  16537. AbstractMesh.prototype.addChild = function (mesh) {
  16538. mesh.setParent(this);
  16539. return this;
  16540. };
  16541. /**
  16542. * Removes the passed mesh from the current mesh children list.
  16543. * Returns the AbstractMesh.
  16544. */
  16545. AbstractMesh.prototype.removeChild = function (mesh) {
  16546. mesh.setParent(null);
  16547. return this;
  16548. };
  16549. // Facet data
  16550. /**
  16551. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  16552. * Returns the AbstractMesh.
  16553. */
  16554. AbstractMesh.prototype._initFacetData = function () {
  16555. if (!this._facetNormals) {
  16556. this._facetNormals = new Array();
  16557. }
  16558. if (!this._facetPositions) {
  16559. this._facetPositions = new Array();
  16560. }
  16561. if (!this._facetPartitioning) {
  16562. this._facetPartitioning = new Array();
  16563. }
  16564. this._facetNb = (this.getIndices().length / 3) | 0;
  16565. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  16566. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  16567. for (var f = 0; f < this._facetNb; f++) {
  16568. this._facetNormals[f] = BABYLON.Vector3.Zero();
  16569. this._facetPositions[f] = BABYLON.Vector3.Zero();
  16570. }
  16571. this._facetDataEnabled = true;
  16572. return this;
  16573. };
  16574. /**
  16575. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  16576. * This method can be called within the render loop.
  16577. * 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.
  16578. * Returns the AbstractMesh.
  16579. */
  16580. AbstractMesh.prototype.updateFacetData = function () {
  16581. if (!this._facetDataEnabled) {
  16582. this._initFacetData();
  16583. }
  16584. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16585. var indices = this.getIndices();
  16586. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16587. var bInfo = this.getBoundingInfo();
  16588. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  16589. // init arrays, matrix and sort function on first call
  16590. this._facetDepthSortEnabled = true;
  16591. if (indices instanceof Uint16Array) {
  16592. this._depthSortedIndices = new Uint16Array(indices);
  16593. }
  16594. else if (indices instanceof Uint32Array) {
  16595. this._depthSortedIndices = new Uint32Array(indices);
  16596. }
  16597. else {
  16598. var needs32bits = false;
  16599. for (var i = 0; i < indices.length; i++) {
  16600. if (indices[i] > 65535) {
  16601. needs32bits = true;
  16602. break;
  16603. }
  16604. }
  16605. if (needs32bits) {
  16606. this._depthSortedIndices = new Uint32Array(indices);
  16607. }
  16608. else {
  16609. this._depthSortedIndices = new Uint16Array(indices);
  16610. }
  16611. }
  16612. this._facetDepthSortFunction = function (f1, f2) {
  16613. return (f2.sqDistance - f1.sqDistance);
  16614. };
  16615. if (!this._facetDepthSortFrom) {
  16616. var camera = this.getScene().activeCamera;
  16617. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  16618. }
  16619. this._depthSortedFacets = [];
  16620. for (var f = 0; f < this._facetNb; f++) {
  16621. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  16622. this._depthSortedFacets.push(depthSortedFacet);
  16623. }
  16624. this._invertedMatrix = BABYLON.Matrix.Identity();
  16625. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  16626. }
  16627. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  16628. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  16629. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  16630. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  16631. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  16632. this._subDiv.max = this._partitioningSubdivisions;
  16633. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  16634. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  16635. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  16636. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  16637. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  16638. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  16639. // set the parameters for ComputeNormals()
  16640. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  16641. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  16642. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  16643. this._facetParameters.bInfo = bInfo;
  16644. this._facetParameters.bbSize = this._bbSize;
  16645. this._facetParameters.subDiv = this._subDiv;
  16646. this._facetParameters.ratio = this.partitioningBBoxRatio;
  16647. this._facetParameters.depthSort = this._facetDepthSort;
  16648. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  16649. this.computeWorldMatrix(true);
  16650. this._worldMatrix.invertToRef(this._invertedMatrix);
  16651. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  16652. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  16653. }
  16654. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  16655. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  16656. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  16657. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  16658. var l = (this._depthSortedIndices.length / 3) | 0;
  16659. for (var f = 0; f < l; f++) {
  16660. var sind = this._depthSortedFacets[f].ind;
  16661. this._depthSortedIndices[f * 3] = indices[sind];
  16662. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  16663. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  16664. }
  16665. this.updateIndices(this._depthSortedIndices);
  16666. }
  16667. return this;
  16668. };
  16669. /**
  16670. * Returns the facetLocalNormals array.
  16671. * The normals are expressed in the mesh local space.
  16672. */
  16673. AbstractMesh.prototype.getFacetLocalNormals = function () {
  16674. if (!this._facetNormals) {
  16675. this.updateFacetData();
  16676. }
  16677. return this._facetNormals;
  16678. };
  16679. /**
  16680. * Returns the facetLocalPositions array.
  16681. * The facet positions are expressed in the mesh local space.
  16682. */
  16683. AbstractMesh.prototype.getFacetLocalPositions = function () {
  16684. if (!this._facetPositions) {
  16685. this.updateFacetData();
  16686. }
  16687. return this._facetPositions;
  16688. };
  16689. /**
  16690. * Returns the facetLocalPartioning array.
  16691. */
  16692. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  16693. if (!this._facetPartitioning) {
  16694. this.updateFacetData();
  16695. }
  16696. return this._facetPartitioning;
  16697. };
  16698. /**
  16699. * Returns the i-th facet position in the world system.
  16700. * This method allocates a new Vector3 per call.
  16701. */
  16702. AbstractMesh.prototype.getFacetPosition = function (i) {
  16703. var pos = BABYLON.Vector3.Zero();
  16704. this.getFacetPositionToRef(i, pos);
  16705. return pos;
  16706. };
  16707. /**
  16708. * Sets the reference Vector3 with the i-th facet position in the world system.
  16709. * Returns the AbstractMesh.
  16710. */
  16711. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  16712. var localPos = (this.getFacetLocalPositions())[i];
  16713. var world = this.getWorldMatrix();
  16714. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  16715. return this;
  16716. };
  16717. /**
  16718. * Returns the i-th facet normal in the world system.
  16719. * This method allocates a new Vector3 per call.
  16720. */
  16721. AbstractMesh.prototype.getFacetNormal = function (i) {
  16722. var norm = BABYLON.Vector3.Zero();
  16723. this.getFacetNormalToRef(i, norm);
  16724. return norm;
  16725. };
  16726. /**
  16727. * Sets the reference Vector3 with the i-th facet normal in the world system.
  16728. * Returns the AbstractMesh.
  16729. */
  16730. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  16731. var localNorm = (this.getFacetLocalNormals())[i];
  16732. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  16733. return this;
  16734. };
  16735. /**
  16736. * 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).
  16737. */
  16738. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  16739. var bInfo = this.getBoundingInfo();
  16740. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  16741. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  16742. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  16743. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  16744. return null;
  16745. }
  16746. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  16747. };
  16748. /**
  16749. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  16750. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  16751. * 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.
  16752. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  16753. * 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.
  16754. */
  16755. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  16756. if (checkFace === void 0) { checkFace = false; }
  16757. if (facing === void 0) { facing = true; }
  16758. var world = this.getWorldMatrix();
  16759. var invMat = BABYLON.Tmp.Matrix[5];
  16760. world.invertToRef(invMat);
  16761. var invVect = BABYLON.Tmp.Vector3[8];
  16762. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  16763. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  16764. if (projected) {
  16765. // tranform the local computed projected vector to world coordinates
  16766. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  16767. }
  16768. return closest;
  16769. };
  16770. /**
  16771. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  16772. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  16773. * 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.
  16774. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  16775. * 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.
  16776. */
  16777. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  16778. if (checkFace === void 0) { checkFace = false; }
  16779. if (facing === void 0) { facing = true; }
  16780. var closest = null;
  16781. var tmpx = 0.0;
  16782. var tmpy = 0.0;
  16783. var tmpz = 0.0;
  16784. var d = 0.0; // tmp dot facet normal * facet position
  16785. var t0 = 0.0;
  16786. var projx = 0.0;
  16787. var projy = 0.0;
  16788. var projz = 0.0;
  16789. // Get all the facets in the same partitioning block than (x, y, z)
  16790. var facetPositions = this.getFacetLocalPositions();
  16791. var facetNormals = this.getFacetLocalNormals();
  16792. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  16793. if (!facetsInBlock) {
  16794. return null;
  16795. }
  16796. // Get the closest facet to (x, y, z)
  16797. var shortest = Number.MAX_VALUE; // init distance vars
  16798. var tmpDistance = shortest;
  16799. var fib; // current facet in the block
  16800. var norm; // current facet normal
  16801. var p0; // current facet barycenter position
  16802. // loop on all the facets in the current partitioning block
  16803. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  16804. fib = facetsInBlock[idx];
  16805. norm = facetNormals[fib];
  16806. p0 = facetPositions[fib];
  16807. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  16808. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  16809. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  16810. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  16811. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  16812. projx = x + norm.x * t0;
  16813. projy = y + norm.y * t0;
  16814. projz = z + norm.z * t0;
  16815. tmpx = projx - x;
  16816. tmpy = projy - y;
  16817. tmpz = projz - z;
  16818. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  16819. if (tmpDistance < shortest) {
  16820. shortest = tmpDistance;
  16821. closest = fib;
  16822. if (projected) {
  16823. projected.x = projx;
  16824. projected.y = projy;
  16825. projected.z = projz;
  16826. }
  16827. }
  16828. }
  16829. }
  16830. return closest;
  16831. };
  16832. /**
  16833. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  16834. */
  16835. AbstractMesh.prototype.getFacetDataParameters = function () {
  16836. return this._facetParameters;
  16837. };
  16838. /**
  16839. * Disables the feature FacetData and frees the related memory.
  16840. * Returns the AbstractMesh.
  16841. */
  16842. AbstractMesh.prototype.disableFacetData = function () {
  16843. if (this._facetDataEnabled) {
  16844. this._facetDataEnabled = false;
  16845. this._facetPositions = new Array();
  16846. this._facetNormals = new Array();
  16847. this._facetPartitioning = new Array();
  16848. this._facetParameters = null;
  16849. this._depthSortedIndices = new Uint32Array(0);
  16850. }
  16851. return this;
  16852. };
  16853. /**
  16854. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  16855. * Returns the mesh.
  16856. */
  16857. AbstractMesh.prototype.updateIndices = function (indices) {
  16858. return this;
  16859. };
  16860. /**
  16861. * The mesh Geometry. Actually used by the Mesh object.
  16862. * Returns a blank geometry object.
  16863. */
  16864. /**
  16865. * Creates new normals data for the mesh.
  16866. * @param updatable.
  16867. */
  16868. AbstractMesh.prototype.createNormals = function (updatable) {
  16869. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16870. var indices = this.getIndices();
  16871. var normals;
  16872. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16873. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16874. }
  16875. else {
  16876. normals = [];
  16877. }
  16878. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  16879. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  16880. };
  16881. /**
  16882. * Align the mesh with a normal.
  16883. * Returns the mesh.
  16884. */
  16885. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  16886. if (!upDirection) {
  16887. upDirection = BABYLON.Axis.Y;
  16888. }
  16889. var axisX = BABYLON.Tmp.Vector3[0];
  16890. var axisZ = BABYLON.Tmp.Vector3[1];
  16891. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  16892. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  16893. if (this.rotationQuaternion) {
  16894. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  16895. }
  16896. else {
  16897. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  16898. }
  16899. return this;
  16900. };
  16901. AbstractMesh.prototype.checkOcclusionQuery = function () {
  16902. var engine = this.getEngine();
  16903. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  16904. this._isOccluded = false;
  16905. return;
  16906. }
  16907. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  16908. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  16909. if (isOcclusionQueryAvailable) {
  16910. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  16911. this._isOcclusionQueryInProgress = false;
  16912. this._occlusionInternalRetryCounter = 0;
  16913. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  16914. }
  16915. else {
  16916. this._occlusionInternalRetryCounter++;
  16917. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  16918. this._isOcclusionQueryInProgress = false;
  16919. this._occlusionInternalRetryCounter = 0;
  16920. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  16921. // if strict continue the last state of the object.
  16922. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  16923. }
  16924. else {
  16925. return;
  16926. }
  16927. }
  16928. }
  16929. var scene = this.getScene();
  16930. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  16931. if (!this._occlusionQuery) {
  16932. this._occlusionQuery = engine.createQuery();
  16933. }
  16934. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  16935. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  16936. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  16937. this._isOcclusionQueryInProgress = true;
  16938. };
  16939. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  16940. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  16941. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  16942. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  16943. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  16944. return AbstractMesh;
  16945. }(BABYLON.TransformNode));
  16946. BABYLON.AbstractMesh = AbstractMesh;
  16947. })(BABYLON || (BABYLON = {}));
  16948. //# sourceMappingURL=babylon.abstractMesh.js.map
  16949. var BABYLON;
  16950. (function (BABYLON) {
  16951. var Light = /** @class */ (function (_super) {
  16952. __extends(Light, _super);
  16953. /**
  16954. * Creates a Light object in the scene.
  16955. * Documentation : http://doc.babylonjs.com/tutorials/lights
  16956. */
  16957. function Light(name, scene) {
  16958. var _this = _super.call(this, name, scene) || this;
  16959. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  16960. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  16961. _this.intensity = 1.0;
  16962. _this.range = Number.MAX_VALUE;
  16963. /**
  16964. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  16965. * of light.
  16966. */
  16967. _this._photometricScale = 1.0;
  16968. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  16969. _this._radius = 0.00001;
  16970. _this.renderPriority = 0;
  16971. /**
  16972. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  16973. * the current shadow generator.
  16974. */
  16975. _this.shadowEnabled = true;
  16976. _this._excludeWithLayerMask = 0;
  16977. _this._includeOnlyWithLayerMask = 0;
  16978. _this._lightmapMode = 0;
  16979. _this._excludedMeshesIds = new Array();
  16980. _this._includedOnlyMeshesIds = new Array();
  16981. _this.getScene().addLight(_this);
  16982. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  16983. _this._buildUniformLayout();
  16984. _this.includedOnlyMeshes = new Array();
  16985. _this.excludedMeshes = new Array();
  16986. _this._resyncMeshes();
  16987. return _this;
  16988. }
  16989. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  16990. /**
  16991. * If every light affecting the material is in this lightmapMode,
  16992. * material.lightmapTexture adds or multiplies
  16993. * (depends on material.useLightmapAsShadowmap)
  16994. * after every other light calculations.
  16995. */
  16996. get: function () {
  16997. return Light._LIGHTMAP_DEFAULT;
  16998. },
  16999. enumerable: true,
  17000. configurable: true
  17001. });
  17002. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  17003. /**
  17004. * material.lightmapTexture as only diffuse lighting from this light
  17005. * adds pnly specular lighting from this light
  17006. * adds dynamic shadows
  17007. */
  17008. get: function () {
  17009. return Light._LIGHTMAP_SPECULAR;
  17010. },
  17011. enumerable: true,
  17012. configurable: true
  17013. });
  17014. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  17015. /**
  17016. * material.lightmapTexture as only lighting
  17017. * no light calculation from this light
  17018. * only adds dynamic shadows from this light
  17019. */
  17020. get: function () {
  17021. return Light._LIGHTMAP_SHADOWSONLY;
  17022. },
  17023. enumerable: true,
  17024. configurable: true
  17025. });
  17026. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  17027. /**
  17028. * Each light type uses the default quantity according to its type:
  17029. * point/spot lights use luminous intensity
  17030. * directional lights use illuminance
  17031. */
  17032. get: function () {
  17033. return Light._INTENSITYMODE_AUTOMATIC;
  17034. },
  17035. enumerable: true,
  17036. configurable: true
  17037. });
  17038. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  17039. /**
  17040. * lumen (lm)
  17041. */
  17042. get: function () {
  17043. return Light._INTENSITYMODE_LUMINOUSPOWER;
  17044. },
  17045. enumerable: true,
  17046. configurable: true
  17047. });
  17048. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  17049. /**
  17050. * candela (lm/sr)
  17051. */
  17052. get: function () {
  17053. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  17054. },
  17055. enumerable: true,
  17056. configurable: true
  17057. });
  17058. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  17059. /**
  17060. * lux (lm/m^2)
  17061. */
  17062. get: function () {
  17063. return Light._INTENSITYMODE_ILLUMINANCE;
  17064. },
  17065. enumerable: true,
  17066. configurable: true
  17067. });
  17068. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  17069. /**
  17070. * nit (cd/m^2)
  17071. */
  17072. get: function () {
  17073. return Light._INTENSITYMODE_LUMINANCE;
  17074. },
  17075. enumerable: true,
  17076. configurable: true
  17077. });
  17078. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  17079. /**
  17080. * Light type const id of the point light.
  17081. */
  17082. get: function () {
  17083. return Light._LIGHTTYPEID_POINTLIGHT;
  17084. },
  17085. enumerable: true,
  17086. configurable: true
  17087. });
  17088. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  17089. /**
  17090. * Light type const id of the directional light.
  17091. */
  17092. get: function () {
  17093. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  17094. },
  17095. enumerable: true,
  17096. configurable: true
  17097. });
  17098. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  17099. /**
  17100. * Light type const id of the spot light.
  17101. */
  17102. get: function () {
  17103. return Light._LIGHTTYPEID_SPOTLIGHT;
  17104. },
  17105. enumerable: true,
  17106. configurable: true
  17107. });
  17108. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  17109. /**
  17110. * Light type const id of the hemispheric light.
  17111. */
  17112. get: function () {
  17113. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  17114. },
  17115. enumerable: true,
  17116. configurable: true
  17117. });
  17118. Object.defineProperty(Light.prototype, "intensityMode", {
  17119. /**
  17120. * Gets the photometric scale used to interpret the intensity.
  17121. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17122. */
  17123. get: function () {
  17124. return this._intensityMode;
  17125. },
  17126. /**
  17127. * Sets the photometric scale used to interpret the intensity.
  17128. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17129. */
  17130. set: function (value) {
  17131. this._intensityMode = value;
  17132. this._computePhotometricScale();
  17133. },
  17134. enumerable: true,
  17135. configurable: true
  17136. });
  17137. ;
  17138. ;
  17139. Object.defineProperty(Light.prototype, "radius", {
  17140. /**
  17141. * Gets the light radius used by PBR Materials to simulate soft area lights.
  17142. */
  17143. get: function () {
  17144. return this._radius;
  17145. },
  17146. /**
  17147. * sets the light radius used by PBR Materials to simulate soft area lights.
  17148. */
  17149. set: function (value) {
  17150. this._radius = value;
  17151. this._computePhotometricScale();
  17152. },
  17153. enumerable: true,
  17154. configurable: true
  17155. });
  17156. ;
  17157. ;
  17158. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  17159. get: function () {
  17160. return this._includedOnlyMeshes;
  17161. },
  17162. set: function (value) {
  17163. this._includedOnlyMeshes = value;
  17164. this._hookArrayForIncludedOnly(value);
  17165. },
  17166. enumerable: true,
  17167. configurable: true
  17168. });
  17169. Object.defineProperty(Light.prototype, "excludedMeshes", {
  17170. get: function () {
  17171. return this._excludedMeshes;
  17172. },
  17173. set: function (value) {
  17174. this._excludedMeshes = value;
  17175. this._hookArrayForExcluded(value);
  17176. },
  17177. enumerable: true,
  17178. configurable: true
  17179. });
  17180. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  17181. get: function () {
  17182. return this._excludeWithLayerMask;
  17183. },
  17184. set: function (value) {
  17185. this._excludeWithLayerMask = value;
  17186. this._resyncMeshes();
  17187. },
  17188. enumerable: true,
  17189. configurable: true
  17190. });
  17191. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  17192. get: function () {
  17193. return this._includeOnlyWithLayerMask;
  17194. },
  17195. set: function (value) {
  17196. this._includeOnlyWithLayerMask = value;
  17197. this._resyncMeshes();
  17198. },
  17199. enumerable: true,
  17200. configurable: true
  17201. });
  17202. Object.defineProperty(Light.prototype, "lightmapMode", {
  17203. get: function () {
  17204. return this._lightmapMode;
  17205. },
  17206. set: function (value) {
  17207. if (this._lightmapMode === value) {
  17208. return;
  17209. }
  17210. this._lightmapMode = value;
  17211. this._markMeshesAsLightDirty();
  17212. },
  17213. enumerable: true,
  17214. configurable: true
  17215. });
  17216. Light.prototype._buildUniformLayout = function () {
  17217. // Overridden
  17218. };
  17219. /**
  17220. * Returns the string "Light".
  17221. */
  17222. Light.prototype.getClassName = function () {
  17223. return "Light";
  17224. };
  17225. /**
  17226. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17227. */
  17228. Light.prototype.toString = function (fullDetails) {
  17229. var ret = "Name: " + this.name;
  17230. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  17231. if (this.animations) {
  17232. for (var i = 0; i < this.animations.length; i++) {
  17233. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17234. }
  17235. }
  17236. if (fullDetails) {
  17237. }
  17238. return ret;
  17239. };
  17240. /**
  17241. * Set the enabled state of this node.
  17242. * @param {boolean} value - the new enabled state
  17243. * @see isEnabled
  17244. */
  17245. Light.prototype.setEnabled = function (value) {
  17246. _super.prototype.setEnabled.call(this, value);
  17247. this._resyncMeshes();
  17248. };
  17249. /**
  17250. * Returns the Light associated shadow generator.
  17251. */
  17252. Light.prototype.getShadowGenerator = function () {
  17253. return this._shadowGenerator;
  17254. };
  17255. /**
  17256. * Returns a Vector3, the absolute light position in the World.
  17257. */
  17258. Light.prototype.getAbsolutePosition = function () {
  17259. return BABYLON.Vector3.Zero();
  17260. };
  17261. Light.prototype.transferToEffect = function (effect, lightIndex) {
  17262. };
  17263. Light.prototype._getWorldMatrix = function () {
  17264. return BABYLON.Matrix.Identity();
  17265. };
  17266. /**
  17267. * Boolean : True if the light will affect the passed mesh.
  17268. */
  17269. Light.prototype.canAffectMesh = function (mesh) {
  17270. if (!mesh) {
  17271. return true;
  17272. }
  17273. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  17274. return false;
  17275. }
  17276. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  17277. return false;
  17278. }
  17279. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  17280. return false;
  17281. }
  17282. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  17283. return false;
  17284. }
  17285. return true;
  17286. };
  17287. /**
  17288. * Returns the light World matrix.
  17289. */
  17290. Light.prototype.getWorldMatrix = function () {
  17291. this._currentRenderId = this.getScene().getRenderId();
  17292. var worldMatrix = this._getWorldMatrix();
  17293. if (this.parent && this.parent.getWorldMatrix) {
  17294. if (!this._parentedWorldMatrix) {
  17295. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  17296. }
  17297. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  17298. this._markSyncedWithParent();
  17299. return this._parentedWorldMatrix;
  17300. }
  17301. return worldMatrix;
  17302. };
  17303. /**
  17304. * Sort function to order lights for rendering.
  17305. * @param a First Light object to compare to second.
  17306. * @param b Second Light object to compare first.
  17307. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  17308. */
  17309. Light.compareLightsPriority = function (a, b) {
  17310. //shadow-casting lights have priority over non-shadow-casting lights
  17311. //the renderPrioirty is a secondary sort criterion
  17312. if (a.shadowEnabled !== b.shadowEnabled) {
  17313. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  17314. }
  17315. return b.renderPriority - a.renderPriority;
  17316. };
  17317. /**
  17318. * Disposes the light.
  17319. */
  17320. Light.prototype.dispose = function () {
  17321. if (this._shadowGenerator) {
  17322. this._shadowGenerator.dispose();
  17323. this._shadowGenerator = null;
  17324. }
  17325. // Animations
  17326. this.getScene().stopAnimation(this);
  17327. this._uniformBuffer.dispose();
  17328. // Remove from scene
  17329. this.getScene().removeLight(this);
  17330. _super.prototype.dispose.call(this);
  17331. };
  17332. /**
  17333. * Returns the light type ID (integer).
  17334. */
  17335. Light.prototype.getTypeID = function () {
  17336. return 0;
  17337. };
  17338. /**
  17339. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  17340. */
  17341. Light.prototype.getScaledIntensity = function () {
  17342. return this._photometricScale * this.intensity;
  17343. };
  17344. /**
  17345. * Returns a new Light object, named "name", from the current one.
  17346. */
  17347. Light.prototype.clone = function (name) {
  17348. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  17349. if (!constructor) {
  17350. return null;
  17351. }
  17352. return BABYLON.SerializationHelper.Clone(constructor, this);
  17353. };
  17354. /**
  17355. * Serializes the current light into a Serialization object.
  17356. * Returns the serialized object.
  17357. */
  17358. Light.prototype.serialize = function () {
  17359. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  17360. // Type
  17361. serializationObject.type = this.getTypeID();
  17362. // Parent
  17363. if (this.parent) {
  17364. serializationObject.parentId = this.parent.id;
  17365. }
  17366. // Inclusion / exclusions
  17367. if (this.excludedMeshes.length > 0) {
  17368. serializationObject.excludedMeshesIds = [];
  17369. this.excludedMeshes.forEach(function (mesh) {
  17370. serializationObject.excludedMeshesIds.push(mesh.id);
  17371. });
  17372. }
  17373. if (this.includedOnlyMeshes.length > 0) {
  17374. serializationObject.includedOnlyMeshesIds = [];
  17375. this.includedOnlyMeshes.forEach(function (mesh) {
  17376. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  17377. });
  17378. }
  17379. // Animations
  17380. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17381. serializationObject.ranges = this.serializeAnimationRanges();
  17382. return serializationObject;
  17383. };
  17384. /**
  17385. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  17386. * This new light is named "name" and added to the passed scene.
  17387. */
  17388. Light.GetConstructorFromName = function (type, name, scene) {
  17389. switch (type) {
  17390. case 0:
  17391. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  17392. case 1:
  17393. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  17394. case 2:
  17395. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  17396. case 3:
  17397. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  17398. }
  17399. return null;
  17400. };
  17401. /**
  17402. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  17403. */
  17404. Light.Parse = function (parsedLight, scene) {
  17405. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  17406. if (!constructor) {
  17407. return null;
  17408. }
  17409. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  17410. // Inclusion / exclusions
  17411. if (parsedLight.excludedMeshesIds) {
  17412. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  17413. }
  17414. if (parsedLight.includedOnlyMeshesIds) {
  17415. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  17416. }
  17417. // Parent
  17418. if (parsedLight.parentId) {
  17419. light._waitingParentId = parsedLight.parentId;
  17420. }
  17421. // Animations
  17422. if (parsedLight.animations) {
  17423. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  17424. var parsedAnimation = parsedLight.animations[animationIndex];
  17425. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17426. }
  17427. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  17428. }
  17429. if (parsedLight.autoAnimate) {
  17430. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  17431. }
  17432. return light;
  17433. };
  17434. Light.prototype._hookArrayForExcluded = function (array) {
  17435. var _this = this;
  17436. var oldPush = array.push;
  17437. array.push = function () {
  17438. var items = [];
  17439. for (var _i = 0; _i < arguments.length; _i++) {
  17440. items[_i] = arguments[_i];
  17441. }
  17442. var result = oldPush.apply(array, items);
  17443. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  17444. var item = items_1[_a];
  17445. item._resyncLighSource(_this);
  17446. }
  17447. return result;
  17448. };
  17449. var oldSplice = array.splice;
  17450. array.splice = function (index, deleteCount) {
  17451. var deleted = oldSplice.apply(array, [index, deleteCount]);
  17452. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  17453. var item = deleted_1[_i];
  17454. item._resyncLighSource(_this);
  17455. }
  17456. return deleted;
  17457. };
  17458. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  17459. var item = array_1[_i];
  17460. item._resyncLighSource(this);
  17461. }
  17462. };
  17463. Light.prototype._hookArrayForIncludedOnly = function (array) {
  17464. var _this = this;
  17465. var oldPush = array.push;
  17466. array.push = function () {
  17467. var items = [];
  17468. for (var _i = 0; _i < arguments.length; _i++) {
  17469. items[_i] = arguments[_i];
  17470. }
  17471. var result = oldPush.apply(array, items);
  17472. _this._resyncMeshes();
  17473. return result;
  17474. };
  17475. var oldSplice = array.splice;
  17476. array.splice = function (index, deleteCount) {
  17477. var deleted = oldSplice.apply(array, [index, deleteCount]);
  17478. _this._resyncMeshes();
  17479. return deleted;
  17480. };
  17481. this._resyncMeshes();
  17482. };
  17483. Light.prototype._resyncMeshes = function () {
  17484. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  17485. var mesh = _a[_i];
  17486. mesh._resyncLighSource(this);
  17487. }
  17488. };
  17489. Light.prototype._markMeshesAsLightDirty = function () {
  17490. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  17491. var mesh = _a[_i];
  17492. if (mesh._lightSources.indexOf(this) !== -1) {
  17493. mesh._markSubMeshesAsLightDirty();
  17494. }
  17495. }
  17496. };
  17497. /**
  17498. * Recomputes the cached photometric scale if needed.
  17499. */
  17500. Light.prototype._computePhotometricScale = function () {
  17501. this._photometricScale = this._getPhotometricScale();
  17502. this.getScene().resetCachedMaterial();
  17503. };
  17504. /**
  17505. * Returns the Photometric Scale according to the light type and intensity mode.
  17506. */
  17507. Light.prototype._getPhotometricScale = function () {
  17508. var photometricScale = 0.0;
  17509. var lightTypeID = this.getTypeID();
  17510. //get photometric mode
  17511. var photometricMode = this.intensityMode;
  17512. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  17513. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  17514. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  17515. }
  17516. else {
  17517. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  17518. }
  17519. }
  17520. //compute photometric scale
  17521. switch (lightTypeID) {
  17522. case Light.LIGHTTYPEID_POINTLIGHT:
  17523. case Light.LIGHTTYPEID_SPOTLIGHT:
  17524. switch (photometricMode) {
  17525. case Light.INTENSITYMODE_LUMINOUSPOWER:
  17526. photometricScale = 1.0 / (4.0 * Math.PI);
  17527. break;
  17528. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  17529. photometricScale = 1.0;
  17530. break;
  17531. case Light.INTENSITYMODE_LUMINANCE:
  17532. photometricScale = this.radius * this.radius;
  17533. break;
  17534. }
  17535. break;
  17536. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  17537. switch (photometricMode) {
  17538. case Light.INTENSITYMODE_ILLUMINANCE:
  17539. photometricScale = 1.0;
  17540. break;
  17541. case Light.INTENSITYMODE_LUMINANCE:
  17542. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  17543. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  17544. var apexAngleRadians = this.radius;
  17545. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  17546. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  17547. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  17548. photometricScale = solidAngle;
  17549. break;
  17550. }
  17551. break;
  17552. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  17553. // No fall off in hemisperic light.
  17554. photometricScale = 1.0;
  17555. break;
  17556. }
  17557. return photometricScale;
  17558. };
  17559. Light.prototype._reorderLightsInScene = function () {
  17560. var scene = this.getScene();
  17561. if (this._renderPriority != 0) {
  17562. scene.requireLightSorting = true;
  17563. }
  17564. this.getScene().sortLightsByPriority();
  17565. };
  17566. //lightmapMode Consts
  17567. Light._LIGHTMAP_DEFAULT = 0;
  17568. Light._LIGHTMAP_SPECULAR = 1;
  17569. Light._LIGHTMAP_SHADOWSONLY = 2;
  17570. // Intensity Mode Consts
  17571. Light._INTENSITYMODE_AUTOMATIC = 0;
  17572. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  17573. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  17574. Light._INTENSITYMODE_ILLUMINANCE = 3;
  17575. Light._INTENSITYMODE_LUMINANCE = 4;
  17576. // Light types ids const.
  17577. Light._LIGHTTYPEID_POINTLIGHT = 0;
  17578. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  17579. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  17580. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  17581. __decorate([
  17582. BABYLON.serializeAsColor3()
  17583. ], Light.prototype, "diffuse", void 0);
  17584. __decorate([
  17585. BABYLON.serializeAsColor3()
  17586. ], Light.prototype, "specular", void 0);
  17587. __decorate([
  17588. BABYLON.serialize()
  17589. ], Light.prototype, "intensity", void 0);
  17590. __decorate([
  17591. BABYLON.serialize()
  17592. ], Light.prototype, "range", void 0);
  17593. __decorate([
  17594. BABYLON.serialize()
  17595. ], Light.prototype, "intensityMode", null);
  17596. __decorate([
  17597. BABYLON.serialize()
  17598. ], Light.prototype, "radius", null);
  17599. __decorate([
  17600. BABYLON.serialize()
  17601. ], Light.prototype, "_renderPriority", void 0);
  17602. __decorate([
  17603. BABYLON.expandToProperty("_reorderLightsInScene")
  17604. ], Light.prototype, "renderPriority", void 0);
  17605. __decorate([
  17606. BABYLON.serialize()
  17607. ], Light.prototype, "shadowEnabled", void 0);
  17608. __decorate([
  17609. BABYLON.serialize("excludeWithLayerMask")
  17610. ], Light.prototype, "_excludeWithLayerMask", void 0);
  17611. __decorate([
  17612. BABYLON.serialize("includeOnlyWithLayerMask")
  17613. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  17614. __decorate([
  17615. BABYLON.serialize("lightmapMode")
  17616. ], Light.prototype, "_lightmapMode", void 0);
  17617. return Light;
  17618. }(BABYLON.Node));
  17619. BABYLON.Light = Light;
  17620. })(BABYLON || (BABYLON = {}));
  17621. //# sourceMappingURL=babylon.light.js.map
  17622. var BABYLON;
  17623. (function (BABYLON) {
  17624. var Camera = /** @class */ (function (_super) {
  17625. __extends(Camera, _super);
  17626. function Camera(name, position, scene) {
  17627. var _this = _super.call(this, name, scene) || this;
  17628. _this.upVector = BABYLON.Vector3.Up();
  17629. _this.orthoLeft = null;
  17630. _this.orthoRight = null;
  17631. _this.orthoBottom = null;
  17632. _this.orthoTop = null;
  17633. _this.fov = 0.8;
  17634. _this.minZ = 1;
  17635. _this.maxZ = 10000.0;
  17636. _this.inertia = 0.9;
  17637. _this.mode = Camera.PERSPECTIVE_CAMERA;
  17638. _this.isIntermediate = false;
  17639. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  17640. _this.layerMask = 0x0FFFFFFF;
  17641. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  17642. // Camera rig members
  17643. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  17644. _this._rigCameras = new Array();
  17645. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  17646. _this._skipRendering = false;
  17647. _this.customRenderTargets = new Array();
  17648. // Observables
  17649. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  17650. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  17651. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  17652. _this.onRestoreStateObservable = new BABYLON.Observable();
  17653. // Cache
  17654. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  17655. _this._projectionMatrix = new BABYLON.Matrix();
  17656. _this._doNotComputeProjectionMatrix = false;
  17657. _this._postProcesses = new Array();
  17658. _this._transformMatrix = BABYLON.Matrix.Zero();
  17659. _this._activeMeshes = new BABYLON.SmartArray(256);
  17660. _this._globalPosition = BABYLON.Vector3.Zero();
  17661. _this._refreshFrustumPlanes = true;
  17662. _this.getScene().addCamera(_this);
  17663. if (!_this.getScene().activeCamera) {
  17664. _this.getScene().activeCamera = _this;
  17665. }
  17666. _this.position = position;
  17667. return _this;
  17668. }
  17669. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  17670. get: function () {
  17671. return Camera._PERSPECTIVE_CAMERA;
  17672. },
  17673. enumerable: true,
  17674. configurable: true
  17675. });
  17676. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  17677. get: function () {
  17678. return Camera._ORTHOGRAPHIC_CAMERA;
  17679. },
  17680. enumerable: true,
  17681. configurable: true
  17682. });
  17683. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  17684. get: function () {
  17685. return Camera._FOVMODE_VERTICAL_FIXED;
  17686. },
  17687. enumerable: true,
  17688. configurable: true
  17689. });
  17690. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  17691. get: function () {
  17692. return Camera._FOVMODE_HORIZONTAL_FIXED;
  17693. },
  17694. enumerable: true,
  17695. configurable: true
  17696. });
  17697. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  17698. get: function () {
  17699. return Camera._RIG_MODE_NONE;
  17700. },
  17701. enumerable: true,
  17702. configurable: true
  17703. });
  17704. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  17705. get: function () {
  17706. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  17707. },
  17708. enumerable: true,
  17709. configurable: true
  17710. });
  17711. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  17712. get: function () {
  17713. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  17714. },
  17715. enumerable: true,
  17716. configurable: true
  17717. });
  17718. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  17719. get: function () {
  17720. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  17721. },
  17722. enumerable: true,
  17723. configurable: true
  17724. });
  17725. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  17726. get: function () {
  17727. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  17728. },
  17729. enumerable: true,
  17730. configurable: true
  17731. });
  17732. Object.defineProperty(Camera, "RIG_MODE_VR", {
  17733. get: function () {
  17734. return Camera._RIG_MODE_VR;
  17735. },
  17736. enumerable: true,
  17737. configurable: true
  17738. });
  17739. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  17740. get: function () {
  17741. return Camera._RIG_MODE_WEBVR;
  17742. },
  17743. enumerable: true,
  17744. configurable: true
  17745. });
  17746. /**
  17747. * Store current camera state (fov, position, etc..)
  17748. */
  17749. Camera.prototype.storeState = function () {
  17750. this._stateStored = true;
  17751. this._storedFov = this.fov;
  17752. return this;
  17753. };
  17754. /**
  17755. * Restores the camera state values if it has been stored. You must call storeState() first
  17756. */
  17757. Camera.prototype._restoreStateValues = function () {
  17758. if (!this._stateStored) {
  17759. return false;
  17760. }
  17761. this.fov = this._storedFov;
  17762. return true;
  17763. };
  17764. /**
  17765. * Restored camera state. You must call storeState() first
  17766. */
  17767. Camera.prototype.restoreState = function () {
  17768. if (this._restoreStateValues()) {
  17769. this.onRestoreStateObservable.notifyObservers(this);
  17770. return true;
  17771. }
  17772. return false;
  17773. };
  17774. Camera.prototype.getClassName = function () {
  17775. return "Camera";
  17776. };
  17777. /**
  17778. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17779. */
  17780. Camera.prototype.toString = function (fullDetails) {
  17781. var ret = "Name: " + this.name;
  17782. ret += ", type: " + this.getClassName();
  17783. if (this.animations) {
  17784. for (var i = 0; i < this.animations.length; i++) {
  17785. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17786. }
  17787. }
  17788. if (fullDetails) {
  17789. }
  17790. return ret;
  17791. };
  17792. Object.defineProperty(Camera.prototype, "globalPosition", {
  17793. get: function () {
  17794. return this._globalPosition;
  17795. },
  17796. enumerable: true,
  17797. configurable: true
  17798. });
  17799. Camera.prototype.getActiveMeshes = function () {
  17800. return this._activeMeshes;
  17801. };
  17802. Camera.prototype.isActiveMesh = function (mesh) {
  17803. return (this._activeMeshes.indexOf(mesh) !== -1);
  17804. };
  17805. //Cache
  17806. Camera.prototype._initCache = function () {
  17807. _super.prototype._initCache.call(this);
  17808. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17809. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17810. this._cache.mode = undefined;
  17811. this._cache.minZ = undefined;
  17812. this._cache.maxZ = undefined;
  17813. this._cache.fov = undefined;
  17814. this._cache.fovMode = undefined;
  17815. this._cache.aspectRatio = undefined;
  17816. this._cache.orthoLeft = undefined;
  17817. this._cache.orthoRight = undefined;
  17818. this._cache.orthoBottom = undefined;
  17819. this._cache.orthoTop = undefined;
  17820. this._cache.renderWidth = undefined;
  17821. this._cache.renderHeight = undefined;
  17822. };
  17823. Camera.prototype._updateCache = function (ignoreParentClass) {
  17824. if (!ignoreParentClass) {
  17825. _super.prototype._updateCache.call(this);
  17826. }
  17827. this._cache.position.copyFrom(this.position);
  17828. this._cache.upVector.copyFrom(this.upVector);
  17829. };
  17830. // Synchronized
  17831. Camera.prototype._isSynchronized = function () {
  17832. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  17833. };
  17834. Camera.prototype._isSynchronizedViewMatrix = function () {
  17835. if (!_super.prototype._isSynchronized.call(this))
  17836. return false;
  17837. return this._cache.position.equals(this.position)
  17838. && this._cache.upVector.equals(this.upVector)
  17839. && this.isSynchronizedWithParent();
  17840. };
  17841. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  17842. var check = this._cache.mode === this.mode
  17843. && this._cache.minZ === this.minZ
  17844. && this._cache.maxZ === this.maxZ;
  17845. if (!check) {
  17846. return false;
  17847. }
  17848. var engine = this.getEngine();
  17849. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  17850. check = this._cache.fov === this.fov
  17851. && this._cache.fovMode === this.fovMode
  17852. && this._cache.aspectRatio === engine.getAspectRatio(this);
  17853. }
  17854. else {
  17855. check = this._cache.orthoLeft === this.orthoLeft
  17856. && this._cache.orthoRight === this.orthoRight
  17857. && this._cache.orthoBottom === this.orthoBottom
  17858. && this._cache.orthoTop === this.orthoTop
  17859. && this._cache.renderWidth === engine.getRenderWidth()
  17860. && this._cache.renderHeight === engine.getRenderHeight();
  17861. }
  17862. return check;
  17863. };
  17864. // Controls
  17865. Camera.prototype.attachControl = function (element, noPreventDefault) {
  17866. };
  17867. Camera.prototype.detachControl = function (element) {
  17868. };
  17869. Camera.prototype.update = function () {
  17870. this._checkInputs();
  17871. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  17872. this._updateRigCameras();
  17873. }
  17874. };
  17875. Camera.prototype._checkInputs = function () {
  17876. this.onAfterCheckInputsObservable.notifyObservers(this);
  17877. };
  17878. Object.defineProperty(Camera.prototype, "rigCameras", {
  17879. get: function () {
  17880. return this._rigCameras;
  17881. },
  17882. enumerable: true,
  17883. configurable: true
  17884. });
  17885. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  17886. get: function () {
  17887. return this._rigPostProcess;
  17888. },
  17889. enumerable: true,
  17890. configurable: true
  17891. });
  17892. Camera.prototype._cascadePostProcessesToRigCams = function () {
  17893. // invalidate framebuffer
  17894. if (this._postProcesses.length > 0) {
  17895. this._postProcesses[0].markTextureDirty();
  17896. }
  17897. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  17898. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  17899. var cam = this._rigCameras[i];
  17900. var rigPostProcess = cam._rigPostProcess;
  17901. // for VR rig, there does not have to be a post process
  17902. if (rigPostProcess) {
  17903. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  17904. if (isPass) {
  17905. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  17906. cam.isIntermediate = this._postProcesses.length === 0;
  17907. }
  17908. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  17909. rigPostProcess.markTextureDirty();
  17910. }
  17911. else {
  17912. cam._postProcesses = this._postProcesses.slice(0);
  17913. }
  17914. }
  17915. };
  17916. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  17917. if (insertAt === void 0) { insertAt = null; }
  17918. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  17919. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  17920. return 0;
  17921. }
  17922. if (insertAt == null || insertAt < 0) {
  17923. this._postProcesses.push(postProcess);
  17924. }
  17925. else {
  17926. this._postProcesses.splice(insertAt, 0, postProcess);
  17927. }
  17928. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  17929. return this._postProcesses.indexOf(postProcess);
  17930. };
  17931. Camera.prototype.detachPostProcess = function (postProcess) {
  17932. var idx = this._postProcesses.indexOf(postProcess);
  17933. if (idx !== -1) {
  17934. this._postProcesses.splice(idx, 1);
  17935. }
  17936. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  17937. };
  17938. Camera.prototype.getWorldMatrix = function () {
  17939. if (!this._worldMatrix) {
  17940. this._worldMatrix = BABYLON.Matrix.Identity();
  17941. }
  17942. var viewMatrix = this.getViewMatrix();
  17943. viewMatrix.invertToRef(this._worldMatrix);
  17944. return this._worldMatrix;
  17945. };
  17946. Camera.prototype._getViewMatrix = function () {
  17947. return BABYLON.Matrix.Identity();
  17948. };
  17949. Camera.prototype.getViewMatrix = function (force) {
  17950. if (!force && this._isSynchronizedViewMatrix()) {
  17951. return this._computedViewMatrix;
  17952. }
  17953. this.updateCache();
  17954. this._computedViewMatrix = this._getViewMatrix();
  17955. this._currentRenderId = this.getScene().getRenderId();
  17956. this._refreshFrustumPlanes = true;
  17957. if (!this.parent || !this.parent.getWorldMatrix) {
  17958. this._globalPosition.copyFrom(this.position);
  17959. }
  17960. else {
  17961. if (!this._worldMatrix) {
  17962. this._worldMatrix = BABYLON.Matrix.Identity();
  17963. }
  17964. this._computedViewMatrix.invertToRef(this._worldMatrix);
  17965. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  17966. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  17967. this._computedViewMatrix.invert();
  17968. this._markSyncedWithParent();
  17969. }
  17970. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  17971. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  17972. }
  17973. this.onViewMatrixChangedObservable.notifyObservers(this);
  17974. return this._computedViewMatrix;
  17975. };
  17976. Camera.prototype.freezeProjectionMatrix = function (projection) {
  17977. this._doNotComputeProjectionMatrix = true;
  17978. if (projection !== undefined) {
  17979. this._projectionMatrix = projection;
  17980. }
  17981. };
  17982. ;
  17983. Camera.prototype.unfreezeProjectionMatrix = function () {
  17984. this._doNotComputeProjectionMatrix = false;
  17985. };
  17986. ;
  17987. Camera.prototype.getProjectionMatrix = function (force) {
  17988. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  17989. return this._projectionMatrix;
  17990. }
  17991. // Cache
  17992. this._cache.mode = this.mode;
  17993. this._cache.minZ = this.minZ;
  17994. this._cache.maxZ = this.maxZ;
  17995. // Matrix
  17996. this._refreshFrustumPlanes = true;
  17997. var engine = this.getEngine();
  17998. var scene = this.getScene();
  17999. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18000. this._cache.fov = this.fov;
  18001. this._cache.fovMode = this.fovMode;
  18002. this._cache.aspectRatio = engine.getAspectRatio(this);
  18003. if (this.minZ <= 0) {
  18004. this.minZ = 0.1;
  18005. }
  18006. if (scene.useRightHandedSystem) {
  18007. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18008. }
  18009. else {
  18010. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18011. }
  18012. }
  18013. else {
  18014. var halfWidth = engine.getRenderWidth() / 2.0;
  18015. var halfHeight = engine.getRenderHeight() / 2.0;
  18016. if (scene.useRightHandedSystem) {
  18017. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18018. }
  18019. else {
  18020. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18021. }
  18022. this._cache.orthoLeft = this.orthoLeft;
  18023. this._cache.orthoRight = this.orthoRight;
  18024. this._cache.orthoBottom = this.orthoBottom;
  18025. this._cache.orthoTop = this.orthoTop;
  18026. this._cache.renderWidth = engine.getRenderWidth();
  18027. this._cache.renderHeight = engine.getRenderHeight();
  18028. }
  18029. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  18030. return this._projectionMatrix;
  18031. };
  18032. Camera.prototype.getTranformationMatrix = function () {
  18033. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18034. return this._transformMatrix;
  18035. };
  18036. Camera.prototype.updateFrustumPlanes = function () {
  18037. if (!this._refreshFrustumPlanes) {
  18038. return;
  18039. }
  18040. this.getTranformationMatrix();
  18041. if (!this._frustumPlanes) {
  18042. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18043. }
  18044. else {
  18045. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18046. }
  18047. this._refreshFrustumPlanes = false;
  18048. };
  18049. Camera.prototype.isInFrustum = function (target) {
  18050. this.updateFrustumPlanes();
  18051. return target.isInFrustum(this._frustumPlanes);
  18052. };
  18053. Camera.prototype.isCompletelyInFrustum = function (target) {
  18054. this.updateFrustumPlanes();
  18055. return target.isCompletelyInFrustum(this._frustumPlanes);
  18056. };
  18057. Camera.prototype.getForwardRay = function (length, transform, origin) {
  18058. if (length === void 0) { length = 100; }
  18059. if (!transform) {
  18060. transform = this.getWorldMatrix();
  18061. }
  18062. if (!origin) {
  18063. origin = this.position;
  18064. }
  18065. var forward = new BABYLON.Vector3(0, 0, 1);
  18066. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  18067. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  18068. return new BABYLON.Ray(origin, direction, length);
  18069. };
  18070. Camera.prototype.dispose = function () {
  18071. // Observables
  18072. this.onViewMatrixChangedObservable.clear();
  18073. this.onProjectionMatrixChangedObservable.clear();
  18074. this.onAfterCheckInputsObservable.clear();
  18075. this.onRestoreStateObservable.clear();
  18076. // Inputs
  18077. if (this.inputs) {
  18078. this.inputs.clear();
  18079. }
  18080. // Animations
  18081. this.getScene().stopAnimation(this);
  18082. // Remove from scene
  18083. this.getScene().removeCamera(this);
  18084. while (this._rigCameras.length > 0) {
  18085. var camera = this._rigCameras.pop();
  18086. if (camera) {
  18087. camera.dispose();
  18088. }
  18089. }
  18090. // Postprocesses
  18091. if (this._rigPostProcess) {
  18092. this._rigPostProcess.dispose(this);
  18093. this._rigPostProcess = null;
  18094. this._postProcesses = [];
  18095. }
  18096. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18097. this._rigPostProcess = null;
  18098. this._postProcesses = [];
  18099. }
  18100. else {
  18101. var i = this._postProcesses.length;
  18102. while (--i >= 0) {
  18103. this._postProcesses[i].dispose(this);
  18104. }
  18105. }
  18106. // Render targets
  18107. var i = this.customRenderTargets.length;
  18108. while (--i >= 0) {
  18109. this.customRenderTargets[i].dispose();
  18110. }
  18111. this.customRenderTargets = [];
  18112. // Active Meshes
  18113. this._activeMeshes.dispose();
  18114. _super.prototype.dispose.call(this);
  18115. };
  18116. Object.defineProperty(Camera.prototype, "leftCamera", {
  18117. // ---- Camera rigs section ----
  18118. get: function () {
  18119. if (this._rigCameras.length < 1) {
  18120. return null;
  18121. }
  18122. return this._rigCameras[0];
  18123. },
  18124. enumerable: true,
  18125. configurable: true
  18126. });
  18127. Object.defineProperty(Camera.prototype, "rightCamera", {
  18128. get: function () {
  18129. if (this._rigCameras.length < 2) {
  18130. return null;
  18131. }
  18132. return this._rigCameras[1];
  18133. },
  18134. enumerable: true,
  18135. configurable: true
  18136. });
  18137. Camera.prototype.getLeftTarget = function () {
  18138. if (this._rigCameras.length < 1) {
  18139. return null;
  18140. }
  18141. return this._rigCameras[0].getTarget();
  18142. };
  18143. Camera.prototype.getRightTarget = function () {
  18144. if (this._rigCameras.length < 2) {
  18145. return null;
  18146. }
  18147. return this._rigCameras[1].getTarget();
  18148. };
  18149. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  18150. if (this.cameraRigMode === mode) {
  18151. return;
  18152. }
  18153. while (this._rigCameras.length > 0) {
  18154. var camera = this._rigCameras.pop();
  18155. if (camera) {
  18156. camera.dispose();
  18157. }
  18158. }
  18159. this.cameraRigMode = mode;
  18160. this._cameraRigParams = {};
  18161. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  18162. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  18163. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  18164. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  18165. // create the rig cameras, unless none
  18166. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18167. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  18168. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  18169. if (leftCamera && rightCamera) {
  18170. this._rigCameras.push(leftCamera);
  18171. this._rigCameras.push(rightCamera);
  18172. }
  18173. }
  18174. switch (this.cameraRigMode) {
  18175. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18176. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18177. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  18178. break;
  18179. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18180. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18181. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18182. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18183. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18184. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  18185. break;
  18186. case Camera.RIG_MODE_VR:
  18187. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  18188. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  18189. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18190. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18191. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  18192. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  18193. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  18194. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  18195. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18196. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18197. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  18198. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  18199. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  18200. if (metrics.compensateDistortion) {
  18201. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  18202. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  18203. }
  18204. break;
  18205. case Camera.RIG_MODE_WEBVR:
  18206. if (rigParams.vrDisplay) {
  18207. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  18208. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  18209. //Left eye
  18210. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18211. this._rigCameras[0].setCameraRigParameter("left", true);
  18212. //leaving this for future reference
  18213. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  18214. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  18215. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  18216. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18217. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18218. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18219. this._rigCameras[0].parent = this;
  18220. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  18221. //Right eye
  18222. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18223. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  18224. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  18225. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  18226. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18227. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18228. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18229. this._rigCameras[1].parent = this;
  18230. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  18231. if (Camera.UseAlternateWebVRRendering) {
  18232. this._rigCameras[1]._skipRendering = true;
  18233. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  18234. }
  18235. }
  18236. break;
  18237. }
  18238. this._cascadePostProcessesToRigCams();
  18239. this.update();
  18240. };
  18241. Camera.prototype._getVRProjectionMatrix = function () {
  18242. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  18243. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  18244. return this._projectionMatrix;
  18245. };
  18246. Camera.prototype._updateCameraRotationMatrix = function () {
  18247. //Here for WebVR
  18248. };
  18249. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  18250. //Here for WebVR
  18251. };
  18252. /**
  18253. * This function MUST be overwritten by the different WebVR cameras available.
  18254. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18255. */
  18256. Camera.prototype._getWebVRProjectionMatrix = function () {
  18257. return BABYLON.Matrix.Identity();
  18258. };
  18259. /**
  18260. * This function MUST be overwritten by the different WebVR cameras available.
  18261. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18262. */
  18263. Camera.prototype._getWebVRViewMatrix = function () {
  18264. return BABYLON.Matrix.Identity();
  18265. };
  18266. Camera.prototype.setCameraRigParameter = function (name, value) {
  18267. if (!this._cameraRigParams) {
  18268. this._cameraRigParams = {};
  18269. }
  18270. this._cameraRigParams[name] = value;
  18271. //provisionnally:
  18272. if (name === "interaxialDistance") {
  18273. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  18274. }
  18275. };
  18276. /**
  18277. * needs to be overridden by children so sub has required properties to be copied
  18278. */
  18279. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  18280. return null;
  18281. };
  18282. /**
  18283. * May need to be overridden by children
  18284. */
  18285. Camera.prototype._updateRigCameras = function () {
  18286. for (var i = 0; i < this._rigCameras.length; i++) {
  18287. this._rigCameras[i].minZ = this.minZ;
  18288. this._rigCameras[i].maxZ = this.maxZ;
  18289. this._rigCameras[i].fov = this.fov;
  18290. }
  18291. // only update viewport when ANAGLYPH
  18292. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  18293. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  18294. }
  18295. };
  18296. Camera.prototype._setupInputs = function () {
  18297. };
  18298. Camera.prototype.serialize = function () {
  18299. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18300. // Type
  18301. serializationObject.type = this.getClassName();
  18302. // Parent
  18303. if (this.parent) {
  18304. serializationObject.parentId = this.parent.id;
  18305. }
  18306. if (this.inputs) {
  18307. this.inputs.serialize(serializationObject);
  18308. }
  18309. // Animations
  18310. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18311. serializationObject.ranges = this.serializeAnimationRanges();
  18312. return serializationObject;
  18313. };
  18314. Camera.prototype.clone = function (name) {
  18315. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  18316. };
  18317. Camera.prototype.getDirection = function (localAxis) {
  18318. var result = BABYLON.Vector3.Zero();
  18319. this.getDirectionToRef(localAxis, result);
  18320. return result;
  18321. };
  18322. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  18323. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18324. };
  18325. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  18326. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  18327. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  18328. switch (type) {
  18329. case "ArcRotateCamera":
  18330. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  18331. case "DeviceOrientationCamera":
  18332. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  18333. case "FollowCamera":
  18334. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  18335. case "ArcFollowCamera":
  18336. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  18337. case "GamepadCamera":
  18338. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18339. case "TouchCamera":
  18340. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  18341. case "VirtualJoysticksCamera":
  18342. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  18343. case "WebVRFreeCamera":
  18344. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18345. case "WebVRGamepadCamera":
  18346. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18347. case "VRDeviceOrientationFreeCamera":
  18348. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18349. case "VRDeviceOrientationGamepadCamera":
  18350. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18351. case "AnaglyphArcRotateCamera":
  18352. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18353. case "AnaglyphFreeCamera":
  18354. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18355. case "AnaglyphGamepadCamera":
  18356. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18357. case "AnaglyphUniversalCamera":
  18358. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18359. case "StereoscopicArcRotateCamera":
  18360. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18361. case "StereoscopicFreeCamera":
  18362. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18363. case "StereoscopicGamepadCamera":
  18364. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18365. case "StereoscopicUniversalCamera":
  18366. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18367. case "FreeCamera":// Forcing Universal here
  18368. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  18369. default:// Universal Camera is the default value
  18370. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  18371. }
  18372. };
  18373. Camera.prototype.computeWorldMatrix = function () {
  18374. return this.getWorldMatrix();
  18375. };
  18376. Camera.Parse = function (parsedCamera, scene) {
  18377. var type = parsedCamera.type;
  18378. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  18379. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  18380. // Parent
  18381. if (parsedCamera.parentId) {
  18382. camera._waitingParentId = parsedCamera.parentId;
  18383. }
  18384. //If camera has an input manager, let it parse inputs settings
  18385. if (camera.inputs) {
  18386. camera.inputs.parse(parsedCamera);
  18387. camera._setupInputs();
  18388. }
  18389. if (camera.setPosition) {
  18390. camera.position.copyFromFloats(0, 0, 0);
  18391. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  18392. }
  18393. // Target
  18394. if (parsedCamera.target) {
  18395. if (camera.setTarget) {
  18396. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  18397. }
  18398. }
  18399. // Apply 3d rig, when found
  18400. if (parsedCamera.cameraRigMode) {
  18401. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  18402. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  18403. }
  18404. // Animations
  18405. if (parsedCamera.animations) {
  18406. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  18407. var parsedAnimation = parsedCamera.animations[animationIndex];
  18408. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18409. }
  18410. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  18411. }
  18412. if (parsedCamera.autoAnimate) {
  18413. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  18414. }
  18415. return camera;
  18416. };
  18417. // Statics
  18418. Camera._PERSPECTIVE_CAMERA = 0;
  18419. Camera._ORTHOGRAPHIC_CAMERA = 1;
  18420. Camera._FOVMODE_VERTICAL_FIXED = 0;
  18421. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  18422. Camera._RIG_MODE_NONE = 0;
  18423. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  18424. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  18425. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  18426. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  18427. Camera._RIG_MODE_VR = 20;
  18428. Camera._RIG_MODE_WEBVR = 21;
  18429. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  18430. Camera.UseAlternateWebVRRendering = false;
  18431. __decorate([
  18432. BABYLON.serializeAsVector3()
  18433. ], Camera.prototype, "position", void 0);
  18434. __decorate([
  18435. BABYLON.serializeAsVector3()
  18436. ], Camera.prototype, "upVector", void 0);
  18437. __decorate([
  18438. BABYLON.serialize()
  18439. ], Camera.prototype, "orthoLeft", void 0);
  18440. __decorate([
  18441. BABYLON.serialize()
  18442. ], Camera.prototype, "orthoRight", void 0);
  18443. __decorate([
  18444. BABYLON.serialize()
  18445. ], Camera.prototype, "orthoBottom", void 0);
  18446. __decorate([
  18447. BABYLON.serialize()
  18448. ], Camera.prototype, "orthoTop", void 0);
  18449. __decorate([
  18450. BABYLON.serialize()
  18451. ], Camera.prototype, "fov", void 0);
  18452. __decorate([
  18453. BABYLON.serialize()
  18454. ], Camera.prototype, "minZ", void 0);
  18455. __decorate([
  18456. BABYLON.serialize()
  18457. ], Camera.prototype, "maxZ", void 0);
  18458. __decorate([
  18459. BABYLON.serialize()
  18460. ], Camera.prototype, "inertia", void 0);
  18461. __decorate([
  18462. BABYLON.serialize()
  18463. ], Camera.prototype, "mode", void 0);
  18464. __decorate([
  18465. BABYLON.serialize()
  18466. ], Camera.prototype, "layerMask", void 0);
  18467. __decorate([
  18468. BABYLON.serialize()
  18469. ], Camera.prototype, "fovMode", void 0);
  18470. __decorate([
  18471. BABYLON.serialize()
  18472. ], Camera.prototype, "cameraRigMode", void 0);
  18473. __decorate([
  18474. BABYLON.serialize()
  18475. ], Camera.prototype, "interaxialDistance", void 0);
  18476. __decorate([
  18477. BABYLON.serialize()
  18478. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  18479. return Camera;
  18480. }(BABYLON.Node));
  18481. BABYLON.Camera = Camera;
  18482. })(BABYLON || (BABYLON = {}));
  18483. //# sourceMappingURL=babylon.camera.js.map
  18484. var BABYLON;
  18485. (function (BABYLON) {
  18486. var RenderingManager = /** @class */ (function () {
  18487. function RenderingManager(scene) {
  18488. this._renderingGroups = new Array();
  18489. this._autoClearDepthStencil = {};
  18490. this._customOpaqueSortCompareFn = {};
  18491. this._customAlphaTestSortCompareFn = {};
  18492. this._customTransparentSortCompareFn = {};
  18493. this._renderinGroupInfo = null;
  18494. this._scene = scene;
  18495. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  18496. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  18497. }
  18498. }
  18499. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  18500. if (depth === void 0) { depth = true; }
  18501. if (stencil === void 0) { stencil = true; }
  18502. if (this._depthStencilBufferAlreadyCleaned) {
  18503. return;
  18504. }
  18505. this._scene.getEngine().clear(null, false, depth, stencil);
  18506. this._depthStencilBufferAlreadyCleaned = true;
  18507. };
  18508. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  18509. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  18510. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  18511. var info = null;
  18512. if (observable) {
  18513. if (!this._renderinGroupInfo) {
  18514. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  18515. }
  18516. info = this._renderinGroupInfo;
  18517. info.scene = this._scene;
  18518. info.camera = this._scene.activeCamera;
  18519. }
  18520. // Dispatch sprites
  18521. if (renderSprites) {
  18522. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  18523. var manager = this._scene.spriteManagers[index];
  18524. this.dispatchSprites(manager);
  18525. }
  18526. }
  18527. // Render
  18528. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18529. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  18530. var renderingGroup = this._renderingGroups[index];
  18531. if (!renderingGroup && !observable)
  18532. continue;
  18533. var renderingGroupMask = 0;
  18534. // Fire PRECLEAR stage
  18535. if (observable && info) {
  18536. renderingGroupMask = Math.pow(2, index);
  18537. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  18538. info.renderingGroupId = index;
  18539. observable.notifyObservers(info, renderingGroupMask);
  18540. }
  18541. // Clear depth/stencil if needed
  18542. if (RenderingManager.AUTOCLEAR) {
  18543. var autoClear = this._autoClearDepthStencil[index];
  18544. if (autoClear && autoClear.autoClear) {
  18545. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  18546. }
  18547. }
  18548. if (observable && info) {
  18549. // Fire PREOPAQUE stage
  18550. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  18551. observable.notifyObservers(info, renderingGroupMask);
  18552. // Fire PRETRANSPARENT stage
  18553. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  18554. observable.notifyObservers(info, renderingGroupMask);
  18555. }
  18556. if (renderingGroup)
  18557. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  18558. // Fire POSTTRANSPARENT stage
  18559. if (observable && info) {
  18560. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  18561. observable.notifyObservers(info, renderingGroupMask);
  18562. }
  18563. }
  18564. };
  18565. RenderingManager.prototype.reset = function () {
  18566. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18567. var renderingGroup = this._renderingGroups[index];
  18568. if (renderingGroup) {
  18569. renderingGroup.prepare();
  18570. }
  18571. }
  18572. };
  18573. RenderingManager.prototype.dispose = function () {
  18574. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18575. var renderingGroup = this._renderingGroups[index];
  18576. if (renderingGroup) {
  18577. renderingGroup.dispose();
  18578. }
  18579. }
  18580. this._renderingGroups.length = 0;
  18581. };
  18582. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  18583. if (this._renderingGroups[renderingGroupId] === undefined) {
  18584. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  18585. }
  18586. };
  18587. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  18588. var renderingGroupId = spriteManager.renderingGroupId || 0;
  18589. this._prepareRenderingGroup(renderingGroupId);
  18590. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  18591. };
  18592. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  18593. var renderingGroupId = particleSystem.renderingGroupId || 0;
  18594. this._prepareRenderingGroup(renderingGroupId);
  18595. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  18596. };
  18597. /**
  18598. * @param subMesh The submesh to dispatch
  18599. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  18600. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  18601. */
  18602. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  18603. if (mesh === undefined) {
  18604. mesh = subMesh.getMesh();
  18605. }
  18606. var renderingGroupId = mesh.renderingGroupId || 0;
  18607. this._prepareRenderingGroup(renderingGroupId);
  18608. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  18609. };
  18610. /**
  18611. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18612. * This allowed control for front to back rendering or reversly depending of the special needs.
  18613. *
  18614. * @param renderingGroupId The rendering group id corresponding to its index
  18615. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18616. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18617. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18618. */
  18619. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18620. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18621. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18622. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18623. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  18624. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  18625. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  18626. if (this._renderingGroups[renderingGroupId]) {
  18627. var group = this._renderingGroups[renderingGroupId];
  18628. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  18629. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  18630. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  18631. }
  18632. };
  18633. /**
  18634. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18635. *
  18636. * @param renderingGroupId The rendering group id corresponding to its index
  18637. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18638. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18639. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18640. */
  18641. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18642. if (depth === void 0) { depth = true; }
  18643. if (stencil === void 0) { stencil = true; }
  18644. this._autoClearDepthStencil[renderingGroupId] = {
  18645. autoClear: autoClearDepthStencil,
  18646. depth: depth,
  18647. stencil: stencil
  18648. };
  18649. };
  18650. /**
  18651. * The max id used for rendering groups (not included)
  18652. */
  18653. RenderingManager.MAX_RENDERINGGROUPS = 4;
  18654. /**
  18655. * The min id used for rendering groups (included)
  18656. */
  18657. RenderingManager.MIN_RENDERINGGROUPS = 0;
  18658. /**
  18659. * Used to globally prevent autoclearing scenes.
  18660. */
  18661. RenderingManager.AUTOCLEAR = true;
  18662. return RenderingManager;
  18663. }());
  18664. BABYLON.RenderingManager = RenderingManager;
  18665. })(BABYLON || (BABYLON = {}));
  18666. //# sourceMappingURL=babylon.renderingManager.js.map
  18667. var BABYLON;
  18668. (function (BABYLON) {
  18669. var RenderingGroup = /** @class */ (function () {
  18670. /**
  18671. * Creates a new rendering group.
  18672. * @param index The rendering group index
  18673. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  18674. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  18675. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  18676. */
  18677. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18678. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18679. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18680. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18681. this.index = index;
  18682. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  18683. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  18684. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  18685. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  18686. this._particleSystems = new BABYLON.SmartArray(256);
  18687. this._spriteManagers = new BABYLON.SmartArray(256);
  18688. this._edgesRenderers = new BABYLON.SmartArray(16);
  18689. this._scene = scene;
  18690. this.opaqueSortCompareFn = opaqueSortCompareFn;
  18691. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  18692. this.transparentSortCompareFn = transparentSortCompareFn;
  18693. }
  18694. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  18695. /**
  18696. * Set the opaque sort comparison function.
  18697. * If null the sub meshes will be render in the order they were created
  18698. */
  18699. set: function (value) {
  18700. this._opaqueSortCompareFn = value;
  18701. if (value) {
  18702. this._renderOpaque = this.renderOpaqueSorted;
  18703. }
  18704. else {
  18705. this._renderOpaque = RenderingGroup.renderUnsorted;
  18706. }
  18707. },
  18708. enumerable: true,
  18709. configurable: true
  18710. });
  18711. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  18712. /**
  18713. * Set the alpha test sort comparison function.
  18714. * If null the sub meshes will be render in the order they were created
  18715. */
  18716. set: function (value) {
  18717. this._alphaTestSortCompareFn = value;
  18718. if (value) {
  18719. this._renderAlphaTest = this.renderAlphaTestSorted;
  18720. }
  18721. else {
  18722. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  18723. }
  18724. },
  18725. enumerable: true,
  18726. configurable: true
  18727. });
  18728. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  18729. /**
  18730. * Set the transparent sort comparison function.
  18731. * If null the sub meshes will be render in the order they were created
  18732. */
  18733. set: function (value) {
  18734. if (value) {
  18735. this._transparentSortCompareFn = value;
  18736. }
  18737. else {
  18738. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  18739. }
  18740. this._renderTransparent = this.renderTransparentSorted;
  18741. },
  18742. enumerable: true,
  18743. configurable: true
  18744. });
  18745. /**
  18746. * Render all the sub meshes contained in the group.
  18747. * @param customRenderFunction Used to override the default render behaviour of the group.
  18748. * @returns true if rendered some submeshes.
  18749. */
  18750. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  18751. if (customRenderFunction) {
  18752. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  18753. return;
  18754. }
  18755. var engine = this._scene.getEngine();
  18756. // Depth only
  18757. if (this._depthOnlySubMeshes.length !== 0) {
  18758. engine.setAlphaTesting(true);
  18759. engine.setColorWrite(false);
  18760. this._renderAlphaTest(this._depthOnlySubMeshes);
  18761. engine.setAlphaTesting(false);
  18762. engine.setColorWrite(true);
  18763. }
  18764. // Opaque
  18765. if (this._opaqueSubMeshes.length !== 0) {
  18766. this._renderOpaque(this._opaqueSubMeshes);
  18767. }
  18768. // Alpha test
  18769. if (this._alphaTestSubMeshes.length !== 0) {
  18770. engine.setAlphaTesting(true);
  18771. this._renderAlphaTest(this._alphaTestSubMeshes);
  18772. engine.setAlphaTesting(false);
  18773. }
  18774. var stencilState = engine.getStencilBuffer();
  18775. engine.setStencilBuffer(false);
  18776. // Sprites
  18777. if (renderSprites) {
  18778. this._renderSprites();
  18779. }
  18780. // Particles
  18781. if (renderParticles) {
  18782. this._renderParticles(activeMeshes);
  18783. }
  18784. if (this.onBeforeTransparentRendering) {
  18785. this.onBeforeTransparentRendering();
  18786. }
  18787. // Transparent
  18788. if (this._transparentSubMeshes.length !== 0) {
  18789. this._renderTransparent(this._transparentSubMeshes);
  18790. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18791. }
  18792. // Set back stencil to false in case it changes before the edge renderer.
  18793. engine.setStencilBuffer(false);
  18794. // Edges
  18795. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  18796. this._edgesRenderers.data[edgesRendererIndex].render();
  18797. }
  18798. // Restore Stencil state.
  18799. engine.setStencilBuffer(stencilState);
  18800. };
  18801. /**
  18802. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  18803. * @param subMeshes The submeshes to render
  18804. */
  18805. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  18806. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  18807. };
  18808. /**
  18809. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  18810. * @param subMeshes The submeshes to render
  18811. */
  18812. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  18813. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  18814. };
  18815. /**
  18816. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  18817. * @param subMeshes The submeshes to render
  18818. */
  18819. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  18820. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  18821. };
  18822. /**
  18823. * Renders the submeshes in a specified order.
  18824. * @param subMeshes The submeshes to sort before render
  18825. * @param sortCompareFn The comparison function use to sort
  18826. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  18827. * @param transparent Specifies to activate blending if true
  18828. */
  18829. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  18830. var subIndex = 0;
  18831. var subMesh;
  18832. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  18833. for (; subIndex < subMeshes.length; subIndex++) {
  18834. subMesh = subMeshes.data[subIndex];
  18835. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  18836. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  18837. }
  18838. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  18839. if (sortCompareFn) {
  18840. sortedArray.sort(sortCompareFn);
  18841. }
  18842. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  18843. subMesh = sortedArray[subIndex];
  18844. if (transparent) {
  18845. var material = subMesh.getMaterial();
  18846. if (material && material.needDepthPrePass) {
  18847. var engine = material.getScene().getEngine();
  18848. engine.setColorWrite(false);
  18849. engine.setAlphaTesting(true);
  18850. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18851. subMesh.render(false);
  18852. engine.setAlphaTesting(false);
  18853. engine.setColorWrite(true);
  18854. }
  18855. }
  18856. subMesh.render(transparent);
  18857. }
  18858. };
  18859. /**
  18860. * Renders the submeshes in the order they were dispatched (no sort applied).
  18861. * @param subMeshes The submeshes to render
  18862. */
  18863. RenderingGroup.renderUnsorted = function (subMeshes) {
  18864. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  18865. var submesh = subMeshes.data[subIndex];
  18866. submesh.render(false);
  18867. }
  18868. };
  18869. /**
  18870. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18871. * are rendered back to front if in the same alpha index.
  18872. *
  18873. * @param a The first submesh
  18874. * @param b The second submesh
  18875. * @returns The result of the comparison
  18876. */
  18877. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  18878. // Alpha index first
  18879. if (a._alphaIndex > b._alphaIndex) {
  18880. return 1;
  18881. }
  18882. if (a._alphaIndex < b._alphaIndex) {
  18883. return -1;
  18884. }
  18885. // Then distance to camera
  18886. return RenderingGroup.backToFrontSortCompare(a, b);
  18887. };
  18888. /**
  18889. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18890. * are rendered back to front.
  18891. *
  18892. * @param a The first submesh
  18893. * @param b The second submesh
  18894. * @returns The result of the comparison
  18895. */
  18896. RenderingGroup.backToFrontSortCompare = function (a, b) {
  18897. // Then distance to camera
  18898. if (a._distanceToCamera < b._distanceToCamera) {
  18899. return 1;
  18900. }
  18901. if (a._distanceToCamera > b._distanceToCamera) {
  18902. return -1;
  18903. }
  18904. return 0;
  18905. };
  18906. /**
  18907. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18908. * are rendered front to back (prevent overdraw).
  18909. *
  18910. * @param a The first submesh
  18911. * @param b The second submesh
  18912. * @returns The result of the comparison
  18913. */
  18914. RenderingGroup.frontToBackSortCompare = function (a, b) {
  18915. // Then distance to camera
  18916. if (a._distanceToCamera < b._distanceToCamera) {
  18917. return -1;
  18918. }
  18919. if (a._distanceToCamera > b._distanceToCamera) {
  18920. return 1;
  18921. }
  18922. return 0;
  18923. };
  18924. /**
  18925. * Resets the different lists of submeshes to prepare a new frame.
  18926. */
  18927. RenderingGroup.prototype.prepare = function () {
  18928. this._opaqueSubMeshes.reset();
  18929. this._transparentSubMeshes.reset();
  18930. this._alphaTestSubMeshes.reset();
  18931. this._depthOnlySubMeshes.reset();
  18932. this._particleSystems.reset();
  18933. this._spriteManagers.reset();
  18934. this._edgesRenderers.reset();
  18935. };
  18936. RenderingGroup.prototype.dispose = function () {
  18937. this._opaqueSubMeshes.dispose();
  18938. this._transparentSubMeshes.dispose();
  18939. this._alphaTestSubMeshes.dispose();
  18940. this._depthOnlySubMeshes.dispose();
  18941. this._particleSystems.dispose();
  18942. this._spriteManagers.dispose();
  18943. this._edgesRenderers.dispose();
  18944. };
  18945. /**
  18946. * Inserts the submesh in its correct queue depending on its material.
  18947. * @param subMesh The submesh to dispatch
  18948. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  18949. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  18950. */
  18951. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  18952. // Get mesh and materials if not provided
  18953. if (mesh === undefined) {
  18954. mesh = subMesh.getMesh();
  18955. }
  18956. if (material === undefined) {
  18957. material = subMesh.getMaterial();
  18958. }
  18959. if (material === null || material === undefined) {
  18960. return;
  18961. }
  18962. if (material.needAlphaBlendingForMesh(mesh)) {
  18963. this._transparentSubMeshes.push(subMesh);
  18964. }
  18965. else if (material.needAlphaTesting()) {
  18966. if (material.needDepthPrePass) {
  18967. this._depthOnlySubMeshes.push(subMesh);
  18968. }
  18969. this._alphaTestSubMeshes.push(subMesh);
  18970. }
  18971. else {
  18972. if (material.needDepthPrePass) {
  18973. this._depthOnlySubMeshes.push(subMesh);
  18974. }
  18975. this._opaqueSubMeshes.push(subMesh); // Opaque
  18976. }
  18977. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  18978. this._edgesRenderers.push(mesh._edgesRenderer);
  18979. }
  18980. };
  18981. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  18982. this._spriteManagers.push(spriteManager);
  18983. };
  18984. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  18985. this._particleSystems.push(particleSystem);
  18986. };
  18987. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  18988. if (this._particleSystems.length === 0) {
  18989. return;
  18990. }
  18991. // Particles
  18992. var activeCamera = this._scene.activeCamera;
  18993. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  18994. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  18995. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  18996. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  18997. continue;
  18998. }
  18999. var emitter = particleSystem.emitter;
  19000. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  19001. this._scene._activeParticles.addCount(particleSystem.render(), false);
  19002. }
  19003. }
  19004. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  19005. };
  19006. RenderingGroup.prototype._renderSprites = function () {
  19007. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19008. return;
  19009. }
  19010. // Sprites
  19011. var activeCamera = this._scene.activeCamera;
  19012. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  19013. for (var id = 0; id < this._spriteManagers.length; id++) {
  19014. var spriteManager = this._spriteManagers.data[id];
  19015. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19016. spriteManager.render();
  19017. }
  19018. }
  19019. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  19020. };
  19021. return RenderingGroup;
  19022. }());
  19023. BABYLON.RenderingGroup = RenderingGroup;
  19024. })(BABYLON || (BABYLON = {}));
  19025. //# sourceMappingURL=babylon.renderingGroup.js.map
  19026. var BABYLON;
  19027. (function (BABYLON) {
  19028. var ClickInfo = /** @class */ (function () {
  19029. function ClickInfo() {
  19030. this._singleClick = false;
  19031. this._doubleClick = false;
  19032. this._hasSwiped = false;
  19033. this._ignore = false;
  19034. }
  19035. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  19036. get: function () {
  19037. return this._singleClick;
  19038. },
  19039. set: function (b) {
  19040. this._singleClick = b;
  19041. },
  19042. enumerable: true,
  19043. configurable: true
  19044. });
  19045. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  19046. get: function () {
  19047. return this._doubleClick;
  19048. },
  19049. set: function (b) {
  19050. this._doubleClick = b;
  19051. },
  19052. enumerable: true,
  19053. configurable: true
  19054. });
  19055. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  19056. get: function () {
  19057. return this._hasSwiped;
  19058. },
  19059. set: function (b) {
  19060. this._hasSwiped = b;
  19061. },
  19062. enumerable: true,
  19063. configurable: true
  19064. });
  19065. Object.defineProperty(ClickInfo.prototype, "ignore", {
  19066. get: function () {
  19067. return this._ignore;
  19068. },
  19069. set: function (b) {
  19070. this._ignore = b;
  19071. },
  19072. enumerable: true,
  19073. configurable: true
  19074. });
  19075. return ClickInfo;
  19076. }());
  19077. /**
  19078. * This class is used by the onRenderingGroupObservable
  19079. */
  19080. var RenderingGroupInfo = /** @class */ (function () {
  19081. function RenderingGroupInfo() {
  19082. }
  19083. /**
  19084. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19085. * This stage will be fired no matter what
  19086. */
  19087. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19088. /**
  19089. * Called before opaque object are rendered.
  19090. * This stage will be fired only if there's 3D Opaque content to render
  19091. */
  19092. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19093. /**
  19094. * Called after the opaque objects are rendered and before the transparent ones
  19095. * This stage will be fired only if there's 3D transparent content to render
  19096. */
  19097. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19098. /**
  19099. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19100. * This stage will be fired no matter what
  19101. */
  19102. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19103. return RenderingGroupInfo;
  19104. }());
  19105. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19106. /**
  19107. * Represents a scene to be rendered by the engine.
  19108. * @see http://doc.babylonjs.com/page.php?p=21911
  19109. */
  19110. var Scene = /** @class */ (function () {
  19111. /**
  19112. * @constructor
  19113. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19114. */
  19115. function Scene(engine) {
  19116. // Members
  19117. this.autoClear = true;
  19118. this.autoClearDepthAndStencil = true;
  19119. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19120. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19121. this.forceWireframe = false;
  19122. this._forcePointsCloud = false;
  19123. this.forceShowBoundingBoxes = false;
  19124. this.animationsEnabled = true;
  19125. this.useConstantAnimationDeltaTime = false;
  19126. this.constantlyUpdateMeshUnderPointer = false;
  19127. this.hoverCursor = "pointer";
  19128. this.defaultCursor = "";
  19129. /**
  19130. * This is used to call preventDefault() on pointer down
  19131. * in order to block unwanted artifacts like system double clicks
  19132. */
  19133. this.preventDefaultOnPointerDown = true;
  19134. // Metadata
  19135. this.metadata = null;
  19136. /**
  19137. * An event triggered when the scene is disposed.
  19138. * @type {BABYLON.Observable}
  19139. */
  19140. this.onDisposeObservable = new BABYLON.Observable();
  19141. /**
  19142. * An event triggered before rendering the scene (right after animations and physics)
  19143. * @type {BABYLON.Observable}
  19144. */
  19145. this.onBeforeRenderObservable = new BABYLON.Observable();
  19146. /**
  19147. * An event triggered after rendering the scene
  19148. * @type {BABYLON.Observable}
  19149. */
  19150. this.onAfterRenderObservable = new BABYLON.Observable();
  19151. /**
  19152. * An event triggered before animating the scene
  19153. * @type {BABYLON.Observable}
  19154. */
  19155. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  19156. /**
  19157. * An event triggered after animations processing
  19158. * @type {BABYLON.Observable}
  19159. */
  19160. this.onAfterAnimationsObservable = new BABYLON.Observable();
  19161. /**
  19162. * An event triggered before draw calls are ready to be sent
  19163. * @type {BABYLON.Observable}
  19164. */
  19165. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  19166. /**
  19167. * An event triggered after draw calls have been sent
  19168. * @type {BABYLON.Observable}
  19169. */
  19170. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  19171. /**
  19172. * An event triggered when physic simulation is about to be run
  19173. * @type {BABYLON.Observable}
  19174. */
  19175. this.onBeforePhysicsObservable = new BABYLON.Observable();
  19176. /**
  19177. * An event triggered when physic simulation has been done
  19178. * @type {BABYLON.Observable}
  19179. */
  19180. this.onAfterPhysicsObservable = new BABYLON.Observable();
  19181. /**
  19182. * An event triggered when the scene is ready
  19183. * @type {BABYLON.Observable}
  19184. */
  19185. this.onReadyObservable = new BABYLON.Observable();
  19186. /**
  19187. * An event triggered before rendering a camera
  19188. * @type {BABYLON.Observable}
  19189. */
  19190. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  19191. /**
  19192. * An event triggered after rendering a camera
  19193. * @type {BABYLON.Observable}
  19194. */
  19195. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  19196. /**
  19197. * An event triggered when active meshes evaluation is about to start
  19198. * @type {BABYLON.Observable}
  19199. */
  19200. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19201. /**
  19202. * An event triggered when active meshes evaluation is done
  19203. * @type {BABYLON.Observable}
  19204. */
  19205. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19206. /**
  19207. * An event triggered when particles rendering is about to start
  19208. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19209. * @type {BABYLON.Observable}
  19210. */
  19211. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  19212. /**
  19213. * An event triggered when particles rendering is done
  19214. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19215. * @type {BABYLON.Observable}
  19216. */
  19217. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  19218. /**
  19219. * An event triggered when sprites rendering is about to start
  19220. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19221. * @type {BABYLON.Observable}
  19222. */
  19223. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  19224. /**
  19225. * An event triggered when sprites rendering is done
  19226. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19227. * @type {BABYLON.Observable}
  19228. */
  19229. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  19230. /**
  19231. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  19232. * @type {BABYLON.Observable}
  19233. */
  19234. this.onDataLoadedObservable = new BABYLON.Observable();
  19235. /**
  19236. * An event triggered when a camera is created
  19237. * @type {BABYLON.Observable}
  19238. */
  19239. this.onNewCameraAddedObservable = new BABYLON.Observable();
  19240. /**
  19241. * An event triggered when a camera is removed
  19242. * @type {BABYLON.Observable}
  19243. */
  19244. this.onCameraRemovedObservable = new BABYLON.Observable();
  19245. /**
  19246. * An event triggered when a light is created
  19247. * @type {BABYLON.Observable}
  19248. */
  19249. this.onNewLightAddedObservable = new BABYLON.Observable();
  19250. /**
  19251. * An event triggered when a light is removed
  19252. * @type {BABYLON.Observable}
  19253. */
  19254. this.onLightRemovedObservable = new BABYLON.Observable();
  19255. /**
  19256. * An event triggered when a geometry is created
  19257. * @type {BABYLON.Observable}
  19258. */
  19259. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  19260. /**
  19261. * An event triggered when a geometry is removed
  19262. * @type {BABYLON.Observable}
  19263. */
  19264. this.onGeometryRemovedObservable = new BABYLON.Observable();
  19265. /**
  19266. * An event triggered when a transform node is created
  19267. * @type {BABYLON.Observable}
  19268. */
  19269. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  19270. /**
  19271. * An event triggered when a transform node is removed
  19272. * @type {BABYLON.Observable}
  19273. */
  19274. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  19275. /**
  19276. * An event triggered when a mesh is created
  19277. * @type {BABYLON.Observable}
  19278. */
  19279. this.onNewMeshAddedObservable = new BABYLON.Observable();
  19280. /**
  19281. * An event triggered when a mesh is removed
  19282. * @type {BABYLON.Observable}
  19283. */
  19284. this.onMeshRemovedObservable = new BABYLON.Observable();
  19285. /**
  19286. * An event triggered when render targets are about to be rendered
  19287. * Can happen multiple times per frame.
  19288. * @type {BABYLON.Observable}
  19289. */
  19290. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  19291. /**
  19292. * An event triggered when render targets were rendered.
  19293. * Can happen multiple times per frame.
  19294. * @type {BABYLON.Observable}
  19295. */
  19296. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  19297. /**
  19298. * An event triggered before calculating deterministic simulation step
  19299. * @type {BABYLON.Observable}
  19300. */
  19301. this.onBeforeStepObservable = new BABYLON.Observable();
  19302. /**
  19303. * An event triggered after calculating deterministic simulation step
  19304. * @type {BABYLON.Observable}
  19305. */
  19306. this.onAfterStepObservable = new BABYLON.Observable();
  19307. /**
  19308. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  19309. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  19310. * 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)
  19311. */
  19312. this.onRenderingGroupObservable = new BABYLON.Observable();
  19313. // Animations
  19314. this.animations = [];
  19315. /**
  19316. * 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).
  19317. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  19318. */
  19319. this.onPrePointerObservable = new BABYLON.Observable();
  19320. /**
  19321. * Observable event triggered each time an input event is received from the rendering canvas
  19322. */
  19323. this.onPointerObservable = new BABYLON.Observable();
  19324. this._meshPickProceed = false;
  19325. this._currentPickResult = null;
  19326. this._previousPickResult = null;
  19327. this._totalPointersPressed = 0;
  19328. this._doubleClickOccured = false;
  19329. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  19330. this.cameraToUseForPointers = null;
  19331. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  19332. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  19333. this._startingPointerTime = 0;
  19334. this._previousStartingPointerTime = 0;
  19335. // Deterministic lockstep
  19336. this._timeAccumulator = 0;
  19337. this._currentStepId = 0;
  19338. this._currentInternalStep = 0;
  19339. // Keyboard
  19340. /**
  19341. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  19342. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  19343. */
  19344. this.onPreKeyboardObservable = new BABYLON.Observable();
  19345. /**
  19346. * Observable event triggered each time an keyboard event is received from the hosting window
  19347. */
  19348. this.onKeyboardObservable = new BABYLON.Observable();
  19349. // Coordinate system
  19350. /**
  19351. * use right-handed coordinate system on this scene.
  19352. * @type {boolean}
  19353. */
  19354. this._useRightHandedSystem = false;
  19355. // Fog
  19356. this._fogEnabled = true;
  19357. this._fogMode = Scene.FOGMODE_NONE;
  19358. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  19359. this.fogDensity = 0.1;
  19360. this.fogStart = 0;
  19361. this.fogEnd = 1000.0;
  19362. // Lights
  19363. /**
  19364. * is shadow enabled on this scene.
  19365. * @type {boolean}
  19366. */
  19367. this._shadowsEnabled = true;
  19368. /**
  19369. * is light enabled on this scene.
  19370. * @type {boolean}
  19371. */
  19372. this._lightsEnabled = true;
  19373. /**
  19374. * All of the lights added to this scene.
  19375. * @see BABYLON.Light
  19376. * @type {BABYLON.Light[]}
  19377. */
  19378. this.lights = new Array();
  19379. // Cameras
  19380. /** All of the cameras added to this scene. */
  19381. this.cameras = new Array();
  19382. /** All of the active cameras added to this scene. */
  19383. this.activeCameras = new Array();
  19384. // Meshes
  19385. /**
  19386. * All of the tranform nodes added to this scene.
  19387. * @see BABYLON.TransformNode
  19388. * @type {BABYLON.TransformNode[]}
  19389. */
  19390. this.transformNodes = new Array();
  19391. /**
  19392. * All of the (abstract) meshes added to this scene.
  19393. * @see BABYLON.AbstractMesh
  19394. * @type {BABYLON.AbstractMesh[]}
  19395. */
  19396. this.meshes = new Array();
  19397. /**
  19398. * All of the animation groups added to this scene.
  19399. * @see BABYLON.AnimationGroup
  19400. * @type {BABYLON.AnimationGroup[]}
  19401. */
  19402. this.animationGroups = new Array();
  19403. // Geometries
  19404. this._geometries = new Array();
  19405. this.materials = new Array();
  19406. this.multiMaterials = new Array();
  19407. // Textures
  19408. this._texturesEnabled = true;
  19409. this.textures = new Array();
  19410. // Particles
  19411. this.particlesEnabled = true;
  19412. this.particleSystems = new Array();
  19413. // Sprites
  19414. this.spritesEnabled = true;
  19415. this.spriteManagers = new Array();
  19416. // Layers
  19417. this.layers = new Array();
  19418. this.highlightLayers = new Array();
  19419. // Skeletons
  19420. this._skeletonsEnabled = true;
  19421. this.skeletons = new Array();
  19422. // Morph targets
  19423. this.morphTargetManagers = new Array();
  19424. // Lens flares
  19425. this.lensFlaresEnabled = true;
  19426. this.lensFlareSystems = new Array();
  19427. // Collisions
  19428. this.collisionsEnabled = true;
  19429. /** Defines the gravity applied to this scene */
  19430. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  19431. // Postprocesses
  19432. this.postProcesses = new Array();
  19433. this.postProcessesEnabled = true;
  19434. // Customs render targets
  19435. this.renderTargetsEnabled = true;
  19436. this.dumpNextRenderTargets = false;
  19437. this.customRenderTargets = new Array();
  19438. // Imported meshes
  19439. this.importedMeshesFiles = new Array();
  19440. // Probes
  19441. this.probesEnabled = true;
  19442. this.reflectionProbes = new Array();
  19443. this._actionManagers = new Array();
  19444. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  19445. // Procedural textures
  19446. this.proceduralTexturesEnabled = true;
  19447. this._proceduralTextures = new Array();
  19448. this.soundTracks = new Array();
  19449. this._audioEnabled = true;
  19450. this._headphone = false;
  19451. // Performance counters
  19452. this._totalVertices = new BABYLON.PerfCounter();
  19453. this._activeIndices = new BABYLON.PerfCounter();
  19454. this._activeParticles = new BABYLON.PerfCounter();
  19455. this._activeBones = new BABYLON.PerfCounter();
  19456. this._animationTime = 0;
  19457. this.animationTimeScale = 1;
  19458. this._renderId = 0;
  19459. this._executeWhenReadyTimeoutId = -1;
  19460. this._intermediateRendering = false;
  19461. this._viewUpdateFlag = -1;
  19462. this._projectionUpdateFlag = -1;
  19463. this._alternateViewUpdateFlag = -1;
  19464. this._alternateProjectionUpdateFlag = -1;
  19465. this._toBeDisposed = new BABYLON.SmartArray(256);
  19466. this._activeRequests = new Array();
  19467. this._pendingData = new Array();
  19468. this._isDisposed = false;
  19469. this.dispatchAllSubMeshesOfActiveMeshes = false;
  19470. this._activeMeshes = new BABYLON.SmartArray(256);
  19471. this._processedMaterials = new BABYLON.SmartArray(256);
  19472. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  19473. this._activeParticleSystems = new BABYLON.SmartArray(256);
  19474. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  19475. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  19476. this._activeAnimatables = new Array();
  19477. this._transformMatrix = BABYLON.Matrix.Zero();
  19478. this._useAlternateCameraConfiguration = false;
  19479. this._alternateRendering = false;
  19480. this.requireLightSorting = false;
  19481. this._activeMeshesFrozen = false;
  19482. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  19483. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  19484. this._engine.scenes.push(this);
  19485. this._uid = null;
  19486. this._renderingManager = new BABYLON.RenderingManager(this);
  19487. this.postProcessManager = new BABYLON.PostProcessManager(this);
  19488. if (BABYLON.OutlineRenderer) {
  19489. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  19490. }
  19491. if (BABYLON.Tools.IsWindowObjectExist()) {
  19492. this.attachControl();
  19493. }
  19494. //simplification queue
  19495. if (BABYLON.SimplificationQueue) {
  19496. this.simplificationQueue = new BABYLON.SimplificationQueue();
  19497. }
  19498. //collision coordinator initialization. For now legacy per default.
  19499. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  19500. // Uniform Buffer
  19501. this._createUbo();
  19502. // Default Image processing definition.
  19503. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  19504. }
  19505. Object.defineProperty(Scene, "FOGMODE_NONE", {
  19506. /** The fog is deactivated */
  19507. get: function () {
  19508. return Scene._FOGMODE_NONE;
  19509. },
  19510. enumerable: true,
  19511. configurable: true
  19512. });
  19513. Object.defineProperty(Scene, "FOGMODE_EXP", {
  19514. /** The fog density is following an exponential function */
  19515. get: function () {
  19516. return Scene._FOGMODE_EXP;
  19517. },
  19518. enumerable: true,
  19519. configurable: true
  19520. });
  19521. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  19522. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  19523. get: function () {
  19524. return Scene._FOGMODE_EXP2;
  19525. },
  19526. enumerable: true,
  19527. configurable: true
  19528. });
  19529. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  19530. /** The fog density is following a linear function. */
  19531. get: function () {
  19532. return Scene._FOGMODE_LINEAR;
  19533. },
  19534. enumerable: true,
  19535. configurable: true
  19536. });
  19537. Object.defineProperty(Scene.prototype, "environmentTexture", {
  19538. /**
  19539. * Texture used in all pbr material as the reflection texture.
  19540. * As in the majority of the scene they are the same (exception for multi room and so on),
  19541. * this is easier to reference from here than from all the materials.
  19542. */
  19543. get: function () {
  19544. return this._environmentTexture;
  19545. },
  19546. /**
  19547. * Texture used in all pbr material as the reflection texture.
  19548. * As in the majority of the scene they are the same (exception for multi room and so on),
  19549. * this is easier to set here than in all the materials.
  19550. */
  19551. set: function (value) {
  19552. if (this._environmentTexture === value) {
  19553. return;
  19554. }
  19555. this._environmentTexture = value;
  19556. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19557. },
  19558. enumerable: true,
  19559. configurable: true
  19560. });
  19561. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  19562. /**
  19563. * Default image processing configuration used either in the rendering
  19564. * Forward main pass or through the imageProcessingPostProcess if present.
  19565. * As in the majority of the scene they are the same (exception for multi camera),
  19566. * this is easier to reference from here than from all the materials and post process.
  19567. *
  19568. * No setter as we it is a shared configuration, you can set the values instead.
  19569. */
  19570. get: function () {
  19571. return this._imageProcessingConfiguration;
  19572. },
  19573. enumerable: true,
  19574. configurable: true
  19575. });
  19576. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  19577. get: function () {
  19578. return this._forcePointsCloud;
  19579. },
  19580. set: function (value) {
  19581. if (this._forcePointsCloud === value) {
  19582. return;
  19583. }
  19584. this._forcePointsCloud = value;
  19585. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19586. },
  19587. enumerable: true,
  19588. configurable: true
  19589. });
  19590. Object.defineProperty(Scene.prototype, "onDispose", {
  19591. /** A function to be executed when this scene is disposed. */
  19592. set: function (callback) {
  19593. if (this._onDisposeObserver) {
  19594. this.onDisposeObservable.remove(this._onDisposeObserver);
  19595. }
  19596. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  19597. },
  19598. enumerable: true,
  19599. configurable: true
  19600. });
  19601. Object.defineProperty(Scene.prototype, "beforeRender", {
  19602. /** A function to be executed before rendering this scene */
  19603. set: function (callback) {
  19604. if (this._onBeforeRenderObserver) {
  19605. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  19606. }
  19607. if (callback) {
  19608. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  19609. }
  19610. },
  19611. enumerable: true,
  19612. configurable: true
  19613. });
  19614. Object.defineProperty(Scene.prototype, "afterRender", {
  19615. /** A function to be executed after rendering this scene */
  19616. set: function (callback) {
  19617. if (this._onAfterRenderObserver) {
  19618. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  19619. }
  19620. if (callback) {
  19621. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  19622. }
  19623. },
  19624. enumerable: true,
  19625. configurable: true
  19626. });
  19627. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  19628. set: function (callback) {
  19629. if (this._onBeforeCameraRenderObserver) {
  19630. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  19631. }
  19632. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  19633. },
  19634. enumerable: true,
  19635. configurable: true
  19636. });
  19637. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  19638. set: function (callback) {
  19639. if (this._onAfterCameraRenderObserver) {
  19640. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  19641. }
  19642. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  19643. },
  19644. enumerable: true,
  19645. configurable: true
  19646. });
  19647. Object.defineProperty(Scene.prototype, "gamepadManager", {
  19648. get: function () {
  19649. if (!this._gamepadManager) {
  19650. this._gamepadManager = new BABYLON.GamepadManager(this);
  19651. }
  19652. return this._gamepadManager;
  19653. },
  19654. enumerable: true,
  19655. configurable: true
  19656. });
  19657. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  19658. get: function () {
  19659. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  19660. },
  19661. enumerable: true,
  19662. configurable: true
  19663. });
  19664. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  19665. get: function () {
  19666. return this._useRightHandedSystem;
  19667. },
  19668. set: function (value) {
  19669. if (this._useRightHandedSystem === value) {
  19670. return;
  19671. }
  19672. this._useRightHandedSystem = value;
  19673. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19674. },
  19675. enumerable: true,
  19676. configurable: true
  19677. });
  19678. Scene.prototype.setStepId = function (newStepId) {
  19679. this._currentStepId = newStepId;
  19680. };
  19681. ;
  19682. Scene.prototype.getStepId = function () {
  19683. return this._currentStepId;
  19684. };
  19685. ;
  19686. Scene.prototype.getInternalStep = function () {
  19687. return this._currentInternalStep;
  19688. };
  19689. ;
  19690. Object.defineProperty(Scene.prototype, "fogEnabled", {
  19691. get: function () {
  19692. return this._fogEnabled;
  19693. },
  19694. /**
  19695. * is fog enabled on this scene.
  19696. */
  19697. set: function (value) {
  19698. if (this._fogEnabled === value) {
  19699. return;
  19700. }
  19701. this._fogEnabled = value;
  19702. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19703. },
  19704. enumerable: true,
  19705. configurable: true
  19706. });
  19707. Object.defineProperty(Scene.prototype, "fogMode", {
  19708. get: function () {
  19709. return this._fogMode;
  19710. },
  19711. set: function (value) {
  19712. if (this._fogMode === value) {
  19713. return;
  19714. }
  19715. this._fogMode = value;
  19716. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19717. },
  19718. enumerable: true,
  19719. configurable: true
  19720. });
  19721. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  19722. get: function () {
  19723. return this._shadowsEnabled;
  19724. },
  19725. set: function (value) {
  19726. if (this._shadowsEnabled === value) {
  19727. return;
  19728. }
  19729. this._shadowsEnabled = value;
  19730. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  19731. },
  19732. enumerable: true,
  19733. configurable: true
  19734. });
  19735. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  19736. get: function () {
  19737. return this._lightsEnabled;
  19738. },
  19739. set: function (value) {
  19740. if (this._lightsEnabled === value) {
  19741. return;
  19742. }
  19743. this._lightsEnabled = value;
  19744. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  19745. },
  19746. enumerable: true,
  19747. configurable: true
  19748. });
  19749. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  19750. /** The default material used on meshes when no material is affected */
  19751. get: function () {
  19752. if (!this._defaultMaterial) {
  19753. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  19754. }
  19755. return this._defaultMaterial;
  19756. },
  19757. /** The default material used on meshes when no material is affected */
  19758. set: function (value) {
  19759. this._defaultMaterial = value;
  19760. },
  19761. enumerable: true,
  19762. configurable: true
  19763. });
  19764. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  19765. get: function () {
  19766. return this._texturesEnabled;
  19767. },
  19768. set: function (value) {
  19769. if (this._texturesEnabled === value) {
  19770. return;
  19771. }
  19772. this._texturesEnabled = value;
  19773. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19774. },
  19775. enumerable: true,
  19776. configurable: true
  19777. });
  19778. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  19779. get: function () {
  19780. return this._skeletonsEnabled;
  19781. },
  19782. set: function (value) {
  19783. if (this._skeletonsEnabled === value) {
  19784. return;
  19785. }
  19786. this._skeletonsEnabled = value;
  19787. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  19788. },
  19789. enumerable: true,
  19790. configurable: true
  19791. });
  19792. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  19793. get: function () {
  19794. if (!this._postProcessRenderPipelineManager) {
  19795. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  19796. }
  19797. return this._postProcessRenderPipelineManager;
  19798. },
  19799. enumerable: true,
  19800. configurable: true
  19801. });
  19802. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  19803. get: function () {
  19804. if (!this._mainSoundTrack) {
  19805. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  19806. }
  19807. return this._mainSoundTrack;
  19808. },
  19809. enumerable: true,
  19810. configurable: true
  19811. });
  19812. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  19813. get: function () {
  19814. return this._alternateRendering;
  19815. },
  19816. enumerable: true,
  19817. configurable: true
  19818. });
  19819. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  19820. get: function () {
  19821. return this._frustumPlanes;
  19822. },
  19823. enumerable: true,
  19824. configurable: true
  19825. });
  19826. Object.defineProperty(Scene.prototype, "debugLayer", {
  19827. // Properties
  19828. get: function () {
  19829. if (!this._debugLayer) {
  19830. this._debugLayer = new BABYLON.DebugLayer(this);
  19831. }
  19832. return this._debugLayer;
  19833. },
  19834. enumerable: true,
  19835. configurable: true
  19836. });
  19837. Object.defineProperty(Scene.prototype, "workerCollisions", {
  19838. get: function () {
  19839. return this._workerCollisions;
  19840. },
  19841. set: function (enabled) {
  19842. if (!BABYLON.CollisionCoordinatorLegacy) {
  19843. return;
  19844. }
  19845. enabled = (enabled && !!Worker);
  19846. this._workerCollisions = enabled;
  19847. if (this.collisionCoordinator) {
  19848. this.collisionCoordinator.destroy();
  19849. }
  19850. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  19851. this.collisionCoordinator.init(this);
  19852. },
  19853. enumerable: true,
  19854. configurable: true
  19855. });
  19856. Object.defineProperty(Scene.prototype, "selectionOctree", {
  19857. get: function () {
  19858. return this._selectionOctree;
  19859. },
  19860. enumerable: true,
  19861. configurable: true
  19862. });
  19863. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  19864. /**
  19865. * The mesh that is currently under the pointer.
  19866. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  19867. */
  19868. get: function () {
  19869. return this._pointerOverMesh;
  19870. },
  19871. enumerable: true,
  19872. configurable: true
  19873. });
  19874. Object.defineProperty(Scene.prototype, "pointerX", {
  19875. /**
  19876. * Current on-screen X position of the pointer
  19877. * @return {number} X position of the pointer
  19878. */
  19879. get: function () {
  19880. return this._pointerX;
  19881. },
  19882. enumerable: true,
  19883. configurable: true
  19884. });
  19885. Object.defineProperty(Scene.prototype, "pointerY", {
  19886. /**
  19887. * Current on-screen Y position of the pointer
  19888. * @return {number} Y position of the pointer
  19889. */
  19890. get: function () {
  19891. return this._pointerY;
  19892. },
  19893. enumerable: true,
  19894. configurable: true
  19895. });
  19896. Scene.prototype.getCachedMaterial = function () {
  19897. return this._cachedMaterial;
  19898. };
  19899. Scene.prototype.getCachedEffect = function () {
  19900. return this._cachedEffect;
  19901. };
  19902. Scene.prototype.getCachedVisibility = function () {
  19903. return this._cachedVisibility;
  19904. };
  19905. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  19906. if (visibility === void 0) { visibility = 1; }
  19907. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  19908. };
  19909. Scene.prototype.getBoundingBoxRenderer = function () {
  19910. if (!this._boundingBoxRenderer) {
  19911. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  19912. }
  19913. return this._boundingBoxRenderer;
  19914. };
  19915. Scene.prototype.getOutlineRenderer = function () {
  19916. return this._outlineRenderer;
  19917. };
  19918. Scene.prototype.getEngine = function () {
  19919. return this._engine;
  19920. };
  19921. Scene.prototype.getTotalVertices = function () {
  19922. return this._totalVertices.current;
  19923. };
  19924. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  19925. get: function () {
  19926. return this._totalVertices;
  19927. },
  19928. enumerable: true,
  19929. configurable: true
  19930. });
  19931. Scene.prototype.getActiveIndices = function () {
  19932. return this._activeIndices.current;
  19933. };
  19934. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  19935. get: function () {
  19936. return this._activeIndices;
  19937. },
  19938. enumerable: true,
  19939. configurable: true
  19940. });
  19941. Scene.prototype.getActiveParticles = function () {
  19942. return this._activeParticles.current;
  19943. };
  19944. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  19945. get: function () {
  19946. return this._activeParticles;
  19947. },
  19948. enumerable: true,
  19949. configurable: true
  19950. });
  19951. Scene.prototype.getActiveBones = function () {
  19952. return this._activeBones.current;
  19953. };
  19954. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  19955. get: function () {
  19956. return this._activeBones;
  19957. },
  19958. enumerable: true,
  19959. configurable: true
  19960. });
  19961. // Stats
  19962. Scene.prototype.getInterFramePerfCounter = function () {
  19963. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  19964. return 0;
  19965. };
  19966. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  19967. get: function () {
  19968. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  19969. return null;
  19970. },
  19971. enumerable: true,
  19972. configurable: true
  19973. });
  19974. Scene.prototype.getLastFrameDuration = function () {
  19975. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  19976. return 0;
  19977. };
  19978. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  19979. get: function () {
  19980. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  19981. return null;
  19982. },
  19983. enumerable: true,
  19984. configurable: true
  19985. });
  19986. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  19987. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  19988. return 0;
  19989. };
  19990. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  19991. get: function () {
  19992. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  19993. return null;
  19994. },
  19995. enumerable: true,
  19996. configurable: true
  19997. });
  19998. Scene.prototype.getActiveMeshes = function () {
  19999. return this._activeMeshes;
  20000. };
  20001. Scene.prototype.getRenderTargetsDuration = function () {
  20002. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  20003. return 0;
  20004. };
  20005. Scene.prototype.getRenderDuration = function () {
  20006. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  20007. return 0;
  20008. };
  20009. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  20010. get: function () {
  20011. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20012. return null;
  20013. },
  20014. enumerable: true,
  20015. configurable: true
  20016. });
  20017. Scene.prototype.getParticlesDuration = function () {
  20018. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  20019. return 0;
  20020. };
  20021. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  20022. get: function () {
  20023. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20024. return null;
  20025. },
  20026. enumerable: true,
  20027. configurable: true
  20028. });
  20029. Scene.prototype.getSpritesDuration = function () {
  20030. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  20031. return 0;
  20032. };
  20033. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  20034. get: function () {
  20035. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  20036. return null;
  20037. },
  20038. enumerable: true,
  20039. configurable: true
  20040. });
  20041. Scene.prototype.getAnimationRatio = function () {
  20042. return this._animationRatio;
  20043. };
  20044. Scene.prototype.getRenderId = function () {
  20045. return this._renderId;
  20046. };
  20047. Scene.prototype.incrementRenderId = function () {
  20048. this._renderId++;
  20049. };
  20050. Scene.prototype._updatePointerPosition = function (evt) {
  20051. var canvasRect = this._engine.getRenderingCanvasClientRect();
  20052. if (!canvasRect) {
  20053. return;
  20054. }
  20055. this._pointerX = evt.clientX - canvasRect.left;
  20056. this._pointerY = evt.clientY - canvasRect.top;
  20057. this._unTranslatedPointerX = this._pointerX;
  20058. this._unTranslatedPointerY = this._pointerY;
  20059. };
  20060. Scene.prototype._createUbo = function () {
  20061. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20062. this._sceneUbo.addUniform("viewProjection", 16);
  20063. this._sceneUbo.addUniform("view", 16);
  20064. };
  20065. Scene.prototype._createAlternateUbo = function () {
  20066. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20067. this._alternateSceneUbo.addUniform("viewProjection", 16);
  20068. this._alternateSceneUbo.addUniform("view", 16);
  20069. };
  20070. // Pointers handling
  20071. /**
  20072. * Use this method to simulate a pointer move on a mesh
  20073. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20074. */
  20075. Scene.prototype.simulatePointerMove = function (pickResult) {
  20076. var evt = new PointerEvent("pointermove");
  20077. return this._processPointerMove(pickResult, evt);
  20078. };
  20079. Scene.prototype._processPointerMove = function (pickResult, evt) {
  20080. var canvas = this._engine.getRenderingCanvas();
  20081. if (!canvas) {
  20082. return this;
  20083. }
  20084. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20085. this.setPointerOverSprite(null);
  20086. this.setPointerOverMesh(pickResult.pickedMesh);
  20087. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  20088. if (this._pointerOverMesh.actionManager.hoverCursor) {
  20089. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  20090. }
  20091. else {
  20092. canvas.style.cursor = this.hoverCursor;
  20093. }
  20094. }
  20095. else {
  20096. canvas.style.cursor = this.defaultCursor;
  20097. }
  20098. }
  20099. else {
  20100. this.setPointerOverMesh(null);
  20101. // Sprites
  20102. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  20103. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20104. this.setPointerOverSprite(pickResult.pickedSprite);
  20105. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  20106. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  20107. }
  20108. else {
  20109. canvas.style.cursor = this.hoverCursor;
  20110. }
  20111. }
  20112. else {
  20113. this.setPointerOverSprite(null);
  20114. // Restore pointer
  20115. canvas.style.cursor = this.defaultCursor;
  20116. }
  20117. }
  20118. if (pickResult) {
  20119. if (this.onPointerMove) {
  20120. this.onPointerMove(evt, pickResult);
  20121. }
  20122. if (this.onPointerObservable.hasObservers()) {
  20123. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20124. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20125. this.onPointerObservable.notifyObservers(pi, type);
  20126. }
  20127. }
  20128. return this;
  20129. };
  20130. /**
  20131. * Use this method to simulate a pointer down on a mesh
  20132. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20133. */
  20134. Scene.prototype.simulatePointerDown = function (pickResult) {
  20135. var evt = new PointerEvent("pointerdown");
  20136. return this._processPointerDown(pickResult, evt);
  20137. };
  20138. Scene.prototype._processPointerDown = function (pickResult, evt) {
  20139. var _this = this;
  20140. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20141. this._pickedDownMesh = pickResult.pickedMesh;
  20142. var actionManager = pickResult.pickedMesh.actionManager;
  20143. if (actionManager) {
  20144. if (actionManager.hasPickTriggers) {
  20145. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20146. switch (evt.button) {
  20147. case 0:
  20148. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20149. break;
  20150. case 1:
  20151. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20152. break;
  20153. case 2:
  20154. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20155. break;
  20156. }
  20157. }
  20158. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  20159. window.setTimeout(function () {
  20160. 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);
  20161. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  20162. if (_this._totalPointersPressed !== 0 &&
  20163. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  20164. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  20165. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  20166. _this._startingPointerTime = 0;
  20167. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20168. }
  20169. }
  20170. }, Scene.LongPressDelay);
  20171. }
  20172. }
  20173. }
  20174. if (pickResult) {
  20175. if (this.onPointerDown) {
  20176. this.onPointerDown(evt, pickResult);
  20177. }
  20178. if (this.onPointerObservable.hasObservers()) {
  20179. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20180. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20181. this.onPointerObservable.notifyObservers(pi, type);
  20182. }
  20183. }
  20184. return this;
  20185. };
  20186. /**
  20187. * Use this method to simulate a pointer up on a mesh
  20188. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20189. */
  20190. Scene.prototype.simulatePointerUp = function (pickResult) {
  20191. var evt = new PointerEvent("pointerup");
  20192. var clickInfo = new ClickInfo();
  20193. clickInfo.singleClick = true;
  20194. clickInfo.ignore = true;
  20195. return this._processPointerUp(pickResult, evt, clickInfo);
  20196. };
  20197. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  20198. if (pickResult && pickResult && pickResult.pickedMesh) {
  20199. this._pickedUpMesh = pickResult.pickedMesh;
  20200. if (this._pickedDownMesh === this._pickedUpMesh) {
  20201. if (this.onPointerPick) {
  20202. this.onPointerPick(evt, pickResult);
  20203. }
  20204. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  20205. var type = BABYLON.PointerEventTypes.POINTERPICK;
  20206. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20207. this.onPointerObservable.notifyObservers(pi, type);
  20208. }
  20209. }
  20210. if (pickResult.pickedMesh.actionManager) {
  20211. if (clickInfo.ignore) {
  20212. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20213. }
  20214. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  20215. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20216. }
  20217. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20218. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20219. }
  20220. }
  20221. }
  20222. if (this._pickedDownMesh &&
  20223. this._pickedDownMesh.actionManager &&
  20224. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  20225. this._pickedDownMesh !== this._pickedUpMesh) {
  20226. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  20227. }
  20228. if (this.onPointerUp) {
  20229. this.onPointerUp(evt, pickResult);
  20230. }
  20231. if (this.onPointerObservable.hasObservers()) {
  20232. if (!clickInfo.ignore) {
  20233. if (!clickInfo.hasSwiped) {
  20234. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20235. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20236. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20237. this.onPointerObservable.notifyObservers(pi, type);
  20238. }
  20239. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20240. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20241. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20242. this.onPointerObservable.notifyObservers(pi, type);
  20243. }
  20244. }
  20245. }
  20246. else {
  20247. var type = BABYLON.PointerEventTypes.POINTERUP;
  20248. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20249. this.onPointerObservable.notifyObservers(pi, type);
  20250. }
  20251. }
  20252. return this;
  20253. };
  20254. /**
  20255. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  20256. * @param attachUp defines if you want to attach events to pointerup
  20257. * @param attachDown defines if you want to attach events to pointerdown
  20258. * @param attachMove defines if you want to attach events to pointermove
  20259. */
  20260. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  20261. var _this = this;
  20262. if (attachUp === void 0) { attachUp = true; }
  20263. if (attachDown === void 0) { attachDown = true; }
  20264. if (attachMove === void 0) { attachMove = true; }
  20265. this._initActionManager = function (act, clickInfo) {
  20266. if (!_this._meshPickProceed) {
  20267. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20268. _this._currentPickResult = pickResult;
  20269. if (pickResult) {
  20270. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  20271. }
  20272. _this._meshPickProceed = true;
  20273. }
  20274. return act;
  20275. };
  20276. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  20277. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  20278. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  20279. btn !== _this._previousButtonPressed) {
  20280. _this._doubleClickOccured = false;
  20281. clickInfo.singleClick = true;
  20282. clickInfo.ignore = false;
  20283. cb(clickInfo, _this._currentPickResult);
  20284. }
  20285. };
  20286. this._initClickEvent = function (obs1, obs2, evt, cb) {
  20287. var clickInfo = new ClickInfo();
  20288. _this._currentPickResult = null;
  20289. var act = null;
  20290. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  20291. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  20292. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20293. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  20294. act = _this._initActionManager(act, clickInfo);
  20295. if (act)
  20296. checkPicking = act.hasPickTriggers;
  20297. }
  20298. if (checkPicking) {
  20299. var btn = evt.button;
  20300. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  20301. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  20302. if (!clickInfo.hasSwiped) {
  20303. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  20304. if (!checkSingleClickImmediately) {
  20305. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  20306. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20307. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20308. act = _this._initActionManager(act, clickInfo);
  20309. if (act)
  20310. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20311. }
  20312. }
  20313. if (checkSingleClickImmediately) {
  20314. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  20315. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  20316. btn !== _this._previousButtonPressed) {
  20317. clickInfo.singleClick = true;
  20318. cb(clickInfo, _this._currentPickResult);
  20319. }
  20320. }
  20321. else {
  20322. // wait that no double click has been raised during the double click delay
  20323. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20324. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  20325. }
  20326. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  20327. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20328. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20329. act = _this._initActionManager(act, clickInfo);
  20330. if (act)
  20331. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20332. }
  20333. if (checkDoubleClick) {
  20334. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  20335. if (btn === _this._previousButtonPressed &&
  20336. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  20337. !_this._doubleClickOccured) {
  20338. // pointer has not moved for 2 clicks, it's a double click
  20339. if (!clickInfo.hasSwiped &&
  20340. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  20341. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  20342. _this._previousStartingPointerTime = 0;
  20343. _this._doubleClickOccured = true;
  20344. clickInfo.doubleClick = true;
  20345. clickInfo.ignore = false;
  20346. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  20347. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20348. }
  20349. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20350. cb(clickInfo, _this._currentPickResult);
  20351. }
  20352. else {
  20353. _this._doubleClickOccured = false;
  20354. _this._previousStartingPointerTime = _this._startingPointerTime;
  20355. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20356. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20357. _this._previousButtonPressed = btn;
  20358. if (Scene.ExclusiveDoubleClickMode) {
  20359. if (_this._previousDelayedSimpleClickTimeout) {
  20360. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20361. }
  20362. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20363. cb(clickInfo, _this._previousPickResult);
  20364. }
  20365. else {
  20366. cb(clickInfo, _this._currentPickResult);
  20367. }
  20368. }
  20369. }
  20370. else {
  20371. _this._doubleClickOccured = false;
  20372. _this._previousStartingPointerTime = _this._startingPointerTime;
  20373. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20374. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20375. _this._previousButtonPressed = btn;
  20376. }
  20377. }
  20378. }
  20379. }
  20380. clickInfo.ignore = true;
  20381. cb(clickInfo, _this._currentPickResult);
  20382. };
  20383. this._spritePredicate = function (sprite) {
  20384. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  20385. };
  20386. this._onPointerMove = function (evt) {
  20387. _this._updatePointerPosition(evt);
  20388. // PreObservable support
  20389. if (_this.onPrePointerObservable.hasObservers()) {
  20390. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20391. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20392. _this.onPrePointerObservable.notifyObservers(pi, type);
  20393. if (pi.skipOnPointerObservable) {
  20394. return;
  20395. }
  20396. }
  20397. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20398. return;
  20399. }
  20400. if (!_this.pointerMovePredicate) {
  20401. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  20402. }
  20403. // Meshes
  20404. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  20405. _this._processPointerMove(pickResult, evt);
  20406. };
  20407. this._onPointerDown = function (evt) {
  20408. _this._totalPointersPressed++;
  20409. _this._pickedDownMesh = null;
  20410. _this._meshPickProceed = false;
  20411. _this._updatePointerPosition(evt);
  20412. if (_this.preventDefaultOnPointerDown && canvas) {
  20413. evt.preventDefault();
  20414. canvas.focus();
  20415. }
  20416. // PreObservable support
  20417. if (_this.onPrePointerObservable.hasObservers()) {
  20418. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20419. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20420. _this.onPrePointerObservable.notifyObservers(pi, type);
  20421. if (pi.skipOnPointerObservable) {
  20422. return;
  20423. }
  20424. }
  20425. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20426. return;
  20427. }
  20428. _this._startingPointerPosition.x = _this._pointerX;
  20429. _this._startingPointerPosition.y = _this._pointerY;
  20430. _this._startingPointerTime = new Date().getTime();
  20431. if (!_this.pointerDownPredicate) {
  20432. _this.pointerDownPredicate = function (mesh) {
  20433. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  20434. };
  20435. }
  20436. // Meshes
  20437. _this._pickedDownMesh = null;
  20438. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20439. _this._processPointerDown(pickResult, evt);
  20440. // Sprites
  20441. _this._pickedDownSprite = null;
  20442. if (_this.spriteManagers.length > 0) {
  20443. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  20444. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20445. if (pickResult.pickedSprite.actionManager) {
  20446. _this._pickedDownSprite = pickResult.pickedSprite;
  20447. switch (evt.button) {
  20448. case 0:
  20449. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20450. break;
  20451. case 1:
  20452. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20453. break;
  20454. case 2:
  20455. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20456. break;
  20457. }
  20458. if (pickResult.pickedSprite.actionManager) {
  20459. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20460. }
  20461. }
  20462. }
  20463. }
  20464. };
  20465. this._onPointerUp = function (evt) {
  20466. if (_this._totalPointersPressed === 0) {
  20467. return; // So we need to test it the pointer down was pressed before.
  20468. }
  20469. _this._totalPointersPressed--;
  20470. _this._pickedUpMesh = null;
  20471. _this._meshPickProceed = false;
  20472. _this._updatePointerPosition(evt);
  20473. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  20474. // PreObservable support
  20475. if (_this.onPrePointerObservable.hasObservers()) {
  20476. if (!clickInfo.ignore) {
  20477. if (!clickInfo.hasSwiped) {
  20478. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20479. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20480. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20481. _this.onPrePointerObservable.notifyObservers(pi, type);
  20482. if (pi.skipOnPointerObservable) {
  20483. return;
  20484. }
  20485. }
  20486. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20487. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20488. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20489. _this.onPrePointerObservable.notifyObservers(pi, type);
  20490. if (pi.skipOnPointerObservable) {
  20491. return;
  20492. }
  20493. }
  20494. }
  20495. }
  20496. else {
  20497. var type = BABYLON.PointerEventTypes.POINTERUP;
  20498. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20499. _this.onPrePointerObservable.notifyObservers(pi, type);
  20500. if (pi.skipOnPointerObservable) {
  20501. return;
  20502. }
  20503. }
  20504. }
  20505. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20506. return;
  20507. }
  20508. if (!_this.pointerUpPredicate) {
  20509. _this.pointerUpPredicate = function (mesh) {
  20510. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  20511. };
  20512. }
  20513. // Meshes
  20514. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  20515. _this._initActionManager(null, clickInfo);
  20516. }
  20517. if (!pickResult) {
  20518. pickResult = _this._currentPickResult;
  20519. }
  20520. _this._processPointerUp(pickResult, evt, clickInfo);
  20521. // Sprites
  20522. if (_this.spriteManagers.length > 0) {
  20523. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  20524. if (spritePickResult) {
  20525. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  20526. if (spritePickResult.pickedSprite.actionManager) {
  20527. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  20528. if (spritePickResult.pickedSprite.actionManager) {
  20529. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  20530. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  20531. }
  20532. }
  20533. }
  20534. }
  20535. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  20536. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  20537. }
  20538. }
  20539. }
  20540. _this._previousPickResult = _this._currentPickResult;
  20541. });
  20542. };
  20543. this._onKeyDown = function (evt) {
  20544. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  20545. if (_this.onPreKeyboardObservable.hasObservers()) {
  20546. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  20547. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  20548. if (pi.skipOnPointerObservable) {
  20549. return;
  20550. }
  20551. }
  20552. if (_this.onKeyboardObservable.hasObservers()) {
  20553. var pi = new BABYLON.KeyboardInfo(type, evt);
  20554. _this.onKeyboardObservable.notifyObservers(pi, type);
  20555. }
  20556. if (_this.actionManager) {
  20557. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20558. }
  20559. };
  20560. this._onKeyUp = function (evt) {
  20561. var type = BABYLON.KeyboardEventTypes.KEYUP;
  20562. if (_this.onPreKeyboardObservable.hasObservers()) {
  20563. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  20564. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  20565. if (pi.skipOnPointerObservable) {
  20566. return;
  20567. }
  20568. }
  20569. if (_this.onKeyboardObservable.hasObservers()) {
  20570. var pi = new BABYLON.KeyboardInfo(type, evt);
  20571. _this.onKeyboardObservable.notifyObservers(pi, type);
  20572. }
  20573. if (_this.actionManager) {
  20574. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20575. }
  20576. };
  20577. var engine = this.getEngine();
  20578. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  20579. if (!canvas) {
  20580. return;
  20581. }
  20582. canvas.addEventListener("keydown", _this._onKeyDown, false);
  20583. canvas.addEventListener("keyup", _this._onKeyUp, false);
  20584. });
  20585. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  20586. if (!canvas) {
  20587. return;
  20588. }
  20589. canvas.removeEventListener("keydown", _this._onKeyDown);
  20590. canvas.removeEventListener("keyup", _this._onKeyUp);
  20591. });
  20592. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20593. var canvas = this._engine.getRenderingCanvas();
  20594. if (!canvas) {
  20595. return;
  20596. }
  20597. if (attachMove) {
  20598. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  20599. // Wheel
  20600. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  20601. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  20602. }
  20603. if (attachDown) {
  20604. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  20605. }
  20606. if (attachUp) {
  20607. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  20608. }
  20609. canvas.tabIndex = 1;
  20610. };
  20611. Scene.prototype.detachControl = function () {
  20612. var engine = this.getEngine();
  20613. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20614. var canvas = engine.getRenderingCanvas();
  20615. if (!canvas) {
  20616. return;
  20617. }
  20618. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  20619. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  20620. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  20621. if (this._onCanvasBlurObserver) {
  20622. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  20623. }
  20624. if (this._onCanvasFocusObserver) {
  20625. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  20626. }
  20627. // Wheel
  20628. canvas.removeEventListener('mousewheel', this._onPointerMove);
  20629. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  20630. // Keyboard
  20631. canvas.removeEventListener("keydown", this._onKeyDown);
  20632. canvas.removeEventListener("keyup", this._onKeyUp);
  20633. // Observables
  20634. this.onKeyboardObservable.clear();
  20635. this.onPreKeyboardObservable.clear();
  20636. this.onPointerObservable.clear();
  20637. this.onPrePointerObservable.clear();
  20638. };
  20639. // Ready
  20640. Scene.prototype.isReady = function () {
  20641. if (this._isDisposed) {
  20642. return false;
  20643. }
  20644. if (this._pendingData.length > 0) {
  20645. return false;
  20646. }
  20647. var index;
  20648. // Geometries
  20649. for (index = 0; index < this._geometries.length; index++) {
  20650. var geometry = this._geometries[index];
  20651. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20652. return false;
  20653. }
  20654. }
  20655. // Meshes
  20656. for (index = 0; index < this.meshes.length; index++) {
  20657. var mesh = this.meshes[index];
  20658. if (!mesh.isEnabled()) {
  20659. continue;
  20660. }
  20661. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  20662. continue;
  20663. }
  20664. if (!mesh.isReady()) {
  20665. return false;
  20666. }
  20667. var mat = mesh.material;
  20668. if (mat) {
  20669. if (!mat.isReady(mesh)) {
  20670. return false;
  20671. }
  20672. }
  20673. }
  20674. return true;
  20675. };
  20676. Scene.prototype.resetCachedMaterial = function () {
  20677. this._cachedMaterial = null;
  20678. this._cachedEffect = null;
  20679. this._cachedVisibility = null;
  20680. };
  20681. Scene.prototype.registerBeforeRender = function (func) {
  20682. this.onBeforeRenderObservable.add(func);
  20683. };
  20684. Scene.prototype.unregisterBeforeRender = function (func) {
  20685. this.onBeforeRenderObservable.removeCallback(func);
  20686. };
  20687. Scene.prototype.registerAfterRender = function (func) {
  20688. this.onAfterRenderObservable.add(func);
  20689. };
  20690. Scene.prototype.unregisterAfterRender = function (func) {
  20691. this.onAfterRenderObservable.removeCallback(func);
  20692. };
  20693. Scene.prototype._addPendingData = function (data) {
  20694. this._pendingData.push(data);
  20695. };
  20696. Scene.prototype._removePendingData = function (data) {
  20697. var wasLoading = this.isLoading;
  20698. var index = this._pendingData.indexOf(data);
  20699. if (index !== -1) {
  20700. this._pendingData.splice(index, 1);
  20701. }
  20702. if (wasLoading && !this.isLoading) {
  20703. this.onDataLoadedObservable.notifyObservers(this);
  20704. }
  20705. };
  20706. Scene.prototype.getWaitingItemsCount = function () {
  20707. return this._pendingData.length;
  20708. };
  20709. Object.defineProperty(Scene.prototype, "isLoading", {
  20710. get: function () {
  20711. return this._pendingData.length > 0;
  20712. },
  20713. enumerable: true,
  20714. configurable: true
  20715. });
  20716. /**
  20717. * Registers a function to be executed when the scene is ready.
  20718. * @param {Function} func - the function to be executed.
  20719. */
  20720. Scene.prototype.executeWhenReady = function (func) {
  20721. var _this = this;
  20722. this.onReadyObservable.add(func);
  20723. if (this._executeWhenReadyTimeoutId !== -1) {
  20724. return;
  20725. }
  20726. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20727. _this._checkIsReady();
  20728. }, 150);
  20729. };
  20730. Scene.prototype._checkIsReady = function () {
  20731. var _this = this;
  20732. if (this.isReady()) {
  20733. this.onReadyObservable.notifyObservers(this);
  20734. this.onReadyObservable.clear();
  20735. this._executeWhenReadyTimeoutId = -1;
  20736. return;
  20737. }
  20738. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20739. _this._checkIsReady();
  20740. }, 150);
  20741. };
  20742. // Animations
  20743. /**
  20744. * Will start the animation sequence of a given target
  20745. * @param target - the target
  20746. * @param {number} from - from which frame should animation start
  20747. * @param {number} to - till which frame should animation run.
  20748. * @param {boolean} [loop] - should the animation loop
  20749. * @param {number} [speedRatio] - the speed in which to run the animation
  20750. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  20751. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  20752. * Returns {BABYLON.Animatable} the animatable object created for this animation
  20753. * See BABYLON.Animatable
  20754. */
  20755. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  20756. if (speedRatio === void 0) { speedRatio = 1.0; }
  20757. if (from > to && speedRatio > 0) {
  20758. speedRatio *= -1;
  20759. }
  20760. this.stopAnimation(target);
  20761. if (!animatable) {
  20762. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  20763. }
  20764. // Local animations
  20765. if (target.animations) {
  20766. animatable.appendAnimations(target, target.animations);
  20767. }
  20768. // Children animations
  20769. if (target.getAnimatables) {
  20770. var animatables = target.getAnimatables();
  20771. for (var index = 0; index < animatables.length; index++) {
  20772. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  20773. }
  20774. }
  20775. animatable.reset();
  20776. return animatable;
  20777. };
  20778. /**
  20779. * Begin a new animation on a given node
  20780. * @param {BABYLON.Node} node defines the root node where the animation will take place
  20781. * @param {BABYLON.Animation[]} defines the list of animations to start
  20782. * @param {number} from defines the initial value
  20783. * @param {number} to defines the final value
  20784. * @param {boolean} loop defines if you want animation to loop (off by default)
  20785. * @param {number} speedRatio defines the speed ratio to apply to all animations
  20786. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  20787. * @returns the list of created animatables
  20788. */
  20789. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  20790. if (speedRatio === undefined) {
  20791. speedRatio = 1.0;
  20792. }
  20793. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  20794. return animatable;
  20795. };
  20796. /**
  20797. * Begin a new animation on a given node and its hierarchy
  20798. * @param {BABYLON.Node} node defines the root node where the animation will take place
  20799. * @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.
  20800. * @param {BABYLON.Animation[]} defines the list of animations to start
  20801. * @param {number} from defines the initial value
  20802. * @param {number} to defines the final value
  20803. * @param {boolean} loop defines if you want animation to loop (off by default)
  20804. * @param {number} speedRatio defines the speed ratio to apply to all animations
  20805. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  20806. * @returns the list of animatables created for all nodes
  20807. */
  20808. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  20809. var children = target.getDescendants(directDescendantsOnly);
  20810. var result = [];
  20811. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  20812. var child = children_1[_i];
  20813. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  20814. }
  20815. return result;
  20816. };
  20817. Scene.prototype.getAnimatableByTarget = function (target) {
  20818. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20819. if (this._activeAnimatables[index].target === target) {
  20820. return this._activeAnimatables[index];
  20821. }
  20822. }
  20823. return null;
  20824. };
  20825. Object.defineProperty(Scene.prototype, "animatables", {
  20826. get: function () {
  20827. return this._activeAnimatables;
  20828. },
  20829. enumerable: true,
  20830. configurable: true
  20831. });
  20832. /**
  20833. * Will stop the animation of the given target
  20834. * @param target - the target
  20835. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  20836. * @see beginAnimation
  20837. */
  20838. Scene.prototype.stopAnimation = function (target, animationName) {
  20839. var animatable = this.getAnimatableByTarget(target);
  20840. if (animatable) {
  20841. animatable.stop(animationName);
  20842. }
  20843. };
  20844. /**
  20845. * Stops and removes all animations that have been applied to the scene
  20846. */
  20847. Scene.prototype.stopAllAnimations = function () {
  20848. if (this._activeAnimatables) {
  20849. for (var i = 0; i < this._activeAnimatables.length; i++) {
  20850. this._activeAnimatables[i].stop();
  20851. }
  20852. this._activeAnimatables = [];
  20853. }
  20854. };
  20855. Scene.prototype._animate = function () {
  20856. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  20857. return;
  20858. }
  20859. // Getting time
  20860. var now = BABYLON.Tools.Now;
  20861. if (!this._animationTimeLast) {
  20862. if (this._pendingData.length > 0) {
  20863. return;
  20864. }
  20865. this._animationTimeLast = now;
  20866. }
  20867. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  20868. this._animationTime += deltaTime;
  20869. this._animationTimeLast = now;
  20870. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20871. this._activeAnimatables[index]._animate(this._animationTime);
  20872. }
  20873. };
  20874. // Matrix
  20875. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  20876. this._useAlternateCameraConfiguration = active;
  20877. };
  20878. Scene.prototype.getViewMatrix = function () {
  20879. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  20880. };
  20881. Scene.prototype.getProjectionMatrix = function () {
  20882. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  20883. };
  20884. Scene.prototype.getTransformMatrix = function () {
  20885. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  20886. };
  20887. Scene.prototype.setTransformMatrix = function (view, projection) {
  20888. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  20889. return;
  20890. }
  20891. this._viewUpdateFlag = view.updateFlag;
  20892. this._projectionUpdateFlag = projection.updateFlag;
  20893. this._viewMatrix = view;
  20894. this._projectionMatrix = projection;
  20895. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20896. // Update frustum
  20897. if (!this._frustumPlanes) {
  20898. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20899. }
  20900. else {
  20901. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20902. }
  20903. if (this.activeCamera && this.activeCamera._alternateCamera) {
  20904. var otherCamera = this.activeCamera._alternateCamera;
  20905. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  20906. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  20907. }
  20908. if (this._sceneUbo.useUbo) {
  20909. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  20910. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  20911. this._sceneUbo.update();
  20912. }
  20913. };
  20914. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  20915. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  20916. return;
  20917. }
  20918. this._alternateViewUpdateFlag = view.updateFlag;
  20919. this._alternateProjectionUpdateFlag = projection.updateFlag;
  20920. this._alternateViewMatrix = view;
  20921. this._alternateProjectionMatrix = projection;
  20922. if (!this._alternateTransformMatrix) {
  20923. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  20924. }
  20925. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  20926. if (!this._alternateSceneUbo) {
  20927. this._createAlternateUbo();
  20928. }
  20929. if (this._alternateSceneUbo.useUbo) {
  20930. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  20931. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  20932. this._alternateSceneUbo.update();
  20933. }
  20934. };
  20935. Scene.prototype.getSceneUniformBuffer = function () {
  20936. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  20937. };
  20938. // Methods
  20939. Scene.prototype.getUniqueId = function () {
  20940. var result = Scene._uniqueIdCounter;
  20941. Scene._uniqueIdCounter++;
  20942. return result;
  20943. };
  20944. Scene.prototype.addMesh = function (newMesh) {
  20945. this.meshes.push(newMesh);
  20946. //notify the collision coordinator
  20947. if (this.collisionCoordinator) {
  20948. this.collisionCoordinator.onMeshAdded(newMesh);
  20949. }
  20950. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  20951. };
  20952. Scene.prototype.removeMesh = function (toRemove) {
  20953. var index = this.meshes.indexOf(toRemove);
  20954. if (index !== -1) {
  20955. // Remove from the scene if mesh found
  20956. this.meshes.splice(index, 1);
  20957. }
  20958. this.onMeshRemovedObservable.notifyObservers(toRemove);
  20959. return index;
  20960. };
  20961. Scene.prototype.addTransformNode = function (newTransformNode) {
  20962. this.transformNodes.push(newTransformNode);
  20963. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  20964. };
  20965. Scene.prototype.removeTransformNode = function (toRemove) {
  20966. var index = this.transformNodes.indexOf(toRemove);
  20967. if (index !== -1) {
  20968. // Remove from the scene if found
  20969. this.transformNodes.splice(index, 1);
  20970. }
  20971. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  20972. return index;
  20973. };
  20974. Scene.prototype.removeSkeleton = function (toRemove) {
  20975. var index = this.skeletons.indexOf(toRemove);
  20976. if (index !== -1) {
  20977. // Remove from the scene if found
  20978. this.skeletons.splice(index, 1);
  20979. }
  20980. return index;
  20981. };
  20982. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  20983. var index = this.morphTargetManagers.indexOf(toRemove);
  20984. if (index !== -1) {
  20985. // Remove from the scene if found
  20986. this.morphTargetManagers.splice(index, 1);
  20987. }
  20988. return index;
  20989. };
  20990. Scene.prototype.removeLight = function (toRemove) {
  20991. var index = this.lights.indexOf(toRemove);
  20992. if (index !== -1) {
  20993. // Remove from meshes
  20994. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  20995. var mesh = _a[_i];
  20996. mesh._removeLightSource(toRemove);
  20997. }
  20998. // Remove from the scene if mesh found
  20999. this.lights.splice(index, 1);
  21000. this.sortLightsByPriority();
  21001. }
  21002. this.onLightRemovedObservable.notifyObservers(toRemove);
  21003. return index;
  21004. };
  21005. Scene.prototype.removeCamera = function (toRemove) {
  21006. var index = this.cameras.indexOf(toRemove);
  21007. if (index !== -1) {
  21008. // Remove from the scene if mesh found
  21009. this.cameras.splice(index, 1);
  21010. }
  21011. // Remove from activeCameras
  21012. var index2 = this.activeCameras.indexOf(toRemove);
  21013. if (index2 !== -1) {
  21014. // Remove from the scene if mesh found
  21015. this.activeCameras.splice(index2, 1);
  21016. }
  21017. // Reset the activeCamera
  21018. if (this.activeCamera === toRemove) {
  21019. if (this.cameras.length > 0) {
  21020. this.activeCamera = this.cameras[0];
  21021. }
  21022. else {
  21023. this.activeCamera = null;
  21024. }
  21025. }
  21026. this.onCameraRemovedObservable.notifyObservers(toRemove);
  21027. return index;
  21028. };
  21029. Scene.prototype.addLight = function (newLight) {
  21030. this.lights.push(newLight);
  21031. this.sortLightsByPriority();
  21032. // Add light to all meshes (To support if the light is removed and then readded)
  21033. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21034. var mesh = _a[_i];
  21035. if (mesh._lightSources.indexOf(newLight) === -1) {
  21036. mesh._lightSources.push(newLight);
  21037. mesh._resyncLightSources();
  21038. }
  21039. }
  21040. this.onNewLightAddedObservable.notifyObservers(newLight);
  21041. };
  21042. Scene.prototype.sortLightsByPriority = function () {
  21043. if (this.requireLightSorting) {
  21044. this.lights.sort(BABYLON.Light.compareLightsPriority);
  21045. }
  21046. };
  21047. Scene.prototype.addCamera = function (newCamera) {
  21048. this.cameras.push(newCamera);
  21049. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  21050. };
  21051. /**
  21052. * Switch active camera
  21053. * @param {Camera} newCamera - new active camera
  21054. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  21055. */
  21056. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  21057. if (attachControl === void 0) { attachControl = true; }
  21058. var canvas = this._engine.getRenderingCanvas();
  21059. if (!canvas) {
  21060. return;
  21061. }
  21062. if (this.activeCamera) {
  21063. this.activeCamera.detachControl(canvas);
  21064. }
  21065. this.activeCamera = newCamera;
  21066. if (attachControl) {
  21067. newCamera.attachControl(canvas);
  21068. }
  21069. };
  21070. /**
  21071. * sets the active camera of the scene using its ID
  21072. * @param {string} id - the camera's ID
  21073. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21074. * @see activeCamera
  21075. */
  21076. Scene.prototype.setActiveCameraByID = function (id) {
  21077. var camera = this.getCameraByID(id);
  21078. if (camera) {
  21079. this.activeCamera = camera;
  21080. return camera;
  21081. }
  21082. return null;
  21083. };
  21084. /**
  21085. * sets the active camera of the scene using its name
  21086. * @param {string} name - the camera's name
  21087. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21088. * @see activeCamera
  21089. */
  21090. Scene.prototype.setActiveCameraByName = function (name) {
  21091. var camera = this.getCameraByName(name);
  21092. if (camera) {
  21093. this.activeCamera = camera;
  21094. return camera;
  21095. }
  21096. return null;
  21097. };
  21098. /**
  21099. * get an animation group using its name
  21100. * @param {string} the material's name
  21101. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  21102. */
  21103. Scene.prototype.getAnimationGroupByName = function (name) {
  21104. for (var index = 0; index < this.animationGroups.length; index++) {
  21105. if (this.animationGroups[index].name === name) {
  21106. return this.animationGroups[index];
  21107. }
  21108. }
  21109. return null;
  21110. };
  21111. /**
  21112. * get a material using its id
  21113. * @param {string} the material's ID
  21114. * @return {BABYLON.Material|null} the material or null if none found.
  21115. */
  21116. Scene.prototype.getMaterialByID = function (id) {
  21117. for (var index = 0; index < this.materials.length; index++) {
  21118. if (this.materials[index].id === id) {
  21119. return this.materials[index];
  21120. }
  21121. }
  21122. return null;
  21123. };
  21124. /**
  21125. * get a material using its name
  21126. * @param {string} the material's name
  21127. * @return {BABYLON.Material|null} the material or null if none found.
  21128. */
  21129. Scene.prototype.getMaterialByName = function (name) {
  21130. for (var index = 0; index < this.materials.length; index++) {
  21131. if (this.materials[index].name === name) {
  21132. return this.materials[index];
  21133. }
  21134. }
  21135. return null;
  21136. };
  21137. Scene.prototype.getLensFlareSystemByName = function (name) {
  21138. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21139. if (this.lensFlareSystems[index].name === name) {
  21140. return this.lensFlareSystems[index];
  21141. }
  21142. }
  21143. return null;
  21144. };
  21145. Scene.prototype.getLensFlareSystemByID = function (id) {
  21146. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21147. if (this.lensFlareSystems[index].id === id) {
  21148. return this.lensFlareSystems[index];
  21149. }
  21150. }
  21151. return null;
  21152. };
  21153. Scene.prototype.getCameraByID = function (id) {
  21154. for (var index = 0; index < this.cameras.length; index++) {
  21155. if (this.cameras[index].id === id) {
  21156. return this.cameras[index];
  21157. }
  21158. }
  21159. return null;
  21160. };
  21161. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  21162. for (var index = 0; index < this.cameras.length; index++) {
  21163. if (this.cameras[index].uniqueId === uniqueId) {
  21164. return this.cameras[index];
  21165. }
  21166. }
  21167. return null;
  21168. };
  21169. /**
  21170. * get a camera using its name
  21171. * @param {string} the camera's name
  21172. * @return {BABYLON.Camera|null} the camera or null if none found.
  21173. */
  21174. Scene.prototype.getCameraByName = function (name) {
  21175. for (var index = 0; index < this.cameras.length; index++) {
  21176. if (this.cameras[index].name === name) {
  21177. return this.cameras[index];
  21178. }
  21179. }
  21180. return null;
  21181. };
  21182. /**
  21183. * get a bone using its id
  21184. * @param {string} the bone's id
  21185. * @return {BABYLON.Bone|null} the bone or null if not found
  21186. */
  21187. Scene.prototype.getBoneByID = function (id) {
  21188. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21189. var skeleton = this.skeletons[skeletonIndex];
  21190. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21191. if (skeleton.bones[boneIndex].id === id) {
  21192. return skeleton.bones[boneIndex];
  21193. }
  21194. }
  21195. }
  21196. return null;
  21197. };
  21198. /**
  21199. * get a bone using its id
  21200. * @param {string} the bone's name
  21201. * @return {BABYLON.Bone|null} the bone or null if not found
  21202. */
  21203. Scene.prototype.getBoneByName = function (name) {
  21204. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21205. var skeleton = this.skeletons[skeletonIndex];
  21206. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21207. if (skeleton.bones[boneIndex].name === name) {
  21208. return skeleton.bones[boneIndex];
  21209. }
  21210. }
  21211. }
  21212. return null;
  21213. };
  21214. /**
  21215. * get a light node using its name
  21216. * @param {string} the light's name
  21217. * @return {BABYLON.Light|null} the light or null if none found.
  21218. */
  21219. Scene.prototype.getLightByName = function (name) {
  21220. for (var index = 0; index < this.lights.length; index++) {
  21221. if (this.lights[index].name === name) {
  21222. return this.lights[index];
  21223. }
  21224. }
  21225. return null;
  21226. };
  21227. /**
  21228. * get a light node using its ID
  21229. * @param {string} the light's id
  21230. * @return {BABYLON.Light|null} the light or null if none found.
  21231. */
  21232. Scene.prototype.getLightByID = function (id) {
  21233. for (var index = 0; index < this.lights.length; index++) {
  21234. if (this.lights[index].id === id) {
  21235. return this.lights[index];
  21236. }
  21237. }
  21238. return null;
  21239. };
  21240. /**
  21241. * get a light node using its scene-generated unique ID
  21242. * @param {number} the light's unique id
  21243. * @return {BABYLON.Light|null} the light or null if none found.
  21244. */
  21245. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  21246. for (var index = 0; index < this.lights.length; index++) {
  21247. if (this.lights[index].uniqueId === uniqueId) {
  21248. return this.lights[index];
  21249. }
  21250. }
  21251. return null;
  21252. };
  21253. /**
  21254. * get a particle system by id
  21255. * @param id {number} the particle system id
  21256. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  21257. */
  21258. Scene.prototype.getParticleSystemByID = function (id) {
  21259. for (var index = 0; index < this.particleSystems.length; index++) {
  21260. if (this.particleSystems[index].id === id) {
  21261. return this.particleSystems[index];
  21262. }
  21263. }
  21264. return null;
  21265. };
  21266. /**
  21267. * get a geometry using its ID
  21268. * @param {string} the geometry's id
  21269. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  21270. */
  21271. Scene.prototype.getGeometryByID = function (id) {
  21272. for (var index = 0; index < this._geometries.length; index++) {
  21273. if (this._geometries[index].id === id) {
  21274. return this._geometries[index];
  21275. }
  21276. }
  21277. return null;
  21278. };
  21279. /**
  21280. * add a new geometry to this scene.
  21281. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  21282. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  21283. * @return {boolean} was the geometry added or not
  21284. */
  21285. Scene.prototype.pushGeometry = function (geometry, force) {
  21286. if (!force && this.getGeometryByID(geometry.id)) {
  21287. return false;
  21288. }
  21289. this._geometries.push(geometry);
  21290. //notify the collision coordinator
  21291. if (this.collisionCoordinator) {
  21292. this.collisionCoordinator.onGeometryAdded(geometry);
  21293. }
  21294. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  21295. return true;
  21296. };
  21297. /**
  21298. * Removes an existing geometry
  21299. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  21300. * @return {boolean} was the geometry removed or not
  21301. */
  21302. Scene.prototype.removeGeometry = function (geometry) {
  21303. var index = this._geometries.indexOf(geometry);
  21304. if (index > -1) {
  21305. this._geometries.splice(index, 1);
  21306. //notify the collision coordinator
  21307. if (this.collisionCoordinator) {
  21308. this.collisionCoordinator.onGeometryDeleted(geometry);
  21309. }
  21310. this.onGeometryRemovedObservable.notifyObservers(geometry);
  21311. return true;
  21312. }
  21313. return false;
  21314. };
  21315. Scene.prototype.getGeometries = function () {
  21316. return this._geometries;
  21317. };
  21318. /**
  21319. * Get the first added mesh found of a given ID
  21320. * @param {string} id - the id to search for
  21321. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21322. */
  21323. Scene.prototype.getMeshByID = function (id) {
  21324. for (var index = 0; index < this.meshes.length; index++) {
  21325. if (this.meshes[index].id === id) {
  21326. return this.meshes[index];
  21327. }
  21328. }
  21329. return null;
  21330. };
  21331. Scene.prototype.getMeshesByID = function (id) {
  21332. return this.meshes.filter(function (m) {
  21333. return m.id === id;
  21334. });
  21335. };
  21336. /**
  21337. * Get the first added transform node found of a given ID
  21338. * @param {string} id - the id to search for
  21339. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  21340. */
  21341. Scene.prototype.getTransformNodeByID = function (id) {
  21342. for (var index = 0; index < this.transformNodes.length; index++) {
  21343. if (this.transformNodes[index].id === id) {
  21344. return this.transformNodes[index];
  21345. }
  21346. }
  21347. return null;
  21348. };
  21349. Scene.prototype.getTransformNodesByID = function (id) {
  21350. return this.transformNodes.filter(function (m) {
  21351. return m.id === id;
  21352. });
  21353. };
  21354. /**
  21355. * Get a mesh with its auto-generated unique id
  21356. * @param {number} uniqueId - the unique id to search for
  21357. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21358. */
  21359. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  21360. for (var index = 0; index < this.meshes.length; index++) {
  21361. if (this.meshes[index].uniqueId === uniqueId) {
  21362. return this.meshes[index];
  21363. }
  21364. }
  21365. return null;
  21366. };
  21367. /**
  21368. * Get a the last added mesh found of a given ID
  21369. * @param {string} id - the id to search for
  21370. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21371. */
  21372. Scene.prototype.getLastMeshByID = function (id) {
  21373. for (var index = this.meshes.length - 1; index >= 0; index--) {
  21374. if (this.meshes[index].id === id) {
  21375. return this.meshes[index];
  21376. }
  21377. }
  21378. return null;
  21379. };
  21380. /**
  21381. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  21382. * @param {string} id - the id to search for
  21383. * @return {BABYLON.Node|null} the node found or null if not found at all.
  21384. */
  21385. Scene.prototype.getLastEntryByID = function (id) {
  21386. var index;
  21387. for (index = this.meshes.length - 1; index >= 0; index--) {
  21388. if (this.meshes[index].id === id) {
  21389. return this.meshes[index];
  21390. }
  21391. }
  21392. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  21393. if (this.transformNodes[index].id === id) {
  21394. return this.transformNodes[index];
  21395. }
  21396. }
  21397. for (index = this.cameras.length - 1; index >= 0; index--) {
  21398. if (this.cameras[index].id === id) {
  21399. return this.cameras[index];
  21400. }
  21401. }
  21402. for (index = this.lights.length - 1; index >= 0; index--) {
  21403. if (this.lights[index].id === id) {
  21404. return this.lights[index];
  21405. }
  21406. }
  21407. return null;
  21408. };
  21409. Scene.prototype.getNodeByID = function (id) {
  21410. var mesh = this.getMeshByID(id);
  21411. if (mesh) {
  21412. return mesh;
  21413. }
  21414. var light = this.getLightByID(id);
  21415. if (light) {
  21416. return light;
  21417. }
  21418. var camera = this.getCameraByID(id);
  21419. if (camera) {
  21420. return camera;
  21421. }
  21422. var bone = this.getBoneByID(id);
  21423. return bone;
  21424. };
  21425. Scene.prototype.getNodeByName = function (name) {
  21426. var mesh = this.getMeshByName(name);
  21427. if (mesh) {
  21428. return mesh;
  21429. }
  21430. var light = this.getLightByName(name);
  21431. if (light) {
  21432. return light;
  21433. }
  21434. var camera = this.getCameraByName(name);
  21435. if (camera) {
  21436. return camera;
  21437. }
  21438. var bone = this.getBoneByName(name);
  21439. return bone;
  21440. };
  21441. Scene.prototype.getMeshByName = function (name) {
  21442. for (var index = 0; index < this.meshes.length; index++) {
  21443. if (this.meshes[index].name === name) {
  21444. return this.meshes[index];
  21445. }
  21446. }
  21447. return null;
  21448. };
  21449. Scene.prototype.getTransformNodeByName = function (name) {
  21450. for (var index = 0; index < this.transformNodes.length; index++) {
  21451. if (this.transformNodes[index].name === name) {
  21452. return this.transformNodes[index];
  21453. }
  21454. }
  21455. return null;
  21456. };
  21457. Scene.prototype.getSoundByName = function (name) {
  21458. var index;
  21459. if (BABYLON.AudioEngine) {
  21460. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  21461. if (this.mainSoundTrack.soundCollection[index].name === name) {
  21462. return this.mainSoundTrack.soundCollection[index];
  21463. }
  21464. }
  21465. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  21466. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  21467. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  21468. return this.soundTracks[sdIndex].soundCollection[index];
  21469. }
  21470. }
  21471. }
  21472. }
  21473. return null;
  21474. };
  21475. Scene.prototype.getLastSkeletonByID = function (id) {
  21476. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  21477. if (this.skeletons[index].id === id) {
  21478. return this.skeletons[index];
  21479. }
  21480. }
  21481. return null;
  21482. };
  21483. Scene.prototype.getSkeletonById = function (id) {
  21484. for (var index = 0; index < this.skeletons.length; index++) {
  21485. if (this.skeletons[index].id === id) {
  21486. return this.skeletons[index];
  21487. }
  21488. }
  21489. return null;
  21490. };
  21491. Scene.prototype.getSkeletonByName = function (name) {
  21492. for (var index = 0; index < this.skeletons.length; index++) {
  21493. if (this.skeletons[index].name === name) {
  21494. return this.skeletons[index];
  21495. }
  21496. }
  21497. return null;
  21498. };
  21499. Scene.prototype.getMorphTargetManagerById = function (id) {
  21500. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  21501. if (this.morphTargetManagers[index].uniqueId === id) {
  21502. return this.morphTargetManagers[index];
  21503. }
  21504. }
  21505. return null;
  21506. };
  21507. Scene.prototype.isActiveMesh = function (mesh) {
  21508. return (this._activeMeshes.indexOf(mesh) !== -1);
  21509. };
  21510. /**
  21511. * Return a the first highlight layer of the scene with a given name.
  21512. * @param name The name of the highlight layer to look for.
  21513. * @return The highlight layer if found otherwise null.
  21514. */
  21515. Scene.prototype.getHighlightLayerByName = function (name) {
  21516. for (var index = 0; index < this.highlightLayers.length; index++) {
  21517. if (this.highlightLayers[index].name === name) {
  21518. return this.highlightLayers[index];
  21519. }
  21520. }
  21521. return null;
  21522. };
  21523. Object.defineProperty(Scene.prototype, "uid", {
  21524. /**
  21525. * Return a unique id as a string which can serve as an identifier for the scene
  21526. */
  21527. get: function () {
  21528. if (!this._uid) {
  21529. this._uid = BABYLON.Tools.RandomId();
  21530. }
  21531. return this._uid;
  21532. },
  21533. enumerable: true,
  21534. configurable: true
  21535. });
  21536. /**
  21537. * Add an externaly attached data from its key.
  21538. * This method call will fail and return false, if such key already exists.
  21539. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  21540. * @param key the unique key that identifies the data
  21541. * @param data the data object to associate to the key for this Engine instance
  21542. * @return true if no such key were already present and the data was added successfully, false otherwise
  21543. */
  21544. Scene.prototype.addExternalData = function (key, data) {
  21545. if (!this._externalData) {
  21546. this._externalData = new BABYLON.StringDictionary();
  21547. }
  21548. return this._externalData.add(key, data);
  21549. };
  21550. /**
  21551. * Get an externaly attached data from its key
  21552. * @param key the unique key that identifies the data
  21553. * @return the associated data, if present (can be null), or undefined if not present
  21554. */
  21555. Scene.prototype.getExternalData = function (key) {
  21556. if (!this._externalData) {
  21557. return null;
  21558. }
  21559. return this._externalData.get(key);
  21560. };
  21561. /**
  21562. * Get an externaly attached data from its key, create it using a factory if it's not already present
  21563. * @param key the unique key that identifies the data
  21564. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  21565. * @return the associated data, can be null if the factory returned null.
  21566. */
  21567. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  21568. if (!this._externalData) {
  21569. this._externalData = new BABYLON.StringDictionary();
  21570. }
  21571. return this._externalData.getOrAddWithFactory(key, factory);
  21572. };
  21573. /**
  21574. * Remove an externaly attached data from the Engine instance
  21575. * @param key the unique key that identifies the data
  21576. * @return true if the data was successfully removed, false if it doesn't exist
  21577. */
  21578. Scene.prototype.removeExternalData = function (key) {
  21579. return this._externalData.remove(key);
  21580. };
  21581. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  21582. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  21583. if (mesh.showSubMeshesBoundingBox) {
  21584. var boundingInfo = subMesh.getBoundingInfo();
  21585. if (boundingInfo !== null && boundingInfo !== undefined) {
  21586. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  21587. }
  21588. }
  21589. var material = subMesh.getMaterial();
  21590. if (material !== null && material !== undefined) {
  21591. // Render targets
  21592. if (material.getRenderTargetTextures !== undefined) {
  21593. if (this._processedMaterials.indexOf(material) === -1) {
  21594. this._processedMaterials.push(material);
  21595. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  21596. }
  21597. }
  21598. // Dispatch
  21599. this._activeIndices.addCount(subMesh.indexCount, false);
  21600. this._renderingManager.dispatch(subMesh, mesh, material);
  21601. }
  21602. }
  21603. };
  21604. Scene.prototype._isInIntermediateRendering = function () {
  21605. return this._intermediateRendering;
  21606. };
  21607. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  21608. this._activeMeshCandidateProvider = provider;
  21609. };
  21610. Scene.prototype.getActiveMeshCandidateProvider = function () {
  21611. return this._activeMeshCandidateProvider;
  21612. };
  21613. /**
  21614. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  21615. */
  21616. Scene.prototype.freezeActiveMeshes = function () {
  21617. this._evaluateActiveMeshes();
  21618. this._activeMeshesFrozen = true;
  21619. return this;
  21620. };
  21621. /**
  21622. * Use this function to restart evaluating active meshes on every frame
  21623. */
  21624. Scene.prototype.unfreezeActiveMeshes = function () {
  21625. this._activeMeshesFrozen = false;
  21626. return this;
  21627. };
  21628. Scene.prototype._evaluateActiveMeshes = function () {
  21629. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  21630. return;
  21631. }
  21632. if (!this.activeCamera) {
  21633. return;
  21634. }
  21635. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  21636. this.activeCamera._activeMeshes.reset();
  21637. this._activeMeshes.reset();
  21638. this._renderingManager.reset();
  21639. this._processedMaterials.reset();
  21640. this._activeParticleSystems.reset();
  21641. this._activeSkeletons.reset();
  21642. this._softwareSkinnedMeshes.reset();
  21643. if (this._boundingBoxRenderer) {
  21644. this._boundingBoxRenderer.reset();
  21645. }
  21646. // Meshes
  21647. var meshes;
  21648. var len;
  21649. var checkIsEnabled = true;
  21650. // Determine mesh candidates
  21651. if (this._activeMeshCandidateProvider !== undefined) {
  21652. // Use _activeMeshCandidateProvider
  21653. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  21654. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  21655. if (meshes !== undefined) {
  21656. len = meshes.length;
  21657. }
  21658. else {
  21659. len = 0;
  21660. }
  21661. }
  21662. else if (this._selectionOctree !== undefined) {
  21663. // Octree
  21664. var selection = this._selectionOctree.select(this._frustumPlanes);
  21665. meshes = selection.data;
  21666. len = selection.length;
  21667. }
  21668. else {
  21669. // Full scene traversal
  21670. len = this.meshes.length;
  21671. meshes = this.meshes;
  21672. }
  21673. // Check each mesh
  21674. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  21675. mesh = meshes[meshIndex];
  21676. if (mesh.isBlocked) {
  21677. continue;
  21678. }
  21679. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  21680. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  21681. continue;
  21682. }
  21683. mesh.computeWorldMatrix();
  21684. // Intersections
  21685. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  21686. this._meshesForIntersections.pushNoDuplicate(mesh);
  21687. }
  21688. // Switch to current LOD
  21689. meshLOD = mesh.getLOD(this.activeCamera);
  21690. if (meshLOD === undefined || meshLOD === null) {
  21691. continue;
  21692. }
  21693. mesh._preActivate();
  21694. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  21695. this._activeMeshes.push(mesh);
  21696. this.activeCamera._activeMeshes.push(mesh);
  21697. mesh._activate(this._renderId);
  21698. if (meshLOD !== mesh) {
  21699. meshLOD._activate(this._renderId);
  21700. }
  21701. this._activeMesh(mesh, meshLOD);
  21702. }
  21703. }
  21704. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  21705. // Particle systems
  21706. if (this.particlesEnabled) {
  21707. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  21708. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  21709. var particleSystem = this.particleSystems[particleIndex];
  21710. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  21711. continue;
  21712. }
  21713. var emitter = particleSystem.emitter;
  21714. if (!emitter.position || emitter.isEnabled()) {
  21715. this._activeParticleSystems.push(particleSystem);
  21716. particleSystem.animate();
  21717. this._renderingManager.dispatchParticles(particleSystem);
  21718. }
  21719. }
  21720. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  21721. }
  21722. };
  21723. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  21724. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  21725. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  21726. mesh.skeleton.prepare();
  21727. }
  21728. if (!mesh.computeBonesUsingShaders) {
  21729. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  21730. }
  21731. }
  21732. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  21733. var boundingInfo = sourceMesh.getBoundingInfo();
  21734. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  21735. }
  21736. if (mesh !== undefined && mesh !== null
  21737. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  21738. // Submeshes Octrees
  21739. var len;
  21740. var subMeshes;
  21741. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  21742. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  21743. len = intersections.length;
  21744. subMeshes = intersections.data;
  21745. }
  21746. else {
  21747. subMeshes = mesh.subMeshes;
  21748. len = subMeshes.length;
  21749. }
  21750. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  21751. subMesh = subMeshes[subIndex];
  21752. this._evaluateSubMesh(subMesh, mesh);
  21753. }
  21754. }
  21755. };
  21756. Scene.prototype.updateTransformMatrix = function (force) {
  21757. if (!this.activeCamera) {
  21758. return;
  21759. }
  21760. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  21761. };
  21762. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  21763. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  21764. };
  21765. Scene.prototype._renderForCamera = function (camera) {
  21766. if (camera && camera._skipRendering) {
  21767. return;
  21768. }
  21769. var engine = this._engine;
  21770. this.activeCamera = camera;
  21771. if (!this.activeCamera)
  21772. throw new Error("Active camera not set");
  21773. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  21774. // Viewport
  21775. engine.setViewport(this.activeCamera.viewport);
  21776. // Camera
  21777. this.resetCachedMaterial();
  21778. this._renderId++;
  21779. this.activeCamera.update();
  21780. this.updateTransformMatrix();
  21781. if (camera._alternateCamera) {
  21782. this.updateAlternateTransformMatrix(camera._alternateCamera);
  21783. this._alternateRendering = true;
  21784. }
  21785. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  21786. // Meshes
  21787. this._evaluateActiveMeshes();
  21788. // Software skinning
  21789. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  21790. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  21791. mesh.applySkeleton(mesh.skeleton);
  21792. }
  21793. // Render targets
  21794. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  21795. var needsRestoreFrameBuffer = false;
  21796. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  21797. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  21798. }
  21799. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  21800. this._intermediateRendering = true;
  21801. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  21802. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  21803. var renderTarget = this._renderTargets.data[renderIndex];
  21804. if (renderTarget._shouldRender()) {
  21805. this._renderId++;
  21806. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  21807. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  21808. }
  21809. }
  21810. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  21811. this._intermediateRendering = false;
  21812. this._renderId++;
  21813. needsRestoreFrameBuffer = true; // Restore back buffer
  21814. }
  21815. // Render HighlightLayer Texture
  21816. var stencilState = this._engine.getStencilBuffer();
  21817. var renderhighlights = false;
  21818. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  21819. this._intermediateRendering = true;
  21820. for (var i = 0; i < this.highlightLayers.length; i++) {
  21821. var highlightLayer = this.highlightLayers[i];
  21822. if (highlightLayer.shouldRender() &&
  21823. (!highlightLayer.camera ||
  21824. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  21825. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  21826. renderhighlights = true;
  21827. var renderTarget = highlightLayer._mainTexture;
  21828. if (renderTarget._shouldRender()) {
  21829. this._renderId++;
  21830. renderTarget.render(false, false);
  21831. needsRestoreFrameBuffer = true;
  21832. }
  21833. }
  21834. }
  21835. this._intermediateRendering = false;
  21836. this._renderId++;
  21837. }
  21838. if (needsRestoreFrameBuffer) {
  21839. engine.restoreDefaultFramebuffer(); // Restore back buffer
  21840. }
  21841. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  21842. // Prepare Frame
  21843. this.postProcessManager._prepareFrame();
  21844. // Backgrounds
  21845. var layerIndex;
  21846. var layer;
  21847. if (this.layers.length) {
  21848. engine.setDepthBuffer(false);
  21849. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  21850. layer = this.layers[layerIndex];
  21851. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  21852. layer.render();
  21853. }
  21854. }
  21855. engine.setDepthBuffer(true);
  21856. }
  21857. // Activate HighlightLayer stencil
  21858. if (renderhighlights) {
  21859. this._engine.setStencilBuffer(true);
  21860. }
  21861. // Render
  21862. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  21863. this._renderingManager.render(null, null, true, true);
  21864. this.onAfterDrawPhaseObservable.notifyObservers(this);
  21865. // Restore HighlightLayer stencil
  21866. if (renderhighlights) {
  21867. this._engine.setStencilBuffer(stencilState);
  21868. }
  21869. // Bounding boxes
  21870. if (this._boundingBoxRenderer) {
  21871. this._boundingBoxRenderer.render();
  21872. }
  21873. // Lens flares
  21874. if (this.lensFlaresEnabled) {
  21875. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  21876. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  21877. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  21878. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  21879. lensFlareSystem.render();
  21880. }
  21881. }
  21882. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  21883. }
  21884. // Foregrounds
  21885. if (this.layers.length) {
  21886. engine.setDepthBuffer(false);
  21887. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  21888. layer = this.layers[layerIndex];
  21889. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  21890. layer.render();
  21891. }
  21892. }
  21893. engine.setDepthBuffer(true);
  21894. }
  21895. // Highlight Layer
  21896. if (renderhighlights) {
  21897. engine.setDepthBuffer(false);
  21898. for (var i = 0; i < this.highlightLayers.length; i++) {
  21899. if (this.highlightLayers[i].shouldRender()) {
  21900. this.highlightLayers[i].render();
  21901. }
  21902. }
  21903. engine.setDepthBuffer(true);
  21904. }
  21905. // Finalize frame
  21906. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  21907. // Reset some special arrays
  21908. this._renderTargets.reset();
  21909. this._alternateRendering = false;
  21910. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  21911. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  21912. };
  21913. Scene.prototype._processSubCameras = function (camera) {
  21914. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  21915. this._renderForCamera(camera);
  21916. return;
  21917. }
  21918. // Update camera
  21919. if (this.activeCamera) {
  21920. this.activeCamera.update();
  21921. }
  21922. // rig cameras
  21923. for (var index = 0; index < camera._rigCameras.length; index++) {
  21924. this._renderForCamera(camera._rigCameras[index]);
  21925. }
  21926. this.activeCamera = camera;
  21927. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  21928. };
  21929. Scene.prototype._checkIntersections = function () {
  21930. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  21931. var sourceMesh = this._meshesForIntersections.data[index];
  21932. if (!sourceMesh.actionManager) {
  21933. continue;
  21934. }
  21935. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  21936. var action = sourceMesh.actionManager.actions[actionIndex];
  21937. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21938. var parameters = action.getTriggerParameter();
  21939. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  21940. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  21941. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  21942. if (areIntersecting && currentIntersectionInProgress === -1) {
  21943. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  21944. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  21945. sourceMesh._intersectionsInProgress.push(otherMesh);
  21946. }
  21947. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21948. sourceMesh._intersectionsInProgress.push(otherMesh);
  21949. }
  21950. }
  21951. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  21952. //They intersected, and now they don't.
  21953. //is this trigger an exit trigger? execute an event.
  21954. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21955. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  21956. }
  21957. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  21958. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21959. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  21960. }
  21961. }
  21962. }
  21963. }
  21964. }
  21965. };
  21966. Scene.prototype.render = function () {
  21967. if (this.isDisposed) {
  21968. return;
  21969. }
  21970. this._activeParticles.fetchNewFrame();
  21971. this._totalVertices.fetchNewFrame();
  21972. this._activeIndices.fetchNewFrame();
  21973. this._activeBones.fetchNewFrame();
  21974. this._meshesForIntersections.reset();
  21975. this.resetCachedMaterial();
  21976. this.onBeforeAnimationsObservable.notifyObservers(this);
  21977. // Actions
  21978. if (this.actionManager) {
  21979. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  21980. }
  21981. //Simplification Queue
  21982. if (this.simplificationQueue && !this.simplificationQueue.running) {
  21983. this.simplificationQueue.executeNext();
  21984. }
  21985. if (this._engine.isDeterministicLockStep()) {
  21986. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  21987. var defaultFPS = (60.0 / 1000.0);
  21988. var defaultFrameTime = 1000 / 60; // frame time in MS
  21989. if (this._physicsEngine) {
  21990. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  21991. }
  21992. var stepsTaken = 0;
  21993. var maxSubSteps = this._engine.getLockstepMaxSteps();
  21994. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  21995. internalSteps = Math.min(internalSteps, maxSubSteps);
  21996. do {
  21997. this.onBeforeStepObservable.notifyObservers(this);
  21998. // Animations
  21999. this._animationRatio = defaultFrameTime * defaultFPS;
  22000. this._animate();
  22001. this.onAfterAnimationsObservable.notifyObservers(this);
  22002. // Physics
  22003. if (this._physicsEngine) {
  22004. this.onBeforePhysicsObservable.notifyObservers(this);
  22005. this._physicsEngine._step(defaultFrameTime / 1000);
  22006. this.onAfterPhysicsObservable.notifyObservers(this);
  22007. }
  22008. this.onAfterStepObservable.notifyObservers(this);
  22009. this._currentStepId++;
  22010. stepsTaken++;
  22011. deltaTime -= defaultFrameTime;
  22012. } while (deltaTime > 0 && stepsTaken < internalSteps);
  22013. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  22014. }
  22015. else {
  22016. // Animations
  22017. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  22018. this._animationRatio = deltaTime * (60.0 / 1000.0);
  22019. this._animate();
  22020. this.onAfterAnimationsObservable.notifyObservers(this);
  22021. // Physics
  22022. if (this._physicsEngine) {
  22023. this.onBeforePhysicsObservable.notifyObservers(this);
  22024. this._physicsEngine._step(deltaTime / 1000.0);
  22025. this.onAfterPhysicsObservable.notifyObservers(this);
  22026. }
  22027. }
  22028. // update gamepad manager
  22029. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  22030. this._gamepadManager._checkGamepadsStatus();
  22031. }
  22032. // Before render
  22033. this.onBeforeRenderObservable.notifyObservers(this);
  22034. // Customs render targets
  22035. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22036. var engine = this.getEngine();
  22037. var currentActiveCamera = this.activeCamera;
  22038. if (this.renderTargetsEnabled) {
  22039. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22040. this._intermediateRendering = true;
  22041. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  22042. var renderTarget = this.customRenderTargets[customIndex];
  22043. if (renderTarget._shouldRender()) {
  22044. this._renderId++;
  22045. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  22046. if (!this.activeCamera)
  22047. throw new Error("Active camera not set");
  22048. // Viewport
  22049. engine.setViewport(this.activeCamera.viewport);
  22050. // Camera
  22051. this.updateTransformMatrix();
  22052. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  22053. }
  22054. }
  22055. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22056. this._intermediateRendering = false;
  22057. this._renderId++;
  22058. }
  22059. // Restore back buffer
  22060. if (this.customRenderTargets.length > 0) {
  22061. engine.restoreDefaultFramebuffer();
  22062. }
  22063. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22064. this.activeCamera = currentActiveCamera;
  22065. // Procedural textures
  22066. if (this.proceduralTexturesEnabled) {
  22067. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22068. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  22069. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  22070. if (proceduralTexture._shouldRender()) {
  22071. proceduralTexture.render();
  22072. }
  22073. }
  22074. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22075. }
  22076. // Clear
  22077. if (this.autoClearDepthAndStencil || this.autoClear) {
  22078. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  22079. }
  22080. // Shadows
  22081. if (this.shadowsEnabled) {
  22082. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  22083. var light = this.lights[lightIndex];
  22084. var shadowGenerator = light.getShadowGenerator();
  22085. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  22086. var shadowMap = (shadowGenerator.getShadowMap());
  22087. if (this.textures.indexOf(shadowMap) !== -1) {
  22088. this._renderTargets.push(shadowMap);
  22089. }
  22090. }
  22091. }
  22092. }
  22093. // Depth renderer
  22094. if (this._depthRenderer) {
  22095. this._renderTargets.push(this._depthRenderer.getDepthMap());
  22096. }
  22097. // Geometry renderer
  22098. if (this._geometryBufferRenderer) {
  22099. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  22100. }
  22101. // RenderPipeline
  22102. if (this._postProcessRenderPipelineManager) {
  22103. this._postProcessRenderPipelineManager.update();
  22104. }
  22105. // Multi-cameras?
  22106. if (this.activeCameras.length > 0) {
  22107. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  22108. if (cameraIndex > 0) {
  22109. this._engine.clear(null, false, true, true);
  22110. }
  22111. this._processSubCameras(this.activeCameras[cameraIndex]);
  22112. }
  22113. }
  22114. else {
  22115. if (!this.activeCamera) {
  22116. throw new Error("No camera defined");
  22117. }
  22118. this._processSubCameras(this.activeCamera);
  22119. }
  22120. // Intersection checks
  22121. this._checkIntersections();
  22122. // Update the audio listener attached to the camera
  22123. if (BABYLON.AudioEngine) {
  22124. this._updateAudioParameters();
  22125. }
  22126. // After render
  22127. if (this.afterRender) {
  22128. this.afterRender();
  22129. }
  22130. this.onAfterRenderObservable.notifyObservers(this);
  22131. // Cleaning
  22132. for (var index = 0; index < this._toBeDisposed.length; index++) {
  22133. var data = this._toBeDisposed.data[index];
  22134. if (data) {
  22135. data.dispose();
  22136. }
  22137. this._toBeDisposed[index] = null;
  22138. }
  22139. this._toBeDisposed.reset();
  22140. if (this.dumpNextRenderTargets) {
  22141. this.dumpNextRenderTargets = false;
  22142. }
  22143. this._activeBones.addCount(0, true);
  22144. this._activeIndices.addCount(0, true);
  22145. this._activeParticles.addCount(0, true);
  22146. };
  22147. Scene.prototype._updateAudioParameters = function () {
  22148. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  22149. return;
  22150. }
  22151. var listeningCamera;
  22152. var audioEngine = BABYLON.Engine.audioEngine;
  22153. if (this.activeCameras.length > 0) {
  22154. listeningCamera = this.activeCameras[0];
  22155. }
  22156. else {
  22157. listeningCamera = this.activeCamera;
  22158. }
  22159. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  22160. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  22161. // for VR cameras
  22162. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  22163. listeningCamera = listeningCamera.rigCameras[0];
  22164. }
  22165. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  22166. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  22167. cameraDirection.normalize();
  22168. // To avoid some errors on GearVR
  22169. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  22170. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  22171. }
  22172. var i;
  22173. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22174. var sound = this.mainSoundTrack.soundCollection[i];
  22175. if (sound.useCustomAttenuation) {
  22176. sound.updateDistanceFromListener();
  22177. }
  22178. }
  22179. for (i = 0; i < this.soundTracks.length; i++) {
  22180. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22181. sound = this.soundTracks[i].soundCollection[j];
  22182. if (sound.useCustomAttenuation) {
  22183. sound.updateDistanceFromListener();
  22184. }
  22185. }
  22186. }
  22187. }
  22188. };
  22189. Object.defineProperty(Scene.prototype, "audioEnabled", {
  22190. // Audio
  22191. get: function () {
  22192. return this._audioEnabled;
  22193. },
  22194. set: function (value) {
  22195. this._audioEnabled = value;
  22196. if (BABYLON.AudioEngine) {
  22197. if (this._audioEnabled) {
  22198. this._enableAudio();
  22199. }
  22200. else {
  22201. this._disableAudio();
  22202. }
  22203. }
  22204. },
  22205. enumerable: true,
  22206. configurable: true
  22207. });
  22208. Scene.prototype._disableAudio = function () {
  22209. var i;
  22210. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22211. this.mainSoundTrack.soundCollection[i].pause();
  22212. }
  22213. for (i = 0; i < this.soundTracks.length; i++) {
  22214. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22215. this.soundTracks[i].soundCollection[j].pause();
  22216. }
  22217. }
  22218. };
  22219. Scene.prototype._enableAudio = function () {
  22220. var i;
  22221. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22222. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  22223. this.mainSoundTrack.soundCollection[i].play();
  22224. }
  22225. }
  22226. for (i = 0; i < this.soundTracks.length; i++) {
  22227. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22228. if (this.soundTracks[i].soundCollection[j].isPaused) {
  22229. this.soundTracks[i].soundCollection[j].play();
  22230. }
  22231. }
  22232. }
  22233. };
  22234. Object.defineProperty(Scene.prototype, "headphone", {
  22235. get: function () {
  22236. return this._headphone;
  22237. },
  22238. set: function (value) {
  22239. this._headphone = value;
  22240. if (BABYLON.AudioEngine) {
  22241. if (this._headphone) {
  22242. this._switchAudioModeForHeadphones();
  22243. }
  22244. else {
  22245. this._switchAudioModeForNormalSpeakers();
  22246. }
  22247. }
  22248. },
  22249. enumerable: true,
  22250. configurable: true
  22251. });
  22252. Scene.prototype._switchAudioModeForHeadphones = function () {
  22253. this.mainSoundTrack.switchPanningModelToHRTF();
  22254. for (var i = 0; i < this.soundTracks.length; i++) {
  22255. this.soundTracks[i].switchPanningModelToHRTF();
  22256. }
  22257. };
  22258. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  22259. this.mainSoundTrack.switchPanningModelToEqualPower();
  22260. for (var i = 0; i < this.soundTracks.length; i++) {
  22261. this.soundTracks[i].switchPanningModelToEqualPower();
  22262. }
  22263. };
  22264. Scene.prototype.enableDepthRenderer = function () {
  22265. if (this._depthRenderer) {
  22266. return this._depthRenderer;
  22267. }
  22268. this._depthRenderer = new BABYLON.DepthRenderer(this);
  22269. return this._depthRenderer;
  22270. };
  22271. Scene.prototype.disableDepthRenderer = function () {
  22272. if (!this._depthRenderer) {
  22273. return;
  22274. }
  22275. this._depthRenderer.dispose();
  22276. this._depthRenderer = null;
  22277. };
  22278. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  22279. if (ratio === void 0) { ratio = 1; }
  22280. if (this._geometryBufferRenderer) {
  22281. return this._geometryBufferRenderer;
  22282. }
  22283. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  22284. if (!this._geometryBufferRenderer.isSupported) {
  22285. this._geometryBufferRenderer = null;
  22286. }
  22287. return this._geometryBufferRenderer;
  22288. };
  22289. Scene.prototype.disableGeometryBufferRenderer = function () {
  22290. if (!this._geometryBufferRenderer) {
  22291. return;
  22292. }
  22293. this._geometryBufferRenderer.dispose();
  22294. this._geometryBufferRenderer = null;
  22295. };
  22296. Scene.prototype.freezeMaterials = function () {
  22297. for (var i = 0; i < this.materials.length; i++) {
  22298. this.materials[i].freeze();
  22299. }
  22300. };
  22301. Scene.prototype.unfreezeMaterials = function () {
  22302. for (var i = 0; i < this.materials.length; i++) {
  22303. this.materials[i].unfreeze();
  22304. }
  22305. };
  22306. Scene.prototype.dispose = function () {
  22307. this.beforeRender = null;
  22308. this.afterRender = null;
  22309. this.skeletons = [];
  22310. this.morphTargetManagers = [];
  22311. this.importedMeshesFiles = new Array();
  22312. this.stopAllAnimations();
  22313. this.resetCachedMaterial();
  22314. if (this._depthRenderer) {
  22315. this._depthRenderer.dispose();
  22316. }
  22317. if (this._gamepadManager) {
  22318. this._gamepadManager.dispose();
  22319. this._gamepadManager = null;
  22320. }
  22321. // Smart arrays
  22322. if (this.activeCamera) {
  22323. this.activeCamera._activeMeshes.dispose();
  22324. this.activeCamera = null;
  22325. }
  22326. this._activeMeshes.dispose();
  22327. this._renderingManager.dispose();
  22328. this._processedMaterials.dispose();
  22329. this._activeParticleSystems.dispose();
  22330. this._activeSkeletons.dispose();
  22331. this._softwareSkinnedMeshes.dispose();
  22332. this._renderTargets.dispose();
  22333. if (this._boundingBoxRenderer) {
  22334. this._boundingBoxRenderer.dispose();
  22335. }
  22336. this._meshesForIntersections.dispose();
  22337. this._toBeDisposed.dispose();
  22338. // Abort active requests
  22339. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  22340. var request = _a[_i];
  22341. request.abort();
  22342. }
  22343. // Debug layer
  22344. if (this._debugLayer) {
  22345. this._debugLayer.hide();
  22346. }
  22347. // Events
  22348. this.onDisposeObservable.notifyObservers(this);
  22349. this.onDisposeObservable.clear();
  22350. this.onBeforeRenderObservable.clear();
  22351. this.onAfterRenderObservable.clear();
  22352. this.OnBeforeRenderTargetsRenderObservable.clear();
  22353. this.OnAfterRenderTargetsRenderObservable.clear();
  22354. this.onAfterStepObservable.clear();
  22355. this.onBeforeStepObservable.clear();
  22356. this.onBeforeActiveMeshesEvaluationObservable.clear();
  22357. this.onAfterActiveMeshesEvaluationObservable.clear();
  22358. this.onBeforeParticlesRenderingObservable.clear();
  22359. this.onAfterParticlesRenderingObservable.clear();
  22360. this.onBeforeSpritesRenderingObservable.clear();
  22361. this.onAfterSpritesRenderingObservable.clear();
  22362. this.onBeforeDrawPhaseObservable.clear();
  22363. this.onAfterDrawPhaseObservable.clear();
  22364. this.onBeforePhysicsObservable.clear();
  22365. this.onAfterPhysicsObservable.clear();
  22366. this.onBeforeAnimationsObservable.clear();
  22367. this.onAfterAnimationsObservable.clear();
  22368. this.onDataLoadedObservable.clear();
  22369. this.detachControl();
  22370. // Release sounds & sounds tracks
  22371. if (BABYLON.AudioEngine) {
  22372. this.disposeSounds();
  22373. }
  22374. // VR Helper
  22375. if (this.VRHelper) {
  22376. this.VRHelper.dispose();
  22377. }
  22378. // Detach cameras
  22379. var canvas = this._engine.getRenderingCanvas();
  22380. if (canvas) {
  22381. var index;
  22382. for (index = 0; index < this.cameras.length; index++) {
  22383. this.cameras[index].detachControl(canvas);
  22384. }
  22385. }
  22386. // Release animation groups
  22387. while (this.animationGroups.length) {
  22388. this.animationGroups[0].dispose();
  22389. }
  22390. // Release lights
  22391. while (this.lights.length) {
  22392. this.lights[0].dispose();
  22393. }
  22394. // Release meshes
  22395. while (this.meshes.length) {
  22396. this.meshes[0].dispose(true);
  22397. }
  22398. while (this.transformNodes.length) {
  22399. this.removeTransformNode(this.transformNodes[0]);
  22400. }
  22401. // Release cameras
  22402. while (this.cameras.length) {
  22403. this.cameras[0].dispose();
  22404. }
  22405. // Release materials
  22406. if (this.defaultMaterial) {
  22407. this.defaultMaterial.dispose();
  22408. }
  22409. while (this.multiMaterials.length) {
  22410. this.multiMaterials[0].dispose();
  22411. }
  22412. while (this.materials.length) {
  22413. this.materials[0].dispose();
  22414. }
  22415. // Release particles
  22416. while (this.particleSystems.length) {
  22417. this.particleSystems[0].dispose();
  22418. }
  22419. // Release sprites
  22420. while (this.spriteManagers.length) {
  22421. this.spriteManagers[0].dispose();
  22422. }
  22423. // Release postProcesses
  22424. while (this.postProcesses.length) {
  22425. this.postProcesses[0].dispose();
  22426. }
  22427. // Release layers
  22428. while (this.layers.length) {
  22429. this.layers[0].dispose();
  22430. }
  22431. while (this.highlightLayers.length) {
  22432. this.highlightLayers[0].dispose();
  22433. }
  22434. // Release textures
  22435. while (this.textures.length) {
  22436. this.textures[0].dispose();
  22437. }
  22438. // Release UBO
  22439. this._sceneUbo.dispose();
  22440. if (this._alternateSceneUbo) {
  22441. this._alternateSceneUbo.dispose();
  22442. }
  22443. // Post-processes
  22444. this.postProcessManager.dispose();
  22445. if (this._postProcessRenderPipelineManager) {
  22446. this._postProcessRenderPipelineManager.dispose();
  22447. }
  22448. // Physics
  22449. if (this._physicsEngine) {
  22450. this.disablePhysicsEngine();
  22451. }
  22452. // Remove from engine
  22453. index = this._engine.scenes.indexOf(this);
  22454. if (index > -1) {
  22455. this._engine.scenes.splice(index, 1);
  22456. }
  22457. this._engine.wipeCaches(true);
  22458. this._isDisposed = true;
  22459. };
  22460. Object.defineProperty(Scene.prototype, "isDisposed", {
  22461. get: function () {
  22462. return this._isDisposed;
  22463. },
  22464. enumerable: true,
  22465. configurable: true
  22466. });
  22467. // Release sounds & sounds tracks
  22468. Scene.prototype.disposeSounds = function () {
  22469. if (!this._mainSoundTrack) {
  22470. return;
  22471. }
  22472. this.mainSoundTrack.dispose();
  22473. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  22474. this.soundTracks[scIndex].dispose();
  22475. }
  22476. };
  22477. // Octrees
  22478. Scene.prototype.getWorldExtends = function () {
  22479. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22480. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  22481. for (var index = 0; index < this.meshes.length; index++) {
  22482. var mesh = this.meshes[index];
  22483. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  22484. continue;
  22485. }
  22486. mesh.computeWorldMatrix(true);
  22487. var boundingInfo = mesh.getBoundingInfo();
  22488. var minBox = boundingInfo.boundingBox.minimumWorld;
  22489. var maxBox = boundingInfo.boundingBox.maximumWorld;
  22490. BABYLON.Tools.CheckExtends(minBox, min, max);
  22491. BABYLON.Tools.CheckExtends(maxBox, min, max);
  22492. }
  22493. return {
  22494. min: min,
  22495. max: max
  22496. };
  22497. };
  22498. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  22499. if (maxCapacity === void 0) { maxCapacity = 64; }
  22500. if (maxDepth === void 0) { maxDepth = 2; }
  22501. if (!this._selectionOctree) {
  22502. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  22503. }
  22504. var worldExtends = this.getWorldExtends();
  22505. // Update octree
  22506. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  22507. return this._selectionOctree;
  22508. };
  22509. // Picking
  22510. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  22511. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  22512. var result = BABYLON.Ray.Zero();
  22513. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  22514. return result;
  22515. };
  22516. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  22517. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  22518. var engine = this._engine;
  22519. if (!camera) {
  22520. if (!this.activeCamera)
  22521. throw new Error("Active camera not set");
  22522. camera = this.activeCamera;
  22523. }
  22524. var cameraViewport = camera.viewport;
  22525. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22526. // Moving coordinates to local viewport world
  22527. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22528. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22529. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  22530. return this;
  22531. };
  22532. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  22533. var result = BABYLON.Ray.Zero();
  22534. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  22535. return result;
  22536. };
  22537. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  22538. if (!BABYLON.PickingInfo) {
  22539. return this;
  22540. }
  22541. var engine = this._engine;
  22542. if (!camera) {
  22543. if (!this.activeCamera)
  22544. throw new Error("Active camera not set");
  22545. camera = this.activeCamera;
  22546. }
  22547. var cameraViewport = camera.viewport;
  22548. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22549. var identity = BABYLON.Matrix.Identity();
  22550. // Moving coordinates to local viewport world
  22551. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22552. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22553. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  22554. return this;
  22555. };
  22556. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  22557. if (!BABYLON.PickingInfo) {
  22558. return null;
  22559. }
  22560. var pickingInfo = null;
  22561. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22562. var mesh = this.meshes[meshIndex];
  22563. if (predicate) {
  22564. if (!predicate(mesh)) {
  22565. continue;
  22566. }
  22567. }
  22568. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22569. continue;
  22570. }
  22571. var world = mesh.getWorldMatrix();
  22572. var ray = rayFunction(world);
  22573. var result = mesh.intersects(ray, fastCheck);
  22574. if (!result || !result.hit)
  22575. continue;
  22576. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22577. continue;
  22578. pickingInfo = result;
  22579. if (fastCheck) {
  22580. break;
  22581. }
  22582. }
  22583. return pickingInfo || new BABYLON.PickingInfo();
  22584. };
  22585. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  22586. if (!BABYLON.PickingInfo) {
  22587. return null;
  22588. }
  22589. var pickingInfos = new Array();
  22590. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22591. var mesh = this.meshes[meshIndex];
  22592. if (predicate) {
  22593. if (!predicate(mesh)) {
  22594. continue;
  22595. }
  22596. }
  22597. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22598. continue;
  22599. }
  22600. var world = mesh.getWorldMatrix();
  22601. var ray = rayFunction(world);
  22602. var result = mesh.intersects(ray, false);
  22603. if (!result || !result.hit)
  22604. continue;
  22605. pickingInfos.push(result);
  22606. }
  22607. return pickingInfos;
  22608. };
  22609. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  22610. if (!BABYLON.PickingInfo) {
  22611. return null;
  22612. }
  22613. var pickingInfo = null;
  22614. if (!camera) {
  22615. if (!this.activeCamera) {
  22616. return null;
  22617. }
  22618. camera = this.activeCamera;
  22619. }
  22620. if (this.spriteManagers.length > 0) {
  22621. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  22622. var spriteManager = this.spriteManagers[spriteIndex];
  22623. if (!spriteManager.isPickable) {
  22624. continue;
  22625. }
  22626. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  22627. if (!result || !result.hit)
  22628. continue;
  22629. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22630. continue;
  22631. pickingInfo = result;
  22632. if (fastCheck) {
  22633. break;
  22634. }
  22635. }
  22636. }
  22637. return pickingInfo || new BABYLON.PickingInfo();
  22638. };
  22639. /** Launch a ray to try to pick a mesh in the scene
  22640. * @param x position on screen
  22641. * @param y position on screen
  22642. * @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
  22643. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22644. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22645. */
  22646. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  22647. var _this = this;
  22648. if (!BABYLON.PickingInfo) {
  22649. return null;
  22650. }
  22651. return this._internalPick(function (world) {
  22652. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  22653. return _this._tempPickingRay;
  22654. }, predicate, fastCheck);
  22655. };
  22656. /** Launch a ray to try to pick a sprite in the scene
  22657. * @param x position on screen
  22658. * @param y position on screen
  22659. * @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
  22660. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22661. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22662. */
  22663. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  22664. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  22665. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  22666. };
  22667. /** Use the given ray to pick a mesh in the scene
  22668. * @param ray The ray to use to pick meshes
  22669. * @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
  22670. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22671. */
  22672. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  22673. var _this = this;
  22674. return this._internalPick(function (world) {
  22675. if (!_this._pickWithRayInverseMatrix) {
  22676. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22677. }
  22678. world.invertToRef(_this._pickWithRayInverseMatrix);
  22679. if (!_this._cachedRayForTransform) {
  22680. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  22681. }
  22682. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  22683. return _this._cachedRayForTransform;
  22684. }, predicate, fastCheck);
  22685. };
  22686. /**
  22687. * Launch a ray to try to pick a mesh in the scene
  22688. * @param x X position on screen
  22689. * @param y Y position on screen
  22690. * @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
  22691. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22692. */
  22693. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  22694. var _this = this;
  22695. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  22696. };
  22697. /**
  22698. * Launch a ray to try to pick a mesh in the scene
  22699. * @param ray Ray to use
  22700. * @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
  22701. */
  22702. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  22703. var _this = this;
  22704. return this._internalMultiPick(function (world) {
  22705. if (!_this._pickWithRayInverseMatrix) {
  22706. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22707. }
  22708. world.invertToRef(_this._pickWithRayInverseMatrix);
  22709. if (!_this._cachedRayForTransform) {
  22710. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  22711. }
  22712. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  22713. return _this._cachedRayForTransform;
  22714. }, predicate);
  22715. };
  22716. Scene.prototype.setPointerOverMesh = function (mesh) {
  22717. if (this._pointerOverMesh === mesh) {
  22718. return;
  22719. }
  22720. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22721. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22722. }
  22723. this._pointerOverMesh = mesh;
  22724. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22725. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22726. }
  22727. };
  22728. Scene.prototype.getPointerOverMesh = function () {
  22729. return this._pointerOverMesh;
  22730. };
  22731. Scene.prototype.setPointerOverSprite = function (sprite) {
  22732. if (this._pointerOverSprite === sprite) {
  22733. return;
  22734. }
  22735. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22736. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22737. }
  22738. this._pointerOverSprite = sprite;
  22739. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22740. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22741. }
  22742. };
  22743. Scene.prototype.getPointerOverSprite = function () {
  22744. return this._pointerOverSprite;
  22745. };
  22746. // Physics
  22747. Scene.prototype.getPhysicsEngine = function () {
  22748. return this._physicsEngine;
  22749. };
  22750. /**
  22751. * Enables physics to the current scene
  22752. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  22753. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  22754. * @return {boolean} was the physics engine initialized
  22755. */
  22756. Scene.prototype.enablePhysics = function (gravity, plugin) {
  22757. if (gravity === void 0) { gravity = null; }
  22758. if (this._physicsEngine) {
  22759. return true;
  22760. }
  22761. try {
  22762. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  22763. return true;
  22764. }
  22765. catch (e) {
  22766. BABYLON.Tools.Error(e.message);
  22767. return false;
  22768. }
  22769. };
  22770. Scene.prototype.disablePhysicsEngine = function () {
  22771. if (!this._physicsEngine) {
  22772. return;
  22773. }
  22774. this._physicsEngine.dispose();
  22775. this._physicsEngine = null;
  22776. };
  22777. Scene.prototype.isPhysicsEnabled = function () {
  22778. return this._physicsEngine !== undefined;
  22779. };
  22780. Scene.prototype.deleteCompoundImpostor = function (compound) {
  22781. var mesh = compound.parts[0].mesh;
  22782. if (mesh.physicsImpostor) {
  22783. mesh.physicsImpostor.dispose();
  22784. mesh.physicsImpostor = null;
  22785. }
  22786. };
  22787. // Misc.
  22788. Scene.prototype._rebuildGeometries = function () {
  22789. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  22790. var geometry = _a[_i];
  22791. geometry._rebuild();
  22792. }
  22793. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  22794. var mesh = _c[_b];
  22795. mesh._rebuild();
  22796. }
  22797. if (this.postProcessManager) {
  22798. this.postProcessManager._rebuild();
  22799. }
  22800. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  22801. var layer = _e[_d];
  22802. layer._rebuild();
  22803. }
  22804. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  22805. var highlightLayer = _g[_f];
  22806. highlightLayer._rebuild();
  22807. }
  22808. if (this._boundingBoxRenderer) {
  22809. this._boundingBoxRenderer._rebuild();
  22810. }
  22811. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  22812. var system = _j[_h];
  22813. system.rebuild();
  22814. }
  22815. if (this._postProcessRenderPipelineManager) {
  22816. this._postProcessRenderPipelineManager._rebuild();
  22817. }
  22818. };
  22819. Scene.prototype._rebuildTextures = function () {
  22820. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  22821. var texture = _a[_i];
  22822. texture._rebuild();
  22823. }
  22824. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22825. };
  22826. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  22827. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  22828. if (replace === void 0) { replace = false; }
  22829. if (attachCameraControls === void 0) { attachCameraControls = false; }
  22830. // Dispose existing camera or light in replace mode.
  22831. if (replace) {
  22832. if (this.activeCamera) {
  22833. this.activeCamera.dispose();
  22834. this.activeCamera = null;
  22835. }
  22836. if (this.lights) {
  22837. for (var i = 0; i < this.lights.length; i++) {
  22838. this.lights[i].dispose();
  22839. }
  22840. }
  22841. }
  22842. // Light
  22843. if (this.lights.length === 0) {
  22844. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  22845. }
  22846. // Camera
  22847. if (!this.activeCamera) {
  22848. var worldExtends = this.getWorldExtends();
  22849. var worldSize = worldExtends.max.subtract(worldExtends.min);
  22850. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  22851. var camera;
  22852. var radius = worldSize.length() * 1.5;
  22853. if (createArcRotateCamera) {
  22854. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  22855. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  22856. arcRotateCamera.wheelPrecision = 100 / radius;
  22857. camera = arcRotateCamera;
  22858. }
  22859. else {
  22860. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  22861. freeCamera.setTarget(worldCenter);
  22862. camera = freeCamera;
  22863. }
  22864. camera.minZ = radius * 0.01;
  22865. camera.maxZ = radius * 1000;
  22866. camera.speed = radius * 0.2;
  22867. this.activeCamera = camera;
  22868. var canvas = this.getEngine().getRenderingCanvas();
  22869. if (attachCameraControls && canvas) {
  22870. camera.attachControl(canvas);
  22871. }
  22872. }
  22873. };
  22874. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  22875. if (pbr === void 0) { pbr = false; }
  22876. if (scale === void 0) { scale = 1000; }
  22877. if (blur === void 0) { blur = 0; }
  22878. if (environmentTexture) {
  22879. this.environmentTexture = environmentTexture;
  22880. }
  22881. if (!this.environmentTexture) {
  22882. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  22883. return null;
  22884. }
  22885. // Skybox
  22886. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  22887. if (pbr) {
  22888. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  22889. hdrSkyboxMaterial.backFaceCulling = false;
  22890. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  22891. if (hdrSkyboxMaterial.reflectionTexture) {
  22892. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  22893. }
  22894. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  22895. hdrSkyboxMaterial.disableLighting = true;
  22896. hdrSkyboxMaterial.twoSidedLighting = true;
  22897. hdrSkybox.infiniteDistance = true;
  22898. hdrSkybox.material = hdrSkyboxMaterial;
  22899. }
  22900. else {
  22901. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  22902. skyboxMaterial.backFaceCulling = false;
  22903. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  22904. if (skyboxMaterial.reflectionTexture) {
  22905. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  22906. }
  22907. skyboxMaterial.disableLighting = true;
  22908. hdrSkybox.infiniteDistance = true;
  22909. hdrSkybox.material = skyboxMaterial;
  22910. }
  22911. return hdrSkybox;
  22912. };
  22913. Scene.prototype.createDefaultEnvironment = function (options) {
  22914. if (BABYLON.EnvironmentHelper) {
  22915. return new BABYLON.EnvironmentHelper(options, this);
  22916. }
  22917. return null;
  22918. };
  22919. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  22920. if (webVROptions === void 0) { webVROptions = {}; }
  22921. return new BABYLON.VRExperienceHelper(this, webVROptions);
  22922. };
  22923. // Tags
  22924. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  22925. if (tagsQuery === undefined) {
  22926. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  22927. return list;
  22928. }
  22929. var listByTags = [];
  22930. forEach = forEach || (function (item) { return; });
  22931. for (var i in list) {
  22932. var item = list[i];
  22933. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  22934. listByTags.push(item);
  22935. forEach(item);
  22936. }
  22937. }
  22938. return listByTags;
  22939. };
  22940. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  22941. return this._getByTags(this.meshes, tagsQuery, forEach);
  22942. };
  22943. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  22944. return this._getByTags(this.cameras, tagsQuery, forEach);
  22945. };
  22946. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  22947. return this._getByTags(this.lights, tagsQuery, forEach);
  22948. };
  22949. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  22950. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  22951. };
  22952. /**
  22953. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22954. * This allowed control for front to back rendering or reversly depending of the special needs.
  22955. *
  22956. * @param renderingGroupId The rendering group id corresponding to its index
  22957. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22958. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22959. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22960. */
  22961. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22962. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22963. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22964. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22965. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  22966. };
  22967. /**
  22968. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22969. *
  22970. * @param renderingGroupId The rendering group id corresponding to its index
  22971. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22972. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22973. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22974. */
  22975. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22976. if (depth === void 0) { depth = true; }
  22977. if (stencil === void 0) { stencil = true; }
  22978. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  22979. };
  22980. /**
  22981. * Will flag all materials as dirty to trigger new shader compilation
  22982. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  22983. */
  22984. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  22985. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  22986. var material = _a[_i];
  22987. if (predicate && !predicate(material)) {
  22988. continue;
  22989. }
  22990. material.markAsDirty(flag);
  22991. }
  22992. };
  22993. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  22994. var _this = this;
  22995. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  22996. this._activeRequests.push(request);
  22997. request.onCompleteObservable.add(function (request) {
  22998. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  22999. });
  23000. return request;
  23001. };
  23002. // Statics
  23003. Scene._FOGMODE_NONE = 0;
  23004. Scene._FOGMODE_EXP = 1;
  23005. Scene._FOGMODE_EXP2 = 2;
  23006. Scene._FOGMODE_LINEAR = 3;
  23007. Scene._uniqueIdCounter = 0;
  23008. Scene.MinDeltaTime = 1.0;
  23009. Scene.MaxDeltaTime = 1000.0;
  23010. /** The distance in pixel that you have to move to prevent some events */
  23011. Scene.DragMovementThreshold = 10; // in pixels
  23012. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  23013. Scene.LongPressDelay = 500; // in milliseconds
  23014. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  23015. Scene.DoubleClickDelay = 300; // in milliseconds
  23016. /** If you need to check double click without raising a single click at first click, enable this flag */
  23017. Scene.ExclusiveDoubleClickMode = false;
  23018. return Scene;
  23019. }());
  23020. BABYLON.Scene = Scene;
  23021. })(BABYLON || (BABYLON = {}));
  23022. //# sourceMappingURL=babylon.scene.js.map
  23023. var BABYLON;
  23024. (function (BABYLON) {
  23025. var Buffer = /** @class */ (function () {
  23026. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  23027. if (instanced === void 0) { instanced = false; }
  23028. if (engine instanceof BABYLON.Mesh) {
  23029. this._engine = engine.getScene().getEngine();
  23030. }
  23031. else {
  23032. this._engine = engine;
  23033. }
  23034. this._updatable = updatable;
  23035. this._data = data;
  23036. this._strideSize = stride;
  23037. if (!postponeInternalCreation) {
  23038. this.create();
  23039. }
  23040. this._instanced = instanced;
  23041. this._instanceDivisor = instanced ? 1 : 0;
  23042. }
  23043. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  23044. // a lot of these parameters are ignored as they are overriden by the buffer
  23045. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  23046. };
  23047. // Properties
  23048. Buffer.prototype.isUpdatable = function () {
  23049. return this._updatable;
  23050. };
  23051. Buffer.prototype.getData = function () {
  23052. return this._data;
  23053. };
  23054. Buffer.prototype.getBuffer = function () {
  23055. return this._buffer;
  23056. };
  23057. Buffer.prototype.getStrideSize = function () {
  23058. return this._strideSize;
  23059. };
  23060. Buffer.prototype.getIsInstanced = function () {
  23061. return this._instanced;
  23062. };
  23063. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  23064. get: function () {
  23065. return this._instanceDivisor;
  23066. },
  23067. set: function (value) {
  23068. this._instanceDivisor = value;
  23069. if (value == 0) {
  23070. this._instanced = false;
  23071. }
  23072. else {
  23073. this._instanced = true;
  23074. }
  23075. },
  23076. enumerable: true,
  23077. configurable: true
  23078. });
  23079. // Methods
  23080. Buffer.prototype.create = function (data) {
  23081. if (data === void 0) { data = null; }
  23082. if (!data && this._buffer) {
  23083. return; // nothing to do
  23084. }
  23085. data = data || this._data;
  23086. if (!data) {
  23087. return;
  23088. }
  23089. if (!this._buffer) {
  23090. if (this._updatable) {
  23091. this._buffer = this._engine.createDynamicVertexBuffer(data);
  23092. this._data = data;
  23093. }
  23094. else {
  23095. this._buffer = this._engine.createVertexBuffer(data);
  23096. }
  23097. }
  23098. else if (this._updatable) {
  23099. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  23100. this._data = data;
  23101. }
  23102. };
  23103. Buffer.prototype._rebuild = function () {
  23104. this._buffer = null;
  23105. this.create(this._data);
  23106. };
  23107. Buffer.prototype.update = function (data) {
  23108. this.create(data);
  23109. };
  23110. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  23111. if (!this._buffer) {
  23112. return;
  23113. }
  23114. if (this._updatable) {
  23115. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  23116. this._data = null;
  23117. }
  23118. };
  23119. Buffer.prototype.dispose = function () {
  23120. if (!this._buffer) {
  23121. return;
  23122. }
  23123. if (this._engine._releaseBuffer(this._buffer)) {
  23124. this._buffer = null;
  23125. }
  23126. };
  23127. return Buffer;
  23128. }());
  23129. BABYLON.Buffer = Buffer;
  23130. })(BABYLON || (BABYLON = {}));
  23131. //# sourceMappingURL=babylon.buffer.js.map
  23132. var BABYLON;
  23133. (function (BABYLON) {
  23134. var VertexBuffer = /** @class */ (function () {
  23135. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  23136. if (!stride) {
  23137. // Deduce stride from kind
  23138. switch (kind) {
  23139. case VertexBuffer.PositionKind:
  23140. stride = 3;
  23141. break;
  23142. case VertexBuffer.NormalKind:
  23143. stride = 3;
  23144. break;
  23145. case VertexBuffer.UVKind:
  23146. case VertexBuffer.UV2Kind:
  23147. case VertexBuffer.UV3Kind:
  23148. case VertexBuffer.UV4Kind:
  23149. case VertexBuffer.UV5Kind:
  23150. case VertexBuffer.UV6Kind:
  23151. stride = 2;
  23152. break;
  23153. case VertexBuffer.TangentKind:
  23154. case VertexBuffer.ColorKind:
  23155. stride = 4;
  23156. break;
  23157. case VertexBuffer.MatricesIndicesKind:
  23158. case VertexBuffer.MatricesIndicesExtraKind:
  23159. stride = 4;
  23160. break;
  23161. case VertexBuffer.MatricesWeightsKind:
  23162. case VertexBuffer.MatricesWeightsExtraKind:
  23163. default:
  23164. stride = 4;
  23165. break;
  23166. }
  23167. }
  23168. if (data instanceof BABYLON.Buffer) {
  23169. if (!stride) {
  23170. stride = data.getStrideSize();
  23171. }
  23172. this._buffer = data;
  23173. this._ownsBuffer = false;
  23174. }
  23175. else {
  23176. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  23177. this._ownsBuffer = true;
  23178. }
  23179. this._stride = stride;
  23180. this._offset = offset ? offset : 0;
  23181. this._size = size ? size : stride;
  23182. this._kind = kind;
  23183. }
  23184. VertexBuffer.prototype._rebuild = function () {
  23185. if (!this._buffer) {
  23186. return;
  23187. }
  23188. this._buffer._rebuild();
  23189. };
  23190. /**
  23191. * Returns the kind of the VertexBuffer (string).
  23192. */
  23193. VertexBuffer.prototype.getKind = function () {
  23194. return this._kind;
  23195. };
  23196. // Properties
  23197. /**
  23198. * Boolean : is the VertexBuffer updatable ?
  23199. */
  23200. VertexBuffer.prototype.isUpdatable = function () {
  23201. return this._buffer.isUpdatable();
  23202. };
  23203. /**
  23204. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  23205. */
  23206. VertexBuffer.prototype.getData = function () {
  23207. return this._buffer.getData();
  23208. };
  23209. /**
  23210. * Returns the WebGLBuffer associated to the VertexBuffer.
  23211. */
  23212. VertexBuffer.prototype.getBuffer = function () {
  23213. return this._buffer.getBuffer();
  23214. };
  23215. /**
  23216. * Returns the stride of the VertexBuffer (integer).
  23217. */
  23218. VertexBuffer.prototype.getStrideSize = function () {
  23219. return this._stride;
  23220. };
  23221. /**
  23222. * Returns the offset (integer).
  23223. */
  23224. VertexBuffer.prototype.getOffset = function () {
  23225. return this._offset;
  23226. };
  23227. /**
  23228. * Returns the VertexBuffer total size (integer).
  23229. */
  23230. VertexBuffer.prototype.getSize = function () {
  23231. return this._size;
  23232. };
  23233. /**
  23234. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  23235. */
  23236. VertexBuffer.prototype.getIsInstanced = function () {
  23237. return this._buffer.getIsInstanced();
  23238. };
  23239. /**
  23240. * Returns the instancing divisor, zero for non-instanced (integer).
  23241. */
  23242. VertexBuffer.prototype.getInstanceDivisor = function () {
  23243. return this._buffer.instanceDivisor;
  23244. };
  23245. // Methods
  23246. /**
  23247. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  23248. * Returns the created WebGLBuffer.
  23249. */
  23250. VertexBuffer.prototype.create = function (data) {
  23251. return this._buffer.create(data);
  23252. };
  23253. /**
  23254. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  23255. * Returns the updated WebGLBuffer.
  23256. */
  23257. VertexBuffer.prototype.update = function (data) {
  23258. return this._buffer.update(data);
  23259. };
  23260. /**
  23261. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  23262. * Returns the directly updated WebGLBuffer.
  23263. */
  23264. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  23265. return this._buffer.updateDirectly(data, offset);
  23266. };
  23267. /**
  23268. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  23269. */
  23270. VertexBuffer.prototype.dispose = function () {
  23271. if (this._ownsBuffer) {
  23272. this._buffer.dispose();
  23273. }
  23274. };
  23275. Object.defineProperty(VertexBuffer, "PositionKind", {
  23276. get: function () {
  23277. return VertexBuffer._PositionKind;
  23278. },
  23279. enumerable: true,
  23280. configurable: true
  23281. });
  23282. Object.defineProperty(VertexBuffer, "NormalKind", {
  23283. get: function () {
  23284. return VertexBuffer._NormalKind;
  23285. },
  23286. enumerable: true,
  23287. configurable: true
  23288. });
  23289. Object.defineProperty(VertexBuffer, "TangentKind", {
  23290. get: function () {
  23291. return VertexBuffer._TangentKind;
  23292. },
  23293. enumerable: true,
  23294. configurable: true
  23295. });
  23296. Object.defineProperty(VertexBuffer, "UVKind", {
  23297. get: function () {
  23298. return VertexBuffer._UVKind;
  23299. },
  23300. enumerable: true,
  23301. configurable: true
  23302. });
  23303. Object.defineProperty(VertexBuffer, "UV2Kind", {
  23304. get: function () {
  23305. return VertexBuffer._UV2Kind;
  23306. },
  23307. enumerable: true,
  23308. configurable: true
  23309. });
  23310. Object.defineProperty(VertexBuffer, "UV3Kind", {
  23311. get: function () {
  23312. return VertexBuffer._UV3Kind;
  23313. },
  23314. enumerable: true,
  23315. configurable: true
  23316. });
  23317. Object.defineProperty(VertexBuffer, "UV4Kind", {
  23318. get: function () {
  23319. return VertexBuffer._UV4Kind;
  23320. },
  23321. enumerable: true,
  23322. configurable: true
  23323. });
  23324. Object.defineProperty(VertexBuffer, "UV5Kind", {
  23325. get: function () {
  23326. return VertexBuffer._UV5Kind;
  23327. },
  23328. enumerable: true,
  23329. configurable: true
  23330. });
  23331. Object.defineProperty(VertexBuffer, "UV6Kind", {
  23332. get: function () {
  23333. return VertexBuffer._UV6Kind;
  23334. },
  23335. enumerable: true,
  23336. configurable: true
  23337. });
  23338. Object.defineProperty(VertexBuffer, "ColorKind", {
  23339. get: function () {
  23340. return VertexBuffer._ColorKind;
  23341. },
  23342. enumerable: true,
  23343. configurable: true
  23344. });
  23345. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  23346. get: function () {
  23347. return VertexBuffer._MatricesIndicesKind;
  23348. },
  23349. enumerable: true,
  23350. configurable: true
  23351. });
  23352. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  23353. get: function () {
  23354. return VertexBuffer._MatricesWeightsKind;
  23355. },
  23356. enumerable: true,
  23357. configurable: true
  23358. });
  23359. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  23360. get: function () {
  23361. return VertexBuffer._MatricesIndicesExtraKind;
  23362. },
  23363. enumerable: true,
  23364. configurable: true
  23365. });
  23366. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  23367. get: function () {
  23368. return VertexBuffer._MatricesWeightsExtraKind;
  23369. },
  23370. enumerable: true,
  23371. configurable: true
  23372. });
  23373. // Enums
  23374. VertexBuffer._PositionKind = "position";
  23375. VertexBuffer._NormalKind = "normal";
  23376. VertexBuffer._TangentKind = "tangent";
  23377. VertexBuffer._UVKind = "uv";
  23378. VertexBuffer._UV2Kind = "uv2";
  23379. VertexBuffer._UV3Kind = "uv3";
  23380. VertexBuffer._UV4Kind = "uv4";
  23381. VertexBuffer._UV5Kind = "uv5";
  23382. VertexBuffer._UV6Kind = "uv6";
  23383. VertexBuffer._ColorKind = "color";
  23384. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  23385. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  23386. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  23387. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  23388. return VertexBuffer;
  23389. }());
  23390. BABYLON.VertexBuffer = VertexBuffer;
  23391. })(BABYLON || (BABYLON = {}));
  23392. //# sourceMappingURL=babylon.vertexBuffer.js.map
  23393. var BABYLON;
  23394. (function (BABYLON) {
  23395. var InternalTexture = /** @class */ (function () {
  23396. function InternalTexture(engine, dataSource) {
  23397. this.onLoadedObservable = new BABYLON.Observable();
  23398. // Private
  23399. this._initialSlot = -1;
  23400. this._designatedSlot = -1;
  23401. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  23402. this._references = 1;
  23403. this._engine = engine;
  23404. this._dataSource = dataSource;
  23405. this._webGLTexture = engine._createTexture();
  23406. }
  23407. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  23408. get: function () {
  23409. return this._dataSource;
  23410. },
  23411. enumerable: true,
  23412. configurable: true
  23413. });
  23414. InternalTexture.prototype.incrementReferences = function () {
  23415. this._references++;
  23416. };
  23417. InternalTexture.prototype.updateSize = function (width, height, depth) {
  23418. if (depth === void 0) { depth = 1; }
  23419. this.width = width;
  23420. this.height = height;
  23421. this.depth = depth;
  23422. this.baseWidth = width;
  23423. this.baseHeight = height;
  23424. this.baseDepth = depth;
  23425. this._size = width * height * depth;
  23426. };
  23427. InternalTexture.prototype._rebuild = function () {
  23428. var _this = this;
  23429. var proxy;
  23430. this.isReady = false;
  23431. this._cachedCoordinatesMode = null;
  23432. this._cachedWrapU = null;
  23433. this._cachedWrapV = null;
  23434. this._cachedAnisotropicFilteringLevel = null;
  23435. switch (this._dataSource) {
  23436. case InternalTexture.DATASOURCE_TEMP:
  23437. return;
  23438. case InternalTexture.DATASOURCE_URL:
  23439. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  23440. _this.isReady = true;
  23441. }, null, this._buffer, undefined, this.format);
  23442. proxy._swapAndDie(this);
  23443. return;
  23444. case InternalTexture.DATASOURCE_RAW:
  23445. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23446. proxy._swapAndDie(this);
  23447. this.isReady = true;
  23448. return;
  23449. case InternalTexture.DATASOURCE_RAW3D:
  23450. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23451. proxy._swapAndDie(this);
  23452. this.isReady = true;
  23453. return;
  23454. case InternalTexture.DATASOURCE_DYNAMIC:
  23455. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  23456. proxy._swapAndDie(this);
  23457. // The engine will make sure to update content so no need to flag it as isReady = true
  23458. return;
  23459. case InternalTexture.DATASOURCE_RENDERTARGET:
  23460. var options = new BABYLON.RenderTargetCreationOptions();
  23461. options.generateDepthBuffer = this._generateDepthBuffer;
  23462. options.generateMipMaps = this.generateMipMaps;
  23463. options.generateStencilBuffer = this._generateStencilBuffer;
  23464. options.samplingMode = this.samplingMode;
  23465. options.type = this.type;
  23466. if (this.isCube) {
  23467. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  23468. }
  23469. else {
  23470. var size = {
  23471. width: this.width,
  23472. height: this.height
  23473. };
  23474. proxy = this._engine.createRenderTargetTexture(size, options);
  23475. }
  23476. proxy._swapAndDie(this);
  23477. this.isReady = true;
  23478. return;
  23479. case InternalTexture.DATASOURCE_CUBE:
  23480. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  23481. _this.isReady = true;
  23482. }, null, this.format, this._extension);
  23483. proxy._swapAndDie(this);
  23484. return;
  23485. case InternalTexture.DATASOURCE_CUBERAW:
  23486. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23487. proxy._swapAndDie(this);
  23488. this.isReady = true;
  23489. return;
  23490. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  23491. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  23492. if (proxy) {
  23493. proxy._swapAndDie(_this);
  23494. }
  23495. _this.isReady = true;
  23496. }, null, this.format, this._extension);
  23497. return;
  23498. }
  23499. };
  23500. InternalTexture.prototype._swapAndDie = function (target) {
  23501. target._webGLTexture = this._webGLTexture;
  23502. if (this._framebuffer) {
  23503. target._framebuffer = this._framebuffer;
  23504. }
  23505. if (this._depthStencilBuffer) {
  23506. target._depthStencilBuffer = this._depthStencilBuffer;
  23507. }
  23508. if (this._lodTextureHigh) {
  23509. if (target._lodTextureHigh) {
  23510. target._lodTextureHigh.dispose();
  23511. }
  23512. target._lodTextureHigh = this._lodTextureHigh;
  23513. }
  23514. if (this._lodTextureMid) {
  23515. if (target._lodTextureMid) {
  23516. target._lodTextureMid.dispose();
  23517. }
  23518. target._lodTextureMid = this._lodTextureMid;
  23519. }
  23520. if (this._lodTextureLow) {
  23521. if (target._lodTextureLow) {
  23522. target._lodTextureLow.dispose();
  23523. }
  23524. target._lodTextureLow = this._lodTextureLow;
  23525. }
  23526. var cache = this._engine.getLoadedTexturesCache();
  23527. var index = cache.indexOf(this);
  23528. if (index !== -1) {
  23529. cache.splice(index, 1);
  23530. }
  23531. };
  23532. InternalTexture.prototype.dispose = function () {
  23533. if (!this._webGLTexture) {
  23534. return;
  23535. }
  23536. this._references--;
  23537. if (this._references === 0) {
  23538. this._engine._releaseTexture(this);
  23539. this._webGLTexture = null;
  23540. }
  23541. };
  23542. InternalTexture.DATASOURCE_UNKNOWN = 0;
  23543. InternalTexture.DATASOURCE_URL = 1;
  23544. InternalTexture.DATASOURCE_TEMP = 2;
  23545. InternalTexture.DATASOURCE_RAW = 3;
  23546. InternalTexture.DATASOURCE_DYNAMIC = 4;
  23547. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  23548. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  23549. InternalTexture.DATASOURCE_CUBE = 7;
  23550. InternalTexture.DATASOURCE_CUBERAW = 8;
  23551. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  23552. InternalTexture.DATASOURCE_RAW3D = 10;
  23553. return InternalTexture;
  23554. }());
  23555. BABYLON.InternalTexture = InternalTexture;
  23556. })(BABYLON || (BABYLON = {}));
  23557. //# sourceMappingURL=babylon.internalTexture.js.map
  23558. var BABYLON;
  23559. (function (BABYLON) {
  23560. var BaseTexture = /** @class */ (function () {
  23561. function BaseTexture(scene) {
  23562. this._hasAlpha = false;
  23563. this.getAlphaFromRGB = false;
  23564. this.level = 1;
  23565. this.coordinatesIndex = 0;
  23566. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  23567. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  23568. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  23569. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  23570. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  23571. this.isCube = false;
  23572. this.is3D = false;
  23573. this.gammaSpace = true;
  23574. this.invertZ = false;
  23575. this.lodLevelInAlpha = false;
  23576. this.lodGenerationOffset = 0.0;
  23577. this.lodGenerationScale = 0.8;
  23578. this.isRenderTarget = false;
  23579. this.animations = new Array();
  23580. /**
  23581. * An event triggered when the texture is disposed.
  23582. * @type {BABYLON.Observable}
  23583. */
  23584. this.onDisposeObservable = new BABYLON.Observable();
  23585. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23586. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  23587. if (this._scene) {
  23588. this._scene.textures.push(this);
  23589. }
  23590. this._uid = null;
  23591. }
  23592. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  23593. get: function () {
  23594. return this._hasAlpha;
  23595. },
  23596. set: function (value) {
  23597. if (this._hasAlpha === value) {
  23598. return;
  23599. }
  23600. this._hasAlpha = value;
  23601. if (this._scene) {
  23602. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23603. }
  23604. },
  23605. enumerable: true,
  23606. configurable: true
  23607. });
  23608. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  23609. get: function () {
  23610. return this._coordinatesMode;
  23611. },
  23612. set: function (value) {
  23613. if (this._coordinatesMode === value) {
  23614. return;
  23615. }
  23616. this._coordinatesMode = value;
  23617. if (this._scene) {
  23618. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23619. }
  23620. },
  23621. enumerable: true,
  23622. configurable: true
  23623. });
  23624. Object.defineProperty(BaseTexture.prototype, "uid", {
  23625. get: function () {
  23626. if (!this._uid) {
  23627. this._uid = BABYLON.Tools.RandomId();
  23628. }
  23629. return this._uid;
  23630. },
  23631. enumerable: true,
  23632. configurable: true
  23633. });
  23634. BaseTexture.prototype.toString = function () {
  23635. return this.name;
  23636. };
  23637. BaseTexture.prototype.getClassName = function () {
  23638. return "BaseTexture";
  23639. };
  23640. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  23641. set: function (callback) {
  23642. if (this._onDisposeObserver) {
  23643. this.onDisposeObservable.remove(this._onDisposeObserver);
  23644. }
  23645. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23646. },
  23647. enumerable: true,
  23648. configurable: true
  23649. });
  23650. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  23651. get: function () {
  23652. return true;
  23653. },
  23654. enumerable: true,
  23655. configurable: true
  23656. });
  23657. BaseTexture.prototype.getScene = function () {
  23658. return this._scene;
  23659. };
  23660. BaseTexture.prototype.getTextureMatrix = function () {
  23661. return BABYLON.Matrix.IdentityReadOnly;
  23662. };
  23663. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  23664. return BABYLON.Matrix.IdentityReadOnly;
  23665. };
  23666. BaseTexture.prototype.getInternalTexture = function () {
  23667. return this._texture;
  23668. };
  23669. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  23670. return !this.isBlocking || this.isReady();
  23671. };
  23672. BaseTexture.prototype.isReady = function () {
  23673. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23674. this.delayLoad();
  23675. return false;
  23676. }
  23677. if (this._texture) {
  23678. return this._texture.isReady;
  23679. }
  23680. return false;
  23681. };
  23682. BaseTexture.prototype.getSize = function () {
  23683. if (this._texture && this._texture.width) {
  23684. return new BABYLON.Size(this._texture.width, this._texture.height);
  23685. }
  23686. if (this._texture && this._texture._size) {
  23687. return new BABYLON.Size(this._texture._size, this._texture._size);
  23688. }
  23689. return BABYLON.Size.Zero();
  23690. };
  23691. BaseTexture.prototype.getBaseSize = function () {
  23692. if (!this.isReady() || !this._texture)
  23693. return BABYLON.Size.Zero();
  23694. if (this._texture._size) {
  23695. return new BABYLON.Size(this._texture._size, this._texture._size);
  23696. }
  23697. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  23698. };
  23699. BaseTexture.prototype.scale = function (ratio) {
  23700. };
  23701. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  23702. get: function () {
  23703. return false;
  23704. },
  23705. enumerable: true,
  23706. configurable: true
  23707. });
  23708. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  23709. if (!this._scene) {
  23710. return null;
  23711. }
  23712. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  23713. for (var index = 0; index < texturesCache.length; index++) {
  23714. var texturesCacheEntry = texturesCache[index];
  23715. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  23716. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  23717. texturesCacheEntry.incrementReferences();
  23718. return texturesCacheEntry;
  23719. }
  23720. }
  23721. }
  23722. return null;
  23723. };
  23724. BaseTexture.prototype._rebuild = function () {
  23725. };
  23726. BaseTexture.prototype.delayLoad = function () {
  23727. };
  23728. BaseTexture.prototype.clone = function () {
  23729. return null;
  23730. };
  23731. Object.defineProperty(BaseTexture.prototype, "textureType", {
  23732. get: function () {
  23733. if (!this._texture) {
  23734. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  23735. }
  23736. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  23737. },
  23738. enumerable: true,
  23739. configurable: true
  23740. });
  23741. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  23742. get: function () {
  23743. if (!this._texture) {
  23744. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  23745. }
  23746. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  23747. },
  23748. enumerable: true,
  23749. configurable: true
  23750. });
  23751. BaseTexture.prototype.readPixels = function (faceIndex) {
  23752. if (faceIndex === void 0) { faceIndex = 0; }
  23753. if (!this._texture) {
  23754. return null;
  23755. }
  23756. var size = this.getSize();
  23757. var scene = this.getScene();
  23758. if (!scene) {
  23759. return null;
  23760. }
  23761. var engine = scene.getEngine();
  23762. if (this._texture.isCube) {
  23763. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  23764. }
  23765. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  23766. };
  23767. BaseTexture.prototype.releaseInternalTexture = function () {
  23768. if (this._texture) {
  23769. this._texture.dispose();
  23770. this._texture = null;
  23771. }
  23772. };
  23773. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  23774. get: function () {
  23775. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  23776. return null;
  23777. }
  23778. if (!this._texture._sphericalPolynomial) {
  23779. this._texture._sphericalPolynomial =
  23780. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  23781. }
  23782. return this._texture._sphericalPolynomial;
  23783. },
  23784. set: function (value) {
  23785. if (this._texture) {
  23786. this._texture._sphericalPolynomial = value;
  23787. }
  23788. },
  23789. enumerable: true,
  23790. configurable: true
  23791. });
  23792. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  23793. get: function () {
  23794. if (this._texture) {
  23795. return this._texture._lodTextureHigh;
  23796. }
  23797. return null;
  23798. },
  23799. enumerable: true,
  23800. configurable: true
  23801. });
  23802. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  23803. get: function () {
  23804. if (this._texture) {
  23805. return this._texture._lodTextureMid;
  23806. }
  23807. return null;
  23808. },
  23809. enumerable: true,
  23810. configurable: true
  23811. });
  23812. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  23813. get: function () {
  23814. if (this._texture) {
  23815. return this._texture._lodTextureLow;
  23816. }
  23817. return null;
  23818. },
  23819. enumerable: true,
  23820. configurable: true
  23821. });
  23822. BaseTexture.prototype.dispose = function () {
  23823. if (!this._scene) {
  23824. return;
  23825. }
  23826. // Animations
  23827. this._scene.stopAnimation(this);
  23828. // Remove from scene
  23829. this._scene._removePendingData(this);
  23830. var index = this._scene.textures.indexOf(this);
  23831. if (index >= 0) {
  23832. this._scene.textures.splice(index, 1);
  23833. }
  23834. if (this._texture === undefined) {
  23835. return;
  23836. }
  23837. // Release
  23838. this.releaseInternalTexture();
  23839. // Callback
  23840. this.onDisposeObservable.notifyObservers(this);
  23841. this.onDisposeObservable.clear();
  23842. };
  23843. BaseTexture.prototype.serialize = function () {
  23844. if (!this.name) {
  23845. return null;
  23846. }
  23847. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23848. // Animations
  23849. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23850. return serializationObject;
  23851. };
  23852. BaseTexture.WhenAllReady = function (textures, callback) {
  23853. var numRemaining = textures.length;
  23854. if (numRemaining === 0) {
  23855. callback();
  23856. return;
  23857. }
  23858. var _loop_1 = function () {
  23859. texture = textures[i];
  23860. if (texture.isReady()) {
  23861. if (--numRemaining === 0) {
  23862. callback();
  23863. }
  23864. }
  23865. else {
  23866. onLoadObservable = texture.onLoadObservable;
  23867. var onLoadCallback_1 = function () {
  23868. onLoadObservable.removeCallback(onLoadCallback_1);
  23869. if (--numRemaining === 0) {
  23870. callback();
  23871. }
  23872. };
  23873. onLoadObservable.add(onLoadCallback_1);
  23874. }
  23875. };
  23876. var texture, onLoadObservable;
  23877. for (var i = 0; i < textures.length; i++) {
  23878. _loop_1();
  23879. }
  23880. };
  23881. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  23882. __decorate([
  23883. BABYLON.serialize()
  23884. ], BaseTexture.prototype, "name", void 0);
  23885. __decorate([
  23886. BABYLON.serialize("hasAlpha")
  23887. ], BaseTexture.prototype, "_hasAlpha", void 0);
  23888. __decorate([
  23889. BABYLON.serialize()
  23890. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  23891. __decorate([
  23892. BABYLON.serialize()
  23893. ], BaseTexture.prototype, "level", void 0);
  23894. __decorate([
  23895. BABYLON.serialize()
  23896. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  23897. __decorate([
  23898. BABYLON.serialize("coordinatesMode")
  23899. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  23900. __decorate([
  23901. BABYLON.serialize()
  23902. ], BaseTexture.prototype, "wrapU", void 0);
  23903. __decorate([
  23904. BABYLON.serialize()
  23905. ], BaseTexture.prototype, "wrapV", void 0);
  23906. __decorate([
  23907. BABYLON.serialize()
  23908. ], BaseTexture.prototype, "wrapR", void 0);
  23909. __decorate([
  23910. BABYLON.serialize()
  23911. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  23912. __decorate([
  23913. BABYLON.serialize()
  23914. ], BaseTexture.prototype, "isCube", void 0);
  23915. __decorate([
  23916. BABYLON.serialize()
  23917. ], BaseTexture.prototype, "is3D", void 0);
  23918. __decorate([
  23919. BABYLON.serialize()
  23920. ], BaseTexture.prototype, "gammaSpace", void 0);
  23921. __decorate([
  23922. BABYLON.serialize()
  23923. ], BaseTexture.prototype, "invertZ", void 0);
  23924. __decorate([
  23925. BABYLON.serialize()
  23926. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  23927. __decorate([
  23928. BABYLON.serialize()
  23929. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  23930. __decorate([
  23931. BABYLON.serialize()
  23932. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  23933. __decorate([
  23934. BABYLON.serialize()
  23935. ], BaseTexture.prototype, "isRenderTarget", void 0);
  23936. return BaseTexture;
  23937. }());
  23938. BABYLON.BaseTexture = BaseTexture;
  23939. })(BABYLON || (BABYLON = {}));
  23940. //# sourceMappingURL=babylon.baseTexture.js.map
  23941. var BABYLON;
  23942. (function (BABYLON) {
  23943. var Texture = /** @class */ (function (_super) {
  23944. __extends(Texture, _super);
  23945. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  23946. if (noMipmap === void 0) { noMipmap = false; }
  23947. if (invertY === void 0) { invertY = true; }
  23948. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23949. if (onLoad === void 0) { onLoad = null; }
  23950. if (onError === void 0) { onError = null; }
  23951. if (buffer === void 0) { buffer = null; }
  23952. if (deleteBuffer === void 0) { deleteBuffer = false; }
  23953. var _this = _super.call(this, scene) || this;
  23954. _this.uOffset = 0;
  23955. _this.vOffset = 0;
  23956. _this.uScale = 1.0;
  23957. _this.vScale = 1.0;
  23958. _this.uAng = 0;
  23959. _this.vAng = 0;
  23960. _this.wAng = 0;
  23961. _this._isBlocking = true;
  23962. _this.name = url || "";
  23963. _this.url = url;
  23964. _this._noMipmap = noMipmap;
  23965. _this._invertY = invertY;
  23966. _this._samplingMode = samplingMode;
  23967. _this._buffer = buffer;
  23968. _this._deleteBuffer = deleteBuffer;
  23969. if (format) {
  23970. _this._format = format;
  23971. }
  23972. scene = _this.getScene();
  23973. if (!scene) {
  23974. return _this;
  23975. }
  23976. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  23977. var load = function () {
  23978. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  23979. _this.onLoadObservable.notifyObservers(_this);
  23980. }
  23981. if (onLoad) {
  23982. onLoad();
  23983. }
  23984. if (!_this.isBlocking && scene) {
  23985. scene.resetCachedMaterial();
  23986. }
  23987. };
  23988. if (!_this.url) {
  23989. _this._delayedOnLoad = load;
  23990. _this._delayedOnError = onError;
  23991. return _this;
  23992. }
  23993. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  23994. if (!_this._texture) {
  23995. if (!scene.useDelayedTextureLoading) {
  23996. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  23997. if (deleteBuffer) {
  23998. delete _this._buffer;
  23999. }
  24000. }
  24001. else {
  24002. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24003. _this._delayedOnLoad = load;
  24004. _this._delayedOnError = onError;
  24005. }
  24006. }
  24007. else {
  24008. if (_this._texture.isReady) {
  24009. BABYLON.Tools.SetImmediate(function () { return load(); });
  24010. }
  24011. else {
  24012. _this._texture.onLoadedObservable.add(load);
  24013. }
  24014. }
  24015. return _this;
  24016. }
  24017. Object.defineProperty(Texture.prototype, "noMipmap", {
  24018. get: function () {
  24019. return this._noMipmap;
  24020. },
  24021. enumerable: true,
  24022. configurable: true
  24023. });
  24024. Object.defineProperty(Texture.prototype, "isBlocking", {
  24025. get: function () {
  24026. return this._isBlocking;
  24027. },
  24028. set: function (value) {
  24029. this._isBlocking = value;
  24030. },
  24031. enumerable: true,
  24032. configurable: true
  24033. });
  24034. Object.defineProperty(Texture.prototype, "samplingMode", {
  24035. get: function () {
  24036. return this._samplingMode;
  24037. },
  24038. enumerable: true,
  24039. configurable: true
  24040. });
  24041. Texture.prototype.updateURL = function (url) {
  24042. this.url = url;
  24043. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24044. this.delayLoad();
  24045. };
  24046. Texture.prototype.delayLoad = function () {
  24047. var _this = this;
  24048. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24049. return;
  24050. }
  24051. var scene = this.getScene();
  24052. if (!scene) {
  24053. return;
  24054. }
  24055. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24056. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  24057. if (!this._texture) {
  24058. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  24059. if (this._deleteBuffer) {
  24060. delete this._buffer;
  24061. }
  24062. }
  24063. else {
  24064. if (this._texture.isReady) {
  24065. BABYLON.Tools.SetImmediate(function () {
  24066. if (!_this._delayedOnLoad) {
  24067. return;
  24068. }
  24069. _this._delayedOnLoad();
  24070. });
  24071. }
  24072. else {
  24073. if (this._delayedOnLoad) {
  24074. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  24075. }
  24076. }
  24077. }
  24078. };
  24079. Texture.prototype.updateSamplingMode = function (samplingMode) {
  24080. if (!this._texture) {
  24081. return;
  24082. }
  24083. var scene = this.getScene();
  24084. if (!scene) {
  24085. return;
  24086. }
  24087. this._samplingMode = samplingMode;
  24088. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  24089. };
  24090. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  24091. x *= this.uScale;
  24092. y *= this.vScale;
  24093. x -= 0.5 * this.uScale;
  24094. y -= 0.5 * this.vScale;
  24095. z -= 0.5;
  24096. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  24097. t.x += 0.5 * this.uScale + this.uOffset;
  24098. t.y += 0.5 * this.vScale + this.vOffset;
  24099. t.z += 0.5;
  24100. };
  24101. Texture.prototype.getTextureMatrix = function () {
  24102. var _this = this;
  24103. if (this.uOffset === this._cachedUOffset &&
  24104. this.vOffset === this._cachedVOffset &&
  24105. this.uScale === this._cachedUScale &&
  24106. this.vScale === this._cachedVScale &&
  24107. this.uAng === this._cachedUAng &&
  24108. this.vAng === this._cachedVAng &&
  24109. this.wAng === this._cachedWAng) {
  24110. return this._cachedTextureMatrix;
  24111. }
  24112. this._cachedUOffset = this.uOffset;
  24113. this._cachedVOffset = this.vOffset;
  24114. this._cachedUScale = this.uScale;
  24115. this._cachedVScale = this.vScale;
  24116. this._cachedUAng = this.uAng;
  24117. this._cachedVAng = this.vAng;
  24118. this._cachedWAng = this.wAng;
  24119. if (!this._cachedTextureMatrix) {
  24120. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24121. this._rowGenerationMatrix = new BABYLON.Matrix();
  24122. this._t0 = BABYLON.Vector3.Zero();
  24123. this._t1 = BABYLON.Vector3.Zero();
  24124. this._t2 = BABYLON.Vector3.Zero();
  24125. }
  24126. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  24127. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  24128. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  24129. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  24130. this._t1.subtractInPlace(this._t0);
  24131. this._t2.subtractInPlace(this._t0);
  24132. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24133. this._cachedTextureMatrix.m[0] = this._t1.x;
  24134. this._cachedTextureMatrix.m[1] = this._t1.y;
  24135. this._cachedTextureMatrix.m[2] = this._t1.z;
  24136. this._cachedTextureMatrix.m[4] = this._t2.x;
  24137. this._cachedTextureMatrix.m[5] = this._t2.y;
  24138. this._cachedTextureMatrix.m[6] = this._t2.z;
  24139. this._cachedTextureMatrix.m[8] = this._t0.x;
  24140. this._cachedTextureMatrix.m[9] = this._t0.y;
  24141. this._cachedTextureMatrix.m[10] = this._t0.z;
  24142. var scene = this.getScene();
  24143. if (!scene) {
  24144. return this._cachedTextureMatrix;
  24145. }
  24146. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  24147. return mat.hasTexture(_this);
  24148. });
  24149. return this._cachedTextureMatrix;
  24150. };
  24151. Texture.prototype.getReflectionTextureMatrix = function () {
  24152. var _this = this;
  24153. var scene = this.getScene();
  24154. if (!scene) {
  24155. return this._cachedTextureMatrix;
  24156. }
  24157. if (this.uOffset === this._cachedUOffset &&
  24158. this.vOffset === this._cachedVOffset &&
  24159. this.uScale === this._cachedUScale &&
  24160. this.vScale === this._cachedVScale &&
  24161. this.coordinatesMode === this._cachedCoordinatesMode) {
  24162. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  24163. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  24164. return this._cachedTextureMatrix;
  24165. }
  24166. }
  24167. else {
  24168. return this._cachedTextureMatrix;
  24169. }
  24170. }
  24171. if (!this._cachedTextureMatrix) {
  24172. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24173. }
  24174. if (!this._projectionModeMatrix) {
  24175. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  24176. }
  24177. this._cachedUOffset = this.uOffset;
  24178. this._cachedVOffset = this.vOffset;
  24179. this._cachedUScale = this.uScale;
  24180. this._cachedVScale = this.vScale;
  24181. this._cachedCoordinatesMode = this.coordinatesMode;
  24182. switch (this.coordinatesMode) {
  24183. case Texture.PLANAR_MODE:
  24184. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24185. this._cachedTextureMatrix[0] = this.uScale;
  24186. this._cachedTextureMatrix[5] = this.vScale;
  24187. this._cachedTextureMatrix[12] = this.uOffset;
  24188. this._cachedTextureMatrix[13] = this.vOffset;
  24189. break;
  24190. case Texture.PROJECTION_MODE:
  24191. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  24192. this._projectionModeMatrix.m[0] = 0.5;
  24193. this._projectionModeMatrix.m[5] = -0.5;
  24194. this._projectionModeMatrix.m[10] = 0.0;
  24195. this._projectionModeMatrix.m[12] = 0.5;
  24196. this._projectionModeMatrix.m[13] = 0.5;
  24197. this._projectionModeMatrix.m[14] = 1.0;
  24198. this._projectionModeMatrix.m[15] = 1.0;
  24199. var projectionMatrix = scene.getProjectionMatrix();
  24200. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  24201. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  24202. break;
  24203. default:
  24204. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24205. break;
  24206. }
  24207. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  24208. return (mat.getActiveTextures().indexOf(_this) !== -1);
  24209. });
  24210. return this._cachedTextureMatrix;
  24211. };
  24212. Texture.prototype.clone = function () {
  24213. var _this = this;
  24214. return BABYLON.SerializationHelper.Clone(function () {
  24215. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  24216. }, this);
  24217. };
  24218. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  24219. get: function () {
  24220. if (!this._onLoadObservable) {
  24221. this._onLoadObservable = new BABYLON.Observable();
  24222. }
  24223. return this._onLoadObservable;
  24224. },
  24225. enumerable: true,
  24226. configurable: true
  24227. });
  24228. Texture.prototype.serialize = function () {
  24229. var serializationObject = _super.prototype.serialize.call(this);
  24230. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  24231. serializationObject.base64String = this._buffer;
  24232. serializationObject.name = serializationObject.name.replace("data:", "");
  24233. }
  24234. return serializationObject;
  24235. };
  24236. Texture.prototype.getClassName = function () {
  24237. return "Texture";
  24238. };
  24239. Texture.prototype.dispose = function () {
  24240. _super.prototype.dispose.call(this);
  24241. if (this.onLoadObservable) {
  24242. this.onLoadObservable.clear();
  24243. this._onLoadObservable = null;
  24244. }
  24245. this._delayedOnLoad = null;
  24246. this._delayedOnError = null;
  24247. };
  24248. // Statics
  24249. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  24250. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24251. if (onLoad === void 0) { onLoad = null; }
  24252. if (onError === void 0) { onError = null; }
  24253. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  24254. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  24255. };
  24256. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  24257. if (parsedTexture.customType) {
  24258. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  24259. // Update Sampling Mode
  24260. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  24261. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  24262. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  24263. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  24264. }
  24265. }
  24266. return parsedCustomTexture;
  24267. }
  24268. if (parsedTexture.isCube) {
  24269. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  24270. }
  24271. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  24272. return null;
  24273. }
  24274. var texture = BABYLON.SerializationHelper.Parse(function () {
  24275. var generateMipMaps = true;
  24276. if (parsedTexture.noMipmap) {
  24277. generateMipMaps = false;
  24278. }
  24279. if (parsedTexture.mirrorPlane) {
  24280. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  24281. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  24282. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  24283. return mirrorTexture;
  24284. }
  24285. else if (parsedTexture.isRenderTarget) {
  24286. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  24287. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  24288. return renderTargetTexture;
  24289. }
  24290. else {
  24291. var texture;
  24292. if (parsedTexture.base64String) {
  24293. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  24294. }
  24295. else {
  24296. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  24297. }
  24298. return texture;
  24299. }
  24300. }, parsedTexture, scene);
  24301. // Update Sampling Mode
  24302. if (parsedTexture.samplingMode) {
  24303. var sampling = parsedTexture.samplingMode;
  24304. if (texture._samplingMode !== sampling) {
  24305. texture.updateSamplingMode(sampling);
  24306. }
  24307. }
  24308. // Animations
  24309. if (parsedTexture.animations) {
  24310. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  24311. var parsedAnimation = parsedTexture.animations[animationIndex];
  24312. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24313. }
  24314. }
  24315. return texture;
  24316. };
  24317. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  24318. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24319. if (noMipmap === void 0) { noMipmap = false; }
  24320. if (invertY === void 0) { invertY = true; }
  24321. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24322. if (onLoad === void 0) { onLoad = null; }
  24323. if (onError === void 0) { onError = null; }
  24324. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  24325. if (name.substr(0, 5) !== "data:") {
  24326. name = "data:" + name;
  24327. }
  24328. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  24329. };
  24330. // Constants
  24331. Texture.NEAREST_SAMPLINGMODE = 1;
  24332. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  24333. Texture.BILINEAR_SAMPLINGMODE = 2;
  24334. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  24335. Texture.TRILINEAR_SAMPLINGMODE = 3;
  24336. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  24337. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  24338. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  24339. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  24340. Texture.NEAREST_LINEAR = 7;
  24341. Texture.NEAREST_NEAREST = 8;
  24342. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  24343. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  24344. Texture.LINEAR_LINEAR = 11;
  24345. Texture.LINEAR_NEAREST = 12;
  24346. Texture.EXPLICIT_MODE = 0;
  24347. Texture.SPHERICAL_MODE = 1;
  24348. Texture.PLANAR_MODE = 2;
  24349. Texture.CUBIC_MODE = 3;
  24350. Texture.PROJECTION_MODE = 4;
  24351. Texture.SKYBOX_MODE = 5;
  24352. Texture.INVCUBIC_MODE = 6;
  24353. Texture.EQUIRECTANGULAR_MODE = 7;
  24354. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  24355. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  24356. Texture.CLAMP_ADDRESSMODE = 0;
  24357. Texture.WRAP_ADDRESSMODE = 1;
  24358. Texture.MIRROR_ADDRESSMODE = 2;
  24359. __decorate([
  24360. BABYLON.serialize()
  24361. ], Texture.prototype, "url", void 0);
  24362. __decorate([
  24363. BABYLON.serialize()
  24364. ], Texture.prototype, "uOffset", void 0);
  24365. __decorate([
  24366. BABYLON.serialize()
  24367. ], Texture.prototype, "vOffset", void 0);
  24368. __decorate([
  24369. BABYLON.serialize()
  24370. ], Texture.prototype, "uScale", void 0);
  24371. __decorate([
  24372. BABYLON.serialize()
  24373. ], Texture.prototype, "vScale", void 0);
  24374. __decorate([
  24375. BABYLON.serialize()
  24376. ], Texture.prototype, "uAng", void 0);
  24377. __decorate([
  24378. BABYLON.serialize()
  24379. ], Texture.prototype, "vAng", void 0);
  24380. __decorate([
  24381. BABYLON.serialize()
  24382. ], Texture.prototype, "wAng", void 0);
  24383. __decorate([
  24384. BABYLON.serialize()
  24385. ], Texture.prototype, "isBlocking", null);
  24386. return Texture;
  24387. }(BABYLON.BaseTexture));
  24388. BABYLON.Texture = Texture;
  24389. })(BABYLON || (BABYLON = {}));
  24390. //# sourceMappingURL=babylon.texture.js.map
  24391. var BABYLON;
  24392. (function (BABYLON) {
  24393. var _InstancesBatch = /** @class */ (function () {
  24394. function _InstancesBatch() {
  24395. this.mustReturn = false;
  24396. this.visibleInstances = new Array();
  24397. this.renderSelf = new Array();
  24398. }
  24399. return _InstancesBatch;
  24400. }());
  24401. BABYLON._InstancesBatch = _InstancesBatch;
  24402. var Mesh = /** @class */ (function (_super) {
  24403. __extends(Mesh, _super);
  24404. /**
  24405. * @constructor
  24406. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  24407. * @param {Scene} scene The scene to add this mesh to.
  24408. * @param {Node} parent The parent of this mesh, if it has one
  24409. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  24410. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  24411. * When false, achieved by calling a clone(), also passing False.
  24412. * This will make creation of children, recursive.
  24413. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  24414. */
  24415. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  24416. if (scene === void 0) { scene = null; }
  24417. if (parent === void 0) { parent = null; }
  24418. if (source === void 0) { source = null; }
  24419. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  24420. var _this = _super.call(this, name, scene) || this;
  24421. // Events
  24422. /**
  24423. * An event triggered before rendering the mesh
  24424. * @type {BABYLON.Observable}
  24425. */
  24426. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24427. /**
  24428. * An event triggered after rendering the mesh
  24429. * @type {BABYLON.Observable}
  24430. */
  24431. _this.onAfterRenderObservable = new BABYLON.Observable();
  24432. /**
  24433. * An event triggered before drawing the mesh
  24434. * @type {BABYLON.Observable}
  24435. */
  24436. _this.onBeforeDrawObservable = new BABYLON.Observable();
  24437. // Members
  24438. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24439. _this.instances = new Array();
  24440. _this._LODLevels = new Array();
  24441. _this._visibleInstances = {};
  24442. _this._renderIdForInstances = new Array();
  24443. _this._batchCache = new _InstancesBatch();
  24444. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  24445. // Use by builder only to know what orientation were the mesh build in.
  24446. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  24447. _this.overrideMaterialSideOrientation = null;
  24448. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  24449. // Will be used to save a source mesh reference, If any
  24450. _this._source = null;
  24451. scene = _this.getScene();
  24452. if (source) {
  24453. // Source mesh
  24454. _this._source = source;
  24455. // Geometry
  24456. if (source._geometry) {
  24457. source._geometry.applyToMesh(_this);
  24458. }
  24459. // Deep copy
  24460. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source"], ["_poseMatrix", "_source"]);
  24461. // Tags
  24462. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  24463. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  24464. }
  24465. _this.metadata = source.metadata;
  24466. // Parent
  24467. _this.parent = source.parent;
  24468. // Pivot
  24469. _this.setPivotMatrix(source.getPivotMatrix());
  24470. _this.id = name + "." + source.id;
  24471. // Material
  24472. _this.material = source.material;
  24473. var index;
  24474. if (!doNotCloneChildren) {
  24475. // Children
  24476. var directDescendants = source.getDescendants(true);
  24477. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  24478. var child = directDescendants[index_1];
  24479. if (child.clone) {
  24480. child.clone(name + "." + child.name, _this);
  24481. }
  24482. }
  24483. }
  24484. // Physics clone
  24485. var physicsEngine = _this.getScene().getPhysicsEngine();
  24486. if (clonePhysicsImpostor && physicsEngine) {
  24487. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  24488. if (impostor) {
  24489. _this.physicsImpostor = impostor.clone(_this);
  24490. }
  24491. }
  24492. // Particles
  24493. for (index = 0; index < scene.particleSystems.length; index++) {
  24494. var system = scene.particleSystems[index];
  24495. if (system.emitter === source) {
  24496. system.clone(system.name, _this);
  24497. }
  24498. }
  24499. _this.computeWorldMatrix(true);
  24500. }
  24501. // Parent
  24502. if (parent !== null) {
  24503. _this.parent = parent;
  24504. }
  24505. return _this;
  24506. }
  24507. Object.defineProperty(Mesh, "FRONTSIDE", {
  24508. /**
  24509. * Mesh side orientation : usually the external or front surface
  24510. */
  24511. get: function () {
  24512. return Mesh._FRONTSIDE;
  24513. },
  24514. enumerable: true,
  24515. configurable: true
  24516. });
  24517. Object.defineProperty(Mesh, "BACKSIDE", {
  24518. /**
  24519. * Mesh side orientation : usually the internal or back surface
  24520. */
  24521. get: function () {
  24522. return Mesh._BACKSIDE;
  24523. },
  24524. enumerable: true,
  24525. configurable: true
  24526. });
  24527. Object.defineProperty(Mesh, "DOUBLESIDE", {
  24528. /**
  24529. * Mesh side orientation : both internal and external or front and back surfaces
  24530. */
  24531. get: function () {
  24532. return Mesh._DOUBLESIDE;
  24533. },
  24534. enumerable: true,
  24535. configurable: true
  24536. });
  24537. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  24538. /**
  24539. * Mesh side orientation : by default, `FRONTSIDE`
  24540. */
  24541. get: function () {
  24542. return Mesh._DEFAULTSIDE;
  24543. },
  24544. enumerable: true,
  24545. configurable: true
  24546. });
  24547. Object.defineProperty(Mesh, "NO_CAP", {
  24548. /**
  24549. * Mesh cap setting : no cap
  24550. */
  24551. get: function () {
  24552. return Mesh._NO_CAP;
  24553. },
  24554. enumerable: true,
  24555. configurable: true
  24556. });
  24557. Object.defineProperty(Mesh, "CAP_START", {
  24558. /**
  24559. * Mesh cap setting : one cap at the beginning of the mesh
  24560. */
  24561. get: function () {
  24562. return Mesh._CAP_START;
  24563. },
  24564. enumerable: true,
  24565. configurable: true
  24566. });
  24567. Object.defineProperty(Mesh, "CAP_END", {
  24568. /**
  24569. * Mesh cap setting : one cap at the end of the mesh
  24570. */
  24571. get: function () {
  24572. return Mesh._CAP_END;
  24573. },
  24574. enumerable: true,
  24575. configurable: true
  24576. });
  24577. Object.defineProperty(Mesh, "CAP_ALL", {
  24578. /**
  24579. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  24580. */
  24581. get: function () {
  24582. return Mesh._CAP_ALL;
  24583. },
  24584. enumerable: true,
  24585. configurable: true
  24586. });
  24587. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  24588. set: function (callback) {
  24589. if (this._onBeforeDrawObserver) {
  24590. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  24591. }
  24592. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  24593. },
  24594. enumerable: true,
  24595. configurable: true
  24596. });
  24597. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  24598. get: function () {
  24599. return this._morphTargetManager;
  24600. },
  24601. set: function (value) {
  24602. if (this._morphTargetManager === value) {
  24603. return;
  24604. }
  24605. this._morphTargetManager = value;
  24606. this._syncGeometryWithMorphTargetManager();
  24607. },
  24608. enumerable: true,
  24609. configurable: true
  24610. });
  24611. Object.defineProperty(Mesh.prototype, "source", {
  24612. get: function () {
  24613. return this._source;
  24614. },
  24615. enumerable: true,
  24616. configurable: true
  24617. });
  24618. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  24619. get: function () {
  24620. return this._unIndexed;
  24621. },
  24622. set: function (value) {
  24623. if (this._unIndexed !== value) {
  24624. this._unIndexed = value;
  24625. this._markSubMeshesAsAttributesDirty();
  24626. }
  24627. },
  24628. enumerable: true,
  24629. configurable: true
  24630. });
  24631. // Methods
  24632. /**
  24633. * Returns the string "Mesh".
  24634. */
  24635. Mesh.prototype.getClassName = function () {
  24636. return "Mesh";
  24637. };
  24638. /**
  24639. * Returns a string.
  24640. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  24641. */
  24642. Mesh.prototype.toString = function (fullDetails) {
  24643. var ret = _super.prototype.toString.call(this, fullDetails);
  24644. ret += ", n vertices: " + this.getTotalVertices();
  24645. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  24646. if (this.animations) {
  24647. for (var i = 0; i < this.animations.length; i++) {
  24648. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  24649. }
  24650. }
  24651. if (fullDetails) {
  24652. if (this._geometry) {
  24653. var ib = this.getIndices();
  24654. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24655. if (vb && ib) {
  24656. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  24657. }
  24658. }
  24659. else {
  24660. ret += ", flat shading: UNKNOWN";
  24661. }
  24662. }
  24663. return ret;
  24664. };
  24665. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  24666. /**
  24667. * True if the mesh has some Levels Of Details (LOD).
  24668. * Returns a boolean.
  24669. */
  24670. get: function () {
  24671. return this._LODLevels.length > 0;
  24672. },
  24673. enumerable: true,
  24674. configurable: true
  24675. });
  24676. Mesh.prototype._sortLODLevels = function () {
  24677. this._LODLevels.sort(function (a, b) {
  24678. if (a.distance < b.distance) {
  24679. return 1;
  24680. }
  24681. if (a.distance > b.distance) {
  24682. return -1;
  24683. }
  24684. return 0;
  24685. });
  24686. };
  24687. /**
  24688. * Add a mesh as LOD level triggered at the given distance.
  24689. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  24690. * @param {number} distance The distance from the center of the object to show this level
  24691. * @param {Mesh} mesh The mesh to be added as LOD level
  24692. * @return {Mesh} This mesh (for chaining)
  24693. */
  24694. Mesh.prototype.addLODLevel = function (distance, mesh) {
  24695. if (mesh && mesh._masterMesh) {
  24696. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  24697. return this;
  24698. }
  24699. var level = new BABYLON.MeshLODLevel(distance, mesh);
  24700. this._LODLevels.push(level);
  24701. if (mesh) {
  24702. mesh._masterMesh = this;
  24703. }
  24704. this._sortLODLevels();
  24705. return this;
  24706. };
  24707. /**
  24708. * Returns the LOD level mesh at the passed distance or null if not found.
  24709. * It is related to the method `addLODLevel(distance, mesh)`.
  24710. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  24711. * Returns an object Mesh or `null`.
  24712. */
  24713. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  24714. for (var index = 0; index < this._LODLevels.length; index++) {
  24715. var level = this._LODLevels[index];
  24716. if (level.distance === distance) {
  24717. return level.mesh;
  24718. }
  24719. }
  24720. return null;
  24721. };
  24722. /**
  24723. * Remove a mesh from the LOD array
  24724. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  24725. * @param {Mesh} mesh The mesh to be removed.
  24726. * @return {Mesh} This mesh (for chaining)
  24727. */
  24728. Mesh.prototype.removeLODLevel = function (mesh) {
  24729. for (var index = 0; index < this._LODLevels.length; index++) {
  24730. if (this._LODLevels[index].mesh === mesh) {
  24731. this._LODLevels.splice(index, 1);
  24732. if (mesh) {
  24733. mesh._masterMesh = null;
  24734. }
  24735. }
  24736. }
  24737. this._sortLODLevels();
  24738. return this;
  24739. };
  24740. /**
  24741. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  24742. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  24743. */
  24744. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  24745. if (!this._LODLevels || this._LODLevels.length === 0) {
  24746. return this;
  24747. }
  24748. var bSphere;
  24749. if (boundingSphere) {
  24750. bSphere = boundingSphere;
  24751. }
  24752. else {
  24753. var boundingInfo = this.getBoundingInfo();
  24754. bSphere = boundingInfo.boundingSphere;
  24755. }
  24756. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  24757. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  24758. if (this.onLODLevelSelection) {
  24759. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  24760. }
  24761. return this;
  24762. }
  24763. for (var index = 0; index < this._LODLevels.length; index++) {
  24764. var level = this._LODLevels[index];
  24765. if (level.distance < distanceToCamera) {
  24766. if (level.mesh) {
  24767. level.mesh._preActivate();
  24768. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  24769. }
  24770. if (this.onLODLevelSelection) {
  24771. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  24772. }
  24773. return level.mesh;
  24774. }
  24775. }
  24776. if (this.onLODLevelSelection) {
  24777. this.onLODLevelSelection(distanceToCamera, this, this);
  24778. }
  24779. return this;
  24780. };
  24781. Object.defineProperty(Mesh.prototype, "geometry", {
  24782. /**
  24783. * Returns the mesh internal Geometry object.
  24784. */
  24785. get: function () {
  24786. return this._geometry;
  24787. },
  24788. enumerable: true,
  24789. configurable: true
  24790. });
  24791. /**
  24792. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  24793. */
  24794. Mesh.prototype.getTotalVertices = function () {
  24795. if (this._geometry === null || this._geometry === undefined) {
  24796. return 0;
  24797. }
  24798. return this._geometry.getTotalVertices();
  24799. };
  24800. /**
  24801. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  24802. * 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.
  24803. * You can force the copy with forceCopy === true
  24804. * Returns null if the mesh has no geometry or no vertex buffer.
  24805. * Possible `kind` values :
  24806. * - BABYLON.VertexBuffer.PositionKind
  24807. * - BABYLON.VertexBuffer.UVKind
  24808. * - BABYLON.VertexBuffer.UV2Kind
  24809. * - BABYLON.VertexBuffer.UV3Kind
  24810. * - BABYLON.VertexBuffer.UV4Kind
  24811. * - BABYLON.VertexBuffer.UV5Kind
  24812. * - BABYLON.VertexBuffer.UV6Kind
  24813. * - BABYLON.VertexBuffer.ColorKind
  24814. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24815. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24816. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24817. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24818. */
  24819. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  24820. if (!this._geometry) {
  24821. return null;
  24822. }
  24823. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  24824. };
  24825. /**
  24826. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  24827. * Returns `null` if the mesh has no geometry.
  24828. * Possible `kind` values :
  24829. * - BABYLON.VertexBuffer.PositionKind
  24830. * - BABYLON.VertexBuffer.UVKind
  24831. * - BABYLON.VertexBuffer.UV2Kind
  24832. * - BABYLON.VertexBuffer.UV3Kind
  24833. * - BABYLON.VertexBuffer.UV4Kind
  24834. * - BABYLON.VertexBuffer.UV5Kind
  24835. * - BABYLON.VertexBuffer.UV6Kind
  24836. * - BABYLON.VertexBuffer.ColorKind
  24837. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24838. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24839. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24840. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24841. */
  24842. Mesh.prototype.getVertexBuffer = function (kind) {
  24843. if (!this._geometry) {
  24844. return null;
  24845. }
  24846. return this._geometry.getVertexBuffer(kind);
  24847. };
  24848. /**
  24849. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  24850. * Possible `kind` values :
  24851. * - BABYLON.VertexBuffer.PositionKind
  24852. * - BABYLON.VertexBuffer.UVKind
  24853. * - BABYLON.VertexBuffer.UV2Kind
  24854. * - BABYLON.VertexBuffer.UV3Kind
  24855. * - BABYLON.VertexBuffer.UV4Kind
  24856. * - BABYLON.VertexBuffer.UV5Kind
  24857. * - BABYLON.VertexBuffer.UV6Kind
  24858. * - BABYLON.VertexBuffer.ColorKind
  24859. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24860. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24861. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24862. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24863. */
  24864. Mesh.prototype.isVerticesDataPresent = function (kind) {
  24865. if (!this._geometry) {
  24866. if (this._delayInfo) {
  24867. return this._delayInfo.indexOf(kind) !== -1;
  24868. }
  24869. return false;
  24870. }
  24871. return this._geometry.isVerticesDataPresent(kind);
  24872. };
  24873. /**
  24874. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  24875. * Possible `kind` values :
  24876. * - BABYLON.VertexBuffer.PositionKind
  24877. * - BABYLON.VertexBuffer.UVKind
  24878. * - BABYLON.VertexBuffer.UV2Kind
  24879. * - BABYLON.VertexBuffer.UV3Kind
  24880. * - BABYLON.VertexBuffer.UV4Kind
  24881. * - BABYLON.VertexBuffer.UV5Kind
  24882. * - BABYLON.VertexBuffer.UV6Kind
  24883. * - BABYLON.VertexBuffer.ColorKind
  24884. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24885. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24886. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24887. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24888. */
  24889. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  24890. if (!this._geometry) {
  24891. if (this._delayInfo) {
  24892. return this._delayInfo.indexOf(kind) !== -1;
  24893. }
  24894. return false;
  24895. }
  24896. return this._geometry.isVertexBufferUpdatable(kind);
  24897. };
  24898. /**
  24899. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  24900. * Possible `kind` values :
  24901. * - BABYLON.VertexBuffer.PositionKind
  24902. * - BABYLON.VertexBuffer.UVKind
  24903. * - BABYLON.VertexBuffer.UV2Kind
  24904. * - BABYLON.VertexBuffer.UV3Kind
  24905. * - BABYLON.VertexBuffer.UV4Kind
  24906. * - BABYLON.VertexBuffer.UV5Kind
  24907. * - BABYLON.VertexBuffer.UV6Kind
  24908. * - BABYLON.VertexBuffer.ColorKind
  24909. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24910. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24911. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24912. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24913. */
  24914. Mesh.prototype.getVerticesDataKinds = function () {
  24915. if (!this._geometry) {
  24916. var result = new Array();
  24917. if (this._delayInfo) {
  24918. this._delayInfo.forEach(function (kind, index, array) {
  24919. result.push(kind);
  24920. });
  24921. }
  24922. return result;
  24923. }
  24924. return this._geometry.getVerticesDataKinds();
  24925. };
  24926. /**
  24927. * Returns a positive integer : the total number of indices in this mesh geometry.
  24928. * Returns zero if the mesh has no geometry.
  24929. */
  24930. Mesh.prototype.getTotalIndices = function () {
  24931. if (!this._geometry) {
  24932. return 0;
  24933. }
  24934. return this._geometry.getTotalIndices();
  24935. };
  24936. /**
  24937. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  24938. * 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.
  24939. * Returns an empty array if the mesh has no geometry.
  24940. */
  24941. Mesh.prototype.getIndices = function (copyWhenShared) {
  24942. if (!this._geometry) {
  24943. return [];
  24944. }
  24945. return this._geometry.getIndices(copyWhenShared);
  24946. };
  24947. Object.defineProperty(Mesh.prototype, "isBlocked", {
  24948. get: function () {
  24949. return this._masterMesh !== null && this._masterMesh !== undefined;
  24950. },
  24951. enumerable: true,
  24952. configurable: true
  24953. });
  24954. /**
  24955. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  24956. */
  24957. Mesh.prototype.isReady = function () {
  24958. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24959. return false;
  24960. }
  24961. return _super.prototype.isReady.call(this);
  24962. };
  24963. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  24964. /**
  24965. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  24966. * This property is pertinent only for updatable parametric shapes.
  24967. */
  24968. get: function () {
  24969. return this._areNormalsFrozen;
  24970. },
  24971. enumerable: true,
  24972. configurable: true
  24973. });
  24974. /**
  24975. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  24976. * It has no effect at all on other shapes.
  24977. * It prevents the mesh normals from being recomputed on next `positions` array update.
  24978. * Returns the Mesh.
  24979. */
  24980. Mesh.prototype.freezeNormals = function () {
  24981. this._areNormalsFrozen = true;
  24982. return this;
  24983. };
  24984. /**
  24985. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  24986. * It has no effect at all on other shapes.
  24987. * It reactivates the mesh normals computation if it was previously frozen.
  24988. * Returns the Mesh.
  24989. */
  24990. Mesh.prototype.unfreezeNormals = function () {
  24991. this._areNormalsFrozen = false;
  24992. return this;
  24993. };
  24994. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  24995. /**
  24996. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  24997. */
  24998. set: function (count) {
  24999. this._overridenInstanceCount = count;
  25000. },
  25001. enumerable: true,
  25002. configurable: true
  25003. });
  25004. // Methods
  25005. Mesh.prototype._preActivate = function () {
  25006. var sceneRenderId = this.getScene().getRenderId();
  25007. if (this._preActivateId === sceneRenderId) {
  25008. return this;
  25009. }
  25010. this._preActivateId = sceneRenderId;
  25011. this._visibleInstances = null;
  25012. return this;
  25013. };
  25014. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  25015. if (this._visibleInstances) {
  25016. this._visibleInstances.intermediateDefaultRenderId = renderId;
  25017. }
  25018. return this;
  25019. };
  25020. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  25021. if (!this._visibleInstances) {
  25022. this._visibleInstances = {};
  25023. this._visibleInstances.defaultRenderId = renderId;
  25024. this._visibleInstances.selfDefaultRenderId = this._renderId;
  25025. }
  25026. if (!this._visibleInstances[renderId]) {
  25027. this._visibleInstances[renderId] = new Array();
  25028. }
  25029. this._visibleInstances[renderId].push(instance);
  25030. return this;
  25031. };
  25032. /**
  25033. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  25034. * This means the mesh underlying bounding box and sphere are recomputed.
  25035. * Returns the Mesh.
  25036. */
  25037. Mesh.prototype.refreshBoundingInfo = function () {
  25038. return this._refreshBoundingInfo(false);
  25039. };
  25040. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  25041. if (this._boundingInfo && this._boundingInfo.isLocked) {
  25042. return this;
  25043. }
  25044. var data = this._getPositionData(applySkeleton);
  25045. if (data) {
  25046. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  25047. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25048. }
  25049. if (this.subMeshes) {
  25050. for (var index = 0; index < this.subMeshes.length; index++) {
  25051. this.subMeshes[index].refreshBoundingInfo();
  25052. }
  25053. }
  25054. this._updateBoundingInfo();
  25055. return this;
  25056. };
  25057. Mesh.prototype._getPositionData = function (applySkeleton) {
  25058. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25059. if (data && applySkeleton && this.skeleton) {
  25060. data = data.slice();
  25061. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25062. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25063. if (matricesWeightsData && matricesIndicesData) {
  25064. var needExtras = this.numBoneInfluencers > 4;
  25065. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25066. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25067. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  25068. var tempVector = BABYLON.Tmp.Vector3[0];
  25069. var finalMatrix = BABYLON.Tmp.Matrix[0];
  25070. var tempMatrix = BABYLON.Tmp.Matrix[1];
  25071. var matWeightIdx = 0;
  25072. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  25073. finalMatrix.reset();
  25074. var inf;
  25075. var weight;
  25076. for (inf = 0; inf < 4; inf++) {
  25077. weight = matricesWeightsData[matWeightIdx + inf];
  25078. if (weight <= 0)
  25079. break;
  25080. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25081. finalMatrix.addToSelf(tempMatrix);
  25082. }
  25083. if (needExtras) {
  25084. for (inf = 0; inf < 4; inf++) {
  25085. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25086. if (weight <= 0)
  25087. break;
  25088. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25089. finalMatrix.addToSelf(tempMatrix);
  25090. }
  25091. }
  25092. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  25093. tempVector.toArray(data, index);
  25094. }
  25095. }
  25096. }
  25097. return data;
  25098. };
  25099. Mesh.prototype._createGlobalSubMesh = function (force) {
  25100. var totalVertices = this.getTotalVertices();
  25101. if (!totalVertices || !this.getIndices()) {
  25102. return null;
  25103. }
  25104. // Check if we need to recreate the submeshes
  25105. if (this.subMeshes && this.subMeshes.length > 0) {
  25106. var ib = this.getIndices();
  25107. if (!ib) {
  25108. return null;
  25109. }
  25110. var totalIndices = ib.length;
  25111. var needToRecreate = false;
  25112. if (force) {
  25113. needToRecreate = true;
  25114. }
  25115. else {
  25116. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  25117. var submesh = _a[_i];
  25118. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  25119. needToRecreate = true;
  25120. break;
  25121. }
  25122. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  25123. needToRecreate = true;
  25124. break;
  25125. }
  25126. }
  25127. }
  25128. if (!needToRecreate) {
  25129. return this.subMeshes[0];
  25130. }
  25131. }
  25132. this.releaseSubMeshes();
  25133. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  25134. };
  25135. Mesh.prototype.subdivide = function (count) {
  25136. if (count < 1) {
  25137. return;
  25138. }
  25139. var totalIndices = this.getTotalIndices();
  25140. var subdivisionSize = (totalIndices / count) | 0;
  25141. var offset = 0;
  25142. // Ensure that subdivisionSize is a multiple of 3
  25143. while (subdivisionSize % 3 !== 0) {
  25144. subdivisionSize++;
  25145. }
  25146. this.releaseSubMeshes();
  25147. for (var index = 0; index < count; index++) {
  25148. if (offset >= totalIndices) {
  25149. break;
  25150. }
  25151. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  25152. offset += subdivisionSize;
  25153. }
  25154. this.synchronizeInstances();
  25155. };
  25156. /**
  25157. * Sets the vertex data of the mesh geometry for the requested `kind`.
  25158. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  25159. * The `data` are either a numeric array either a Float32Array.
  25160. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  25161. * 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).
  25162. * Note that a new underlying VertexBuffer object is created each call.
  25163. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  25164. *
  25165. * Possible `kind` values :
  25166. * - BABYLON.VertexBuffer.PositionKind
  25167. * - BABYLON.VertexBuffer.UVKind
  25168. * - BABYLON.VertexBuffer.UV2Kind
  25169. * - BABYLON.VertexBuffer.UV3Kind
  25170. * - BABYLON.VertexBuffer.UV4Kind
  25171. * - BABYLON.VertexBuffer.UV5Kind
  25172. * - BABYLON.VertexBuffer.UV6Kind
  25173. * - BABYLON.VertexBuffer.ColorKind
  25174. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25175. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25176. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25177. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25178. *
  25179. * Returns the Mesh.
  25180. */
  25181. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25182. if (updatable === void 0) { updatable = false; }
  25183. if (!this._geometry) {
  25184. var vertexData = new BABYLON.VertexData();
  25185. vertexData.set(data, kind);
  25186. var scene = this.getScene();
  25187. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  25188. }
  25189. else {
  25190. this._geometry.setVerticesData(kind, data, updatable, stride);
  25191. }
  25192. return this;
  25193. };
  25194. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  25195. if (updatable === void 0) { updatable = true; }
  25196. var vb = this.getVertexBuffer(kind);
  25197. if (!vb || vb.isUpdatable() === updatable) {
  25198. return;
  25199. }
  25200. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  25201. };
  25202. /**
  25203. * Sets the mesh VertexBuffer.
  25204. * Returns the Mesh.
  25205. */
  25206. Mesh.prototype.setVerticesBuffer = function (buffer) {
  25207. if (!this._geometry) {
  25208. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  25209. }
  25210. this._geometry.setVerticesBuffer(buffer);
  25211. return this;
  25212. };
  25213. /**
  25214. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  25215. * If the mesh has no geometry, it is simply returned as it is.
  25216. * The `data` are either a numeric array either a Float32Array.
  25217. * No new underlying VertexBuffer object is created.
  25218. * 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.
  25219. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  25220. *
  25221. * Possible `kind` values :
  25222. * - BABYLON.VertexBuffer.PositionKind
  25223. * - BABYLON.VertexBuffer.UVKind
  25224. * - BABYLON.VertexBuffer.UV2Kind
  25225. * - BABYLON.VertexBuffer.UV3Kind
  25226. * - BABYLON.VertexBuffer.UV4Kind
  25227. * - BABYLON.VertexBuffer.UV5Kind
  25228. * - BABYLON.VertexBuffer.UV6Kind
  25229. * - BABYLON.VertexBuffer.ColorKind
  25230. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25231. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25232. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25233. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25234. *
  25235. * Returns the Mesh.
  25236. */
  25237. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  25238. if (!this._geometry) {
  25239. return this;
  25240. }
  25241. if (!makeItUnique) {
  25242. this._geometry.updateVerticesData(kind, data, updateExtends);
  25243. }
  25244. else {
  25245. this.makeGeometryUnique();
  25246. this.updateVerticesData(kind, data, updateExtends, false);
  25247. }
  25248. return this;
  25249. };
  25250. /**
  25251. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  25252. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  25253. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  25254. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  25255. * Returns the Mesh.
  25256. */
  25257. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  25258. if (computeNormals === void 0) { computeNormals = true; }
  25259. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25260. if (!positions) {
  25261. return this;
  25262. }
  25263. positionFunction(positions);
  25264. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  25265. if (computeNormals) {
  25266. var indices = this.getIndices();
  25267. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25268. if (!normals) {
  25269. return this;
  25270. }
  25271. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  25272. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  25273. }
  25274. return this;
  25275. };
  25276. /**
  25277. * Creates a un-shared specific occurence of the geometry for the mesh.
  25278. * Returns the Mesh.
  25279. */
  25280. Mesh.prototype.makeGeometryUnique = function () {
  25281. if (!this._geometry) {
  25282. return this;
  25283. }
  25284. var oldGeometry = this._geometry;
  25285. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  25286. oldGeometry.releaseForMesh(this, true);
  25287. geometry.applyToMesh(this);
  25288. return this;
  25289. };
  25290. /**
  25291. * Sets the mesh indices.
  25292. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  25293. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  25294. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  25295. * This method creates a new index buffer each call.
  25296. * Returns the Mesh.
  25297. */
  25298. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  25299. if (totalVertices === void 0) { totalVertices = null; }
  25300. if (updatable === void 0) { updatable = false; }
  25301. if (!this._geometry) {
  25302. var vertexData = new BABYLON.VertexData();
  25303. vertexData.indices = indices;
  25304. var scene = this.getScene();
  25305. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  25306. }
  25307. else {
  25308. this._geometry.setIndices(indices, totalVertices, updatable);
  25309. }
  25310. return this;
  25311. };
  25312. /**
  25313. * Update the current index buffer
  25314. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  25315. * Returns the Mesh.
  25316. */
  25317. Mesh.prototype.updateIndices = function (indices, offset) {
  25318. if (!this._geometry) {
  25319. return this;
  25320. }
  25321. this._geometry.updateIndices(indices, offset);
  25322. return this;
  25323. };
  25324. /**
  25325. * Invert the geometry to move from a right handed system to a left handed one.
  25326. * Returns the Mesh.
  25327. */
  25328. Mesh.prototype.toLeftHanded = function () {
  25329. if (!this._geometry) {
  25330. return this;
  25331. }
  25332. this._geometry.toLeftHanded();
  25333. return this;
  25334. };
  25335. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  25336. if (!this._geometry) {
  25337. return this;
  25338. }
  25339. var engine = this.getScene().getEngine();
  25340. // Wireframe
  25341. var indexToBind;
  25342. if (this._unIndexed) {
  25343. indexToBind = null;
  25344. }
  25345. else {
  25346. switch (fillMode) {
  25347. case BABYLON.Material.PointFillMode:
  25348. indexToBind = null;
  25349. break;
  25350. case BABYLON.Material.WireFrameFillMode:
  25351. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  25352. break;
  25353. default:
  25354. case BABYLON.Material.TriangleFillMode:
  25355. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  25356. break;
  25357. }
  25358. }
  25359. // VBOs
  25360. this._geometry._bind(effect, indexToBind);
  25361. return this;
  25362. };
  25363. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  25364. if (alternate === void 0) { alternate = false; }
  25365. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  25366. return this;
  25367. }
  25368. this.onBeforeDrawObservable.notifyObservers(this);
  25369. var scene = this.getScene();
  25370. var engine = scene.getEngine();
  25371. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  25372. // or triangles as points
  25373. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  25374. }
  25375. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  25376. // Triangles as wireframe
  25377. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  25378. }
  25379. else {
  25380. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  25381. }
  25382. if (scene._isAlternateRenderingEnabled && !alternate) {
  25383. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  25384. if (!effect || !scene.activeCamera) {
  25385. return this;
  25386. }
  25387. scene._switchToAlternateCameraConfiguration(true);
  25388. this._effectiveMaterial.bindView(effect);
  25389. this._effectiveMaterial.bindViewProjection(effect);
  25390. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  25391. this._draw(subMesh, fillMode, instancesCount, true);
  25392. engine.setViewport(scene.activeCamera.viewport);
  25393. scene._switchToAlternateCameraConfiguration(false);
  25394. this._effectiveMaterial.bindView(effect);
  25395. this._effectiveMaterial.bindViewProjection(effect);
  25396. }
  25397. return this;
  25398. };
  25399. /**
  25400. * Registers for this mesh a javascript function called just before the rendering process.
  25401. * This function is passed the current mesh.
  25402. * Return the Mesh.
  25403. */
  25404. Mesh.prototype.registerBeforeRender = function (func) {
  25405. this.onBeforeRenderObservable.add(func);
  25406. return this;
  25407. };
  25408. /**
  25409. * Disposes a previously registered javascript function called before the rendering.
  25410. * This function is passed the current mesh.
  25411. * Returns the Mesh.
  25412. */
  25413. Mesh.prototype.unregisterBeforeRender = function (func) {
  25414. this.onBeforeRenderObservable.removeCallback(func);
  25415. return this;
  25416. };
  25417. /**
  25418. * Registers for this mesh a javascript function called just after the rendering is complete.
  25419. * This function is passed the current mesh.
  25420. * Returns the Mesh.
  25421. */
  25422. Mesh.prototype.registerAfterRender = function (func) {
  25423. this.onAfterRenderObservable.add(func);
  25424. return this;
  25425. };
  25426. /**
  25427. * Disposes a previously registered javascript function called after the rendering.
  25428. * This function is passed the current mesh.
  25429. * Return the Mesh.
  25430. */
  25431. Mesh.prototype.unregisterAfterRender = function (func) {
  25432. this.onAfterRenderObservable.removeCallback(func);
  25433. return this;
  25434. };
  25435. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  25436. var scene = this.getScene();
  25437. this._batchCache.mustReturn = false;
  25438. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  25439. this._batchCache.visibleInstances[subMeshId] = null;
  25440. if (this._visibleInstances) {
  25441. var currentRenderId = scene.getRenderId();
  25442. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  25443. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  25444. var selfRenderId = this._renderId;
  25445. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  25446. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  25447. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  25448. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  25449. }
  25450. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  25451. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  25452. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  25453. this._batchCache.mustReturn = true;
  25454. return this._batchCache;
  25455. }
  25456. if (currentRenderId !== selfRenderId) {
  25457. this._batchCache.renderSelf[subMeshId] = false;
  25458. }
  25459. }
  25460. this._renderIdForInstances[subMeshId] = currentRenderId;
  25461. }
  25462. return this._batchCache;
  25463. };
  25464. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  25465. var visibleInstances = batch.visibleInstances[subMesh._id];
  25466. if (!visibleInstances) {
  25467. return this;
  25468. }
  25469. var matricesCount = visibleInstances.length + 1;
  25470. var bufferSize = matricesCount * 16 * 4;
  25471. var currentInstancesBufferSize = this._instancesBufferSize;
  25472. var instancesBuffer = this._instancesBuffer;
  25473. while (this._instancesBufferSize < bufferSize) {
  25474. this._instancesBufferSize *= 2;
  25475. }
  25476. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  25477. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  25478. }
  25479. var offset = 0;
  25480. var instancesCount = 0;
  25481. var world = this.getWorldMatrix();
  25482. if (batch.renderSelf[subMesh._id]) {
  25483. world.copyToArray(this._instancesData, offset);
  25484. offset += 16;
  25485. instancesCount++;
  25486. }
  25487. if (visibleInstances) {
  25488. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  25489. var instance = visibleInstances[instanceIndex];
  25490. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  25491. offset += 16;
  25492. instancesCount++;
  25493. }
  25494. }
  25495. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  25496. if (instancesBuffer) {
  25497. instancesBuffer.dispose();
  25498. }
  25499. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  25500. this._instancesBuffer = instancesBuffer;
  25501. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  25502. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  25503. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  25504. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  25505. }
  25506. else {
  25507. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  25508. }
  25509. this._bind(subMesh, effect, fillMode);
  25510. this._draw(subMesh, fillMode, instancesCount);
  25511. engine.unbindInstanceAttributes();
  25512. return this;
  25513. };
  25514. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  25515. var scene = this.getScene();
  25516. var engine = scene.getEngine();
  25517. if (hardwareInstancedRendering) {
  25518. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  25519. }
  25520. else {
  25521. if (batch.renderSelf[subMesh._id]) {
  25522. // Draw
  25523. if (onBeforeDraw) {
  25524. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  25525. }
  25526. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  25527. }
  25528. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  25529. if (visibleInstancesForSubMesh) {
  25530. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  25531. var instance = visibleInstancesForSubMesh[instanceIndex];
  25532. // World
  25533. var world = instance.getWorldMatrix();
  25534. if (onBeforeDraw) {
  25535. onBeforeDraw(true, world, effectiveMaterial);
  25536. }
  25537. // Draw
  25538. this._draw(subMesh, fillMode);
  25539. }
  25540. }
  25541. }
  25542. return this;
  25543. };
  25544. /**
  25545. * Triggers the draw call for the mesh.
  25546. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  25547. * Returns the Mesh.
  25548. */
  25549. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  25550. this.checkOcclusionQuery();
  25551. if (this._isOccluded) {
  25552. return this;
  25553. }
  25554. var scene = this.getScene();
  25555. // Managing instances
  25556. var batch = this._getInstancesRenderList(subMesh._id);
  25557. if (batch.mustReturn) {
  25558. return this;
  25559. }
  25560. // Checking geometry state
  25561. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  25562. return this;
  25563. }
  25564. this.onBeforeRenderObservable.notifyObservers(this);
  25565. var engine = scene.getEngine();
  25566. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  25567. // Material
  25568. var material = subMesh.getMaterial();
  25569. if (!material) {
  25570. return this;
  25571. }
  25572. this._effectiveMaterial = material;
  25573. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  25574. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  25575. return this;
  25576. }
  25577. }
  25578. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  25579. return this;
  25580. }
  25581. // Alpha mode
  25582. if (enableAlphaMode) {
  25583. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  25584. }
  25585. // Outline - step 1
  25586. var savedDepthWrite = engine.getDepthWrite();
  25587. if (this.renderOutline) {
  25588. engine.setDepthWrite(false);
  25589. scene.getOutlineRenderer().render(subMesh, batch);
  25590. engine.setDepthWrite(savedDepthWrite);
  25591. }
  25592. var effect;
  25593. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  25594. effect = subMesh.effect;
  25595. }
  25596. else {
  25597. effect = this._effectiveMaterial.getEffect();
  25598. }
  25599. if (!effect) {
  25600. return this;
  25601. }
  25602. var sideOrientation = this.overrideMaterialSideOrientation;
  25603. if (sideOrientation == null) {
  25604. sideOrientation = this._effectiveMaterial.sideOrientation;
  25605. if (this._getWorldMatrixDeterminant() < 0) {
  25606. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  25607. }
  25608. }
  25609. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  25610. if (this._effectiveMaterial.forceDepthWrite) {
  25611. engine.setDepthWrite(true);
  25612. }
  25613. // Bind
  25614. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  25615. if (!hardwareInstancedRendering) {
  25616. this._bind(subMesh, effect, fillMode);
  25617. }
  25618. var world = this.getWorldMatrix();
  25619. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  25620. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  25621. }
  25622. else {
  25623. this._effectiveMaterial.bind(world, this);
  25624. }
  25625. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  25626. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  25627. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  25628. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  25629. }
  25630. // Draw
  25631. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  25632. // Unbind
  25633. this._effectiveMaterial.unbind();
  25634. // Outline - step 2
  25635. if (this.renderOutline && savedDepthWrite) {
  25636. engine.setDepthWrite(true);
  25637. engine.setColorWrite(false);
  25638. scene.getOutlineRenderer().render(subMesh, batch);
  25639. engine.setColorWrite(true);
  25640. }
  25641. // Overlay
  25642. if (this.renderOverlay) {
  25643. var currentMode = engine.getAlphaMode();
  25644. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  25645. scene.getOutlineRenderer().render(subMesh, batch, true);
  25646. engine.setAlphaMode(currentMode);
  25647. }
  25648. this.onAfterRenderObservable.notifyObservers(this);
  25649. return this;
  25650. };
  25651. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  25652. if (isInstance && effectiveMaterial) {
  25653. effectiveMaterial.bindOnlyWorldMatrix(world);
  25654. }
  25655. };
  25656. /**
  25657. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  25658. */
  25659. Mesh.prototype.getEmittedParticleSystems = function () {
  25660. var results = new Array();
  25661. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  25662. var particleSystem = this.getScene().particleSystems[index];
  25663. if (particleSystem.emitter === this) {
  25664. results.push(particleSystem);
  25665. }
  25666. }
  25667. return results;
  25668. };
  25669. /**
  25670. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  25671. */
  25672. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  25673. var results = new Array();
  25674. var descendants = this.getDescendants();
  25675. descendants.push(this);
  25676. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  25677. var particleSystem = this.getScene().particleSystems[index];
  25678. var emitter = particleSystem.emitter;
  25679. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  25680. results.push(particleSystem);
  25681. }
  25682. }
  25683. return results;
  25684. };
  25685. Mesh.prototype._checkDelayState = function () {
  25686. var scene = this.getScene();
  25687. if (this._geometry) {
  25688. this._geometry.load(scene);
  25689. }
  25690. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  25691. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  25692. this._queueLoad(scene);
  25693. }
  25694. return this;
  25695. };
  25696. Mesh.prototype._queueLoad = function (scene) {
  25697. var _this = this;
  25698. scene._addPendingData(this);
  25699. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  25700. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  25701. if (data instanceof ArrayBuffer) {
  25702. _this._delayLoadingFunction(data, _this);
  25703. }
  25704. else {
  25705. _this._delayLoadingFunction(JSON.parse(data), _this);
  25706. }
  25707. _this.instances.forEach(function (instance) {
  25708. instance._syncSubMeshes();
  25709. });
  25710. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  25711. scene._removePendingData(_this);
  25712. }, function () { }, scene.database, getBinaryData);
  25713. return this;
  25714. };
  25715. /**
  25716. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  25717. */
  25718. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  25719. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25720. return false;
  25721. }
  25722. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  25723. return false;
  25724. }
  25725. this._checkDelayState();
  25726. return true;
  25727. };
  25728. /**
  25729. * Sets the mesh material by the material or multiMaterial `id` property.
  25730. * The material `id` is a string identifying the material or the multiMaterial.
  25731. * This method returns the Mesh.
  25732. */
  25733. Mesh.prototype.setMaterialByID = function (id) {
  25734. var materials = this.getScene().materials;
  25735. var index;
  25736. for (index = materials.length - 1; index > -1; index--) {
  25737. if (materials[index].id === id) {
  25738. this.material = materials[index];
  25739. return this;
  25740. }
  25741. }
  25742. // Multi
  25743. var multiMaterials = this.getScene().multiMaterials;
  25744. for (index = multiMaterials.length - 1; index > -1; index--) {
  25745. if (multiMaterials[index].id === id) {
  25746. this.material = multiMaterials[index];
  25747. return this;
  25748. }
  25749. }
  25750. return this;
  25751. };
  25752. /**
  25753. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  25754. */
  25755. Mesh.prototype.getAnimatables = function () {
  25756. var results = new Array();
  25757. if (this.material) {
  25758. results.push(this.material);
  25759. }
  25760. if (this.skeleton) {
  25761. results.push(this.skeleton);
  25762. }
  25763. return results;
  25764. };
  25765. /**
  25766. * Modifies the mesh geometry according to the passed transformation matrix.
  25767. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  25768. * The mesh normals are modified accordingly the same transformation.
  25769. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  25770. * Note that, under the hood, this method sets a new VertexBuffer each call.
  25771. * Returns the Mesh.
  25772. */
  25773. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  25774. // Position
  25775. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25776. return this;
  25777. }
  25778. var submeshes = this.subMeshes.splice(0);
  25779. this._resetPointsArrayCache();
  25780. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25781. var temp = new Array();
  25782. var index;
  25783. for (index = 0; index < data.length; index += 3) {
  25784. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  25785. }
  25786. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  25787. // Normals
  25788. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25789. return this;
  25790. }
  25791. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25792. temp = [];
  25793. for (index = 0; index < data.length; index += 3) {
  25794. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  25795. }
  25796. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  25797. // flip faces?
  25798. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  25799. this.flipFaces();
  25800. }
  25801. // Restore submeshes
  25802. this.releaseSubMeshes();
  25803. this.subMeshes = submeshes;
  25804. return this;
  25805. };
  25806. /**
  25807. * Modifies the mesh geometry according to its own current World Matrix.
  25808. * The mesh World Matrix is then reset.
  25809. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  25810. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  25811. * Note that, under the hood, this method sets a new VertexBuffer each call.
  25812. * Returns the Mesh.
  25813. */
  25814. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  25815. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  25816. this.scaling.copyFromFloats(1, 1, 1);
  25817. this.position.copyFromFloats(0, 0, 0);
  25818. this.rotation.copyFromFloats(0, 0, 0);
  25819. //only if quaternion is already set
  25820. if (this.rotationQuaternion) {
  25821. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  25822. }
  25823. this._worldMatrix = BABYLON.Matrix.Identity();
  25824. return this;
  25825. };
  25826. Object.defineProperty(Mesh.prototype, "_positions", {
  25827. // Cache
  25828. get: function () {
  25829. if (this._geometry) {
  25830. return this._geometry._positions;
  25831. }
  25832. return null;
  25833. },
  25834. enumerable: true,
  25835. configurable: true
  25836. });
  25837. Mesh.prototype._resetPointsArrayCache = function () {
  25838. if (this._geometry) {
  25839. this._geometry._resetPointsArrayCache();
  25840. }
  25841. return this;
  25842. };
  25843. Mesh.prototype._generatePointsArray = function () {
  25844. if (this._geometry) {
  25845. return this._geometry._generatePointsArray();
  25846. }
  25847. return false;
  25848. };
  25849. /**
  25850. * Returns a new Mesh object generated from the current mesh properties.
  25851. * This method must not get confused with createInstance().
  25852. * The parameter `name` is a string, the name given to the new mesh.
  25853. * The optional parameter `newParent` can be any Node object (default `null`).
  25854. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  25855. * 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.
  25856. */
  25857. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  25858. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  25859. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  25860. };
  25861. /**
  25862. * Disposes the Mesh.
  25863. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  25864. * Returns nothing.
  25865. */
  25866. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  25867. var _this = this;
  25868. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  25869. this.morphTargetManager = null;
  25870. if (this._geometry) {
  25871. this._geometry.releaseForMesh(this, true);
  25872. }
  25873. // Sources
  25874. var meshes = this.getScene().meshes;
  25875. meshes.forEach(function (abstractMesh) {
  25876. var mesh = abstractMesh;
  25877. if (mesh._source && mesh._source === _this) {
  25878. mesh._source = null;
  25879. }
  25880. });
  25881. this._source = null;
  25882. // Instances
  25883. if (this._instancesBuffer) {
  25884. this._instancesBuffer.dispose();
  25885. this._instancesBuffer = null;
  25886. }
  25887. while (this.instances.length) {
  25888. this.instances[0].dispose();
  25889. }
  25890. // Highlight layers.
  25891. var highlightLayers = this.getScene().highlightLayers;
  25892. for (var i = 0; i < highlightLayers.length; i++) {
  25893. var highlightLayer = highlightLayers[i];
  25894. if (highlightLayer) {
  25895. highlightLayer.removeMesh(this);
  25896. highlightLayer.removeExcludedMesh(this);
  25897. }
  25898. }
  25899. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  25900. };
  25901. /**
  25902. * Modifies the mesh geometry according to a displacement map.
  25903. * 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.
  25904. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  25905. * This method returns nothing.
  25906. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  25907. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  25908. * 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.
  25909. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  25910. * The parameter `uvScale` is an optional vector2 used to scale UV.
  25911. *
  25912. * Returns the Mesh.
  25913. */
  25914. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  25915. var _this = this;
  25916. var scene = this.getScene();
  25917. var onload = function (img) {
  25918. // Getting height map data
  25919. var canvas = document.createElement("canvas");
  25920. var context = canvas.getContext("2d");
  25921. var heightMapWidth = img.width;
  25922. var heightMapHeight = img.height;
  25923. canvas.width = heightMapWidth;
  25924. canvas.height = heightMapHeight;
  25925. context.drawImage(img, 0, 0);
  25926. // Create VertexData from map data
  25927. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  25928. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  25929. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  25930. //execute success callback, if set
  25931. if (onSuccess) {
  25932. onSuccess(_this);
  25933. }
  25934. };
  25935. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  25936. return this;
  25937. };
  25938. /**
  25939. * Modifies the mesh geometry according to a displacementMap buffer.
  25940. * 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.
  25941. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  25942. * This method returns nothing.
  25943. * 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.
  25944. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  25945. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  25946. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  25947. * The parameter `uvScale` is an optional vector2 used to scale UV.
  25948. *
  25949. * Returns the Mesh.
  25950. */
  25951. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  25952. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  25953. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  25954. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25955. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  25956. return this;
  25957. }
  25958. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25959. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25960. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  25961. var position = BABYLON.Vector3.Zero();
  25962. var normal = BABYLON.Vector3.Zero();
  25963. var uv = BABYLON.Vector2.Zero();
  25964. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  25965. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  25966. for (var index = 0; index < positions.length; index += 3) {
  25967. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  25968. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  25969. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  25970. // Compute height
  25971. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  25972. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  25973. var pos = (u + v * heightMapWidth) * 4;
  25974. var r = buffer[pos] / 255.0;
  25975. var g = buffer[pos + 1] / 255.0;
  25976. var b = buffer[pos + 2] / 255.0;
  25977. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  25978. normal.normalize();
  25979. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  25980. position = position.add(normal);
  25981. position.toArray(positions, index);
  25982. }
  25983. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  25984. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  25985. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  25986. return this;
  25987. };
  25988. /**
  25989. * Modify the mesh to get a flat shading rendering.
  25990. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  25991. * This method returns the Mesh.
  25992. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  25993. */
  25994. Mesh.prototype.convertToFlatShadedMesh = function () {
  25995. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  25996. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  25997. var kinds = this.getVerticesDataKinds();
  25998. var vbs = {};
  25999. var data = {};
  26000. var newdata = {};
  26001. var updatableNormals = false;
  26002. var kindIndex;
  26003. var kind;
  26004. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26005. kind = kinds[kindIndex];
  26006. var vertexBuffer = this.getVertexBuffer(kind);
  26007. if (kind === BABYLON.VertexBuffer.NormalKind) {
  26008. updatableNormals = vertexBuffer.isUpdatable();
  26009. kinds.splice(kindIndex, 1);
  26010. kindIndex--;
  26011. continue;
  26012. }
  26013. vbs[kind] = vertexBuffer;
  26014. data[kind] = vbs[kind].getData();
  26015. newdata[kind] = [];
  26016. }
  26017. // Save previous submeshes
  26018. var previousSubmeshes = this.subMeshes.slice(0);
  26019. var indices = this.getIndices();
  26020. var totalIndices = this.getTotalIndices();
  26021. // Generating unique vertices per face
  26022. var index;
  26023. for (index = 0; index < totalIndices; index++) {
  26024. var vertexIndex = indices[index];
  26025. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26026. kind = kinds[kindIndex];
  26027. var stride = vbs[kind].getStrideSize();
  26028. for (var offset = 0; offset < stride; offset++) {
  26029. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  26030. }
  26031. }
  26032. }
  26033. // Updating faces & normal
  26034. var normals = [];
  26035. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  26036. for (index = 0; index < totalIndices; index += 3) {
  26037. indices[index] = index;
  26038. indices[index + 1] = index + 1;
  26039. indices[index + 2] = index + 2;
  26040. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  26041. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  26042. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  26043. var p1p2 = p1.subtract(p2);
  26044. var p3p2 = p3.subtract(p2);
  26045. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  26046. // Store same normals for every vertex
  26047. for (var localIndex = 0; localIndex < 3; localIndex++) {
  26048. normals.push(normal.x);
  26049. normals.push(normal.y);
  26050. normals.push(normal.z);
  26051. }
  26052. }
  26053. this.setIndices(indices);
  26054. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  26055. // Updating vertex buffers
  26056. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26057. kind = kinds[kindIndex];
  26058. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  26059. }
  26060. // Updating submeshes
  26061. this.releaseSubMeshes();
  26062. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  26063. var previousOne = previousSubmeshes[submeshIndex];
  26064. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  26065. }
  26066. this.synchronizeInstances();
  26067. return this;
  26068. };
  26069. /**
  26070. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  26071. * In other words, more vertices, no more indices and a single bigger VBO.
  26072. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  26073. * Returns the Mesh.
  26074. */
  26075. Mesh.prototype.convertToUnIndexedMesh = function () {
  26076. /// <summary>Remove indices by unfolding faces into buffers</summary>
  26077. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  26078. var kinds = this.getVerticesDataKinds();
  26079. var vbs = {};
  26080. var data = {};
  26081. var newdata = {};
  26082. var kindIndex;
  26083. var kind;
  26084. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26085. kind = kinds[kindIndex];
  26086. var vertexBuffer = this.getVertexBuffer(kind);
  26087. vbs[kind] = vertexBuffer;
  26088. data[kind] = vbs[kind].getData();
  26089. newdata[kind] = [];
  26090. }
  26091. // Save previous submeshes
  26092. var previousSubmeshes = this.subMeshes.slice(0);
  26093. var indices = this.getIndices();
  26094. var totalIndices = this.getTotalIndices();
  26095. // Generating unique vertices per face
  26096. var index;
  26097. for (index = 0; index < totalIndices; index++) {
  26098. var vertexIndex = indices[index];
  26099. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26100. kind = kinds[kindIndex];
  26101. var stride = vbs[kind].getStrideSize();
  26102. for (var offset = 0; offset < stride; offset++) {
  26103. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  26104. }
  26105. }
  26106. }
  26107. // Updating indices
  26108. for (index = 0; index < totalIndices; index += 3) {
  26109. indices[index] = index;
  26110. indices[index + 1] = index + 1;
  26111. indices[index + 2] = index + 2;
  26112. }
  26113. this.setIndices(indices);
  26114. // Updating vertex buffers
  26115. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26116. kind = kinds[kindIndex];
  26117. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  26118. }
  26119. // Updating submeshes
  26120. this.releaseSubMeshes();
  26121. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  26122. var previousOne = previousSubmeshes[submeshIndex];
  26123. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  26124. }
  26125. this._unIndexed = true;
  26126. this.synchronizeInstances();
  26127. return this;
  26128. };
  26129. /**
  26130. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  26131. * This method returns the Mesh.
  26132. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  26133. */
  26134. Mesh.prototype.flipFaces = function (flipNormals) {
  26135. if (flipNormals === void 0) { flipNormals = false; }
  26136. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  26137. var i;
  26138. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  26139. for (i = 0; i < vertex_data.normals.length; i++) {
  26140. vertex_data.normals[i] *= -1;
  26141. }
  26142. }
  26143. if (vertex_data.indices) {
  26144. var temp;
  26145. for (i = 0; i < vertex_data.indices.length; i += 3) {
  26146. // reassign indices
  26147. temp = vertex_data.indices[i + 1];
  26148. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  26149. vertex_data.indices[i + 2] = temp;
  26150. }
  26151. }
  26152. vertex_data.applyToMesh(this);
  26153. return this;
  26154. };
  26155. // Instances
  26156. /**
  26157. * Creates a new InstancedMesh object from the mesh model.
  26158. * An instance shares the same properties and the same material than its model.
  26159. * Only these properties of each instance can then be set individually :
  26160. * - position
  26161. * - rotation
  26162. * - rotationQuaternion
  26163. * - setPivotMatrix
  26164. * - scaling
  26165. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  26166. * Warning : this method is not supported for Line mesh and LineSystem
  26167. */
  26168. Mesh.prototype.createInstance = function (name) {
  26169. return new BABYLON.InstancedMesh(name, this);
  26170. };
  26171. /**
  26172. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  26173. * After this call, all the mesh instances have the same submeshes than the current mesh.
  26174. * This method returns the Mesh.
  26175. */
  26176. Mesh.prototype.synchronizeInstances = function () {
  26177. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  26178. var instance = this.instances[instanceIndex];
  26179. instance._syncSubMeshes();
  26180. }
  26181. return this;
  26182. };
  26183. /**
  26184. * Simplify the mesh according to the given array of settings.
  26185. * Function will return immediately and will simplify async. It returns the Mesh.
  26186. * @param settings a collection of simplification settings.
  26187. * @param parallelProcessing should all levels calculate parallel or one after the other.
  26188. * @param type the type of simplification to run.
  26189. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  26190. */
  26191. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  26192. if (parallelProcessing === void 0) { parallelProcessing = true; }
  26193. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  26194. this.getScene().simplificationQueue.addTask({
  26195. settings: settings,
  26196. parallelProcessing: parallelProcessing,
  26197. mesh: this,
  26198. simplificationType: simplificationType,
  26199. successCallback: successCallback
  26200. });
  26201. return this;
  26202. };
  26203. /**
  26204. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  26205. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  26206. * This should be used together with the simplification to avoid disappearing triangles.
  26207. * Returns the Mesh.
  26208. * @param successCallback an optional success callback to be called after the optimization finished.
  26209. */
  26210. Mesh.prototype.optimizeIndices = function (successCallback) {
  26211. var _this = this;
  26212. var indices = this.getIndices();
  26213. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26214. if (!positions || !indices) {
  26215. return this;
  26216. }
  26217. var vectorPositions = new Array();
  26218. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  26219. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  26220. }
  26221. var dupes = new Array();
  26222. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  26223. var realPos = vectorPositions.length - 1 - iteration;
  26224. var testedPosition = vectorPositions[realPos];
  26225. for (var j = 0; j < realPos; ++j) {
  26226. var againstPosition = vectorPositions[j];
  26227. if (testedPosition.equals(againstPosition)) {
  26228. dupes[realPos] = j;
  26229. break;
  26230. }
  26231. }
  26232. }, function () {
  26233. for (var i = 0; i < indices.length; ++i) {
  26234. indices[i] = dupes[indices[i]] || indices[i];
  26235. }
  26236. //indices are now reordered
  26237. var originalSubMeshes = _this.subMeshes.slice(0);
  26238. _this.setIndices(indices);
  26239. _this.subMeshes = originalSubMeshes;
  26240. if (successCallback) {
  26241. successCallback(_this);
  26242. }
  26243. });
  26244. return this;
  26245. };
  26246. Mesh.prototype.serialize = function (serializationObject) {
  26247. serializationObject.name = this.name;
  26248. serializationObject.id = this.id;
  26249. serializationObject.type = this.getClassName();
  26250. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  26251. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26252. }
  26253. serializationObject.position = this.position.asArray();
  26254. if (this.rotationQuaternion) {
  26255. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  26256. }
  26257. else if (this.rotation) {
  26258. serializationObject.rotation = this.rotation.asArray();
  26259. }
  26260. serializationObject.scaling = this.scaling.asArray();
  26261. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  26262. serializationObject.isEnabled = this.isEnabled(false);
  26263. serializationObject.isVisible = this.isVisible;
  26264. serializationObject.infiniteDistance = this.infiniteDistance;
  26265. serializationObject.pickable = this.isPickable;
  26266. serializationObject.receiveShadows = this.receiveShadows;
  26267. serializationObject.billboardMode = this.billboardMode;
  26268. serializationObject.visibility = this.visibility;
  26269. serializationObject.checkCollisions = this.checkCollisions;
  26270. serializationObject.isBlocker = this.isBlocker;
  26271. // Parent
  26272. if (this.parent) {
  26273. serializationObject.parentId = this.parent.id;
  26274. }
  26275. // Geometry
  26276. serializationObject.isUnIndexed = this.isUnIndexed;
  26277. var geometry = this._geometry;
  26278. if (geometry) {
  26279. var geometryId = geometry.id;
  26280. serializationObject.geometryId = geometryId;
  26281. // SubMeshes
  26282. serializationObject.subMeshes = [];
  26283. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  26284. var subMesh = this.subMeshes[subIndex];
  26285. serializationObject.subMeshes.push({
  26286. materialIndex: subMesh.materialIndex,
  26287. verticesStart: subMesh.verticesStart,
  26288. verticesCount: subMesh.verticesCount,
  26289. indexStart: subMesh.indexStart,
  26290. indexCount: subMesh.indexCount
  26291. });
  26292. }
  26293. }
  26294. // Material
  26295. if (this.material) {
  26296. serializationObject.materialId = this.material.id;
  26297. }
  26298. else {
  26299. this.material = null;
  26300. }
  26301. // Morph targets
  26302. if (this.morphTargetManager) {
  26303. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  26304. }
  26305. // Skeleton
  26306. if (this.skeleton) {
  26307. serializationObject.skeletonId = this.skeleton.id;
  26308. }
  26309. // Physics
  26310. //TODO implement correct serialization for physics impostors.
  26311. var impostor = this.getPhysicsImpostor();
  26312. if (impostor) {
  26313. serializationObject.physicsMass = impostor.getParam("mass");
  26314. serializationObject.physicsFriction = impostor.getParam("friction");
  26315. serializationObject.physicsRestitution = impostor.getParam("mass");
  26316. serializationObject.physicsImpostor = impostor.type;
  26317. }
  26318. // Metadata
  26319. if (this.metadata) {
  26320. serializationObject.metadata = this.metadata;
  26321. }
  26322. // Instances
  26323. serializationObject.instances = [];
  26324. for (var index = 0; index < this.instances.length; index++) {
  26325. var instance = this.instances[index];
  26326. var serializationInstance = {
  26327. name: instance.name,
  26328. id: instance.id,
  26329. position: instance.position.asArray(),
  26330. scaling: instance.scaling.asArray()
  26331. };
  26332. if (instance.rotationQuaternion) {
  26333. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  26334. }
  26335. else if (instance.rotation) {
  26336. serializationInstance.rotation = instance.rotation.asArray();
  26337. }
  26338. serializationObject.instances.push(serializationInstance);
  26339. // Animations
  26340. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  26341. serializationInstance.ranges = instance.serializeAnimationRanges();
  26342. }
  26343. //
  26344. // Animations
  26345. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26346. serializationObject.ranges = this.serializeAnimationRanges();
  26347. // Layer mask
  26348. serializationObject.layerMask = this.layerMask;
  26349. // Alpha
  26350. serializationObject.alphaIndex = this.alphaIndex;
  26351. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  26352. // Overlay
  26353. serializationObject.overlayAlpha = this.overlayAlpha;
  26354. serializationObject.overlayColor = this.overlayColor.asArray();
  26355. serializationObject.renderOverlay = this.renderOverlay;
  26356. // Fog
  26357. serializationObject.applyFog = this.applyFog;
  26358. // Action Manager
  26359. if (this.actionManager) {
  26360. serializationObject.actions = this.actionManager.serialize(this.name);
  26361. }
  26362. };
  26363. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  26364. if (!this.geometry) {
  26365. return;
  26366. }
  26367. this._markSubMeshesAsAttributesDirty();
  26368. var morphTargetManager = this._morphTargetManager;
  26369. if (morphTargetManager && morphTargetManager.vertexCount) {
  26370. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  26371. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  26372. this.morphTargetManager = null;
  26373. return;
  26374. }
  26375. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  26376. var morphTarget = morphTargetManager.getActiveTarget(index);
  26377. var positions = morphTarget.getPositions();
  26378. if (!positions) {
  26379. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  26380. return;
  26381. }
  26382. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  26383. var normals = morphTarget.getNormals();
  26384. if (normals) {
  26385. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  26386. }
  26387. var tangents = morphTarget.getTangents();
  26388. if (tangents) {
  26389. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  26390. }
  26391. }
  26392. }
  26393. else {
  26394. var index = 0;
  26395. // Positions
  26396. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  26397. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  26398. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  26399. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  26400. }
  26401. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  26402. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  26403. }
  26404. index++;
  26405. }
  26406. }
  26407. };
  26408. // Statics
  26409. /**
  26410. * Returns a new Mesh object parsed from the source provided.
  26411. * The parameter `parsedMesh` is the source.
  26412. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  26413. */
  26414. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  26415. var mesh;
  26416. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  26417. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  26418. }
  26419. else {
  26420. mesh = new Mesh(parsedMesh.name, scene);
  26421. }
  26422. mesh.id = parsedMesh.id;
  26423. if (BABYLON.Tags) {
  26424. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  26425. }
  26426. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  26427. if (parsedMesh.metadata !== undefined) {
  26428. mesh.metadata = parsedMesh.metadata;
  26429. }
  26430. if (parsedMesh.rotationQuaternion) {
  26431. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  26432. }
  26433. else if (parsedMesh.rotation) {
  26434. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  26435. }
  26436. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  26437. if (parsedMesh.localMatrix) {
  26438. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  26439. }
  26440. else if (parsedMesh.pivotMatrix) {
  26441. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  26442. }
  26443. mesh.setEnabled(parsedMesh.isEnabled);
  26444. mesh.isVisible = parsedMesh.isVisible;
  26445. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  26446. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  26447. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  26448. if (parsedMesh.applyFog !== undefined) {
  26449. mesh.applyFog = parsedMesh.applyFog;
  26450. }
  26451. if (parsedMesh.pickable !== undefined) {
  26452. mesh.isPickable = parsedMesh.pickable;
  26453. }
  26454. if (parsedMesh.alphaIndex !== undefined) {
  26455. mesh.alphaIndex = parsedMesh.alphaIndex;
  26456. }
  26457. mesh.receiveShadows = parsedMesh.receiveShadows;
  26458. mesh.billboardMode = parsedMesh.billboardMode;
  26459. if (parsedMesh.visibility !== undefined) {
  26460. mesh.visibility = parsedMesh.visibility;
  26461. }
  26462. mesh.checkCollisions = parsedMesh.checkCollisions;
  26463. if (parsedMesh.isBlocker !== undefined) {
  26464. mesh.isBlocker = parsedMesh.isBlocker;
  26465. }
  26466. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  26467. // freezeWorldMatrix
  26468. if (parsedMesh.freezeWorldMatrix) {
  26469. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  26470. }
  26471. // Parent
  26472. if (parsedMesh.parentId) {
  26473. mesh._waitingParentId = parsedMesh.parentId;
  26474. }
  26475. // Actions
  26476. if (parsedMesh.actions !== undefined) {
  26477. mesh._waitingActions = parsedMesh.actions;
  26478. }
  26479. // Overlay
  26480. if (parsedMesh.overlayAlpha !== undefined) {
  26481. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  26482. }
  26483. if (parsedMesh.overlayColor !== undefined) {
  26484. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  26485. }
  26486. if (parsedMesh.renderOverlay !== undefined) {
  26487. mesh.renderOverlay = parsedMesh.renderOverlay;
  26488. }
  26489. // Geometry
  26490. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  26491. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  26492. if (parsedMesh.delayLoadingFile) {
  26493. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26494. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  26495. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  26496. if (parsedMesh._binaryInfo) {
  26497. mesh._binaryInfo = parsedMesh._binaryInfo;
  26498. }
  26499. mesh._delayInfo = [];
  26500. if (parsedMesh.hasUVs) {
  26501. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  26502. }
  26503. if (parsedMesh.hasUVs2) {
  26504. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  26505. }
  26506. if (parsedMesh.hasUVs3) {
  26507. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  26508. }
  26509. if (parsedMesh.hasUVs4) {
  26510. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  26511. }
  26512. if (parsedMesh.hasUVs5) {
  26513. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  26514. }
  26515. if (parsedMesh.hasUVs6) {
  26516. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  26517. }
  26518. if (parsedMesh.hasColors) {
  26519. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  26520. }
  26521. if (parsedMesh.hasMatricesIndices) {
  26522. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26523. }
  26524. if (parsedMesh.hasMatricesWeights) {
  26525. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26526. }
  26527. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  26528. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  26529. mesh._checkDelayState();
  26530. }
  26531. }
  26532. else {
  26533. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  26534. }
  26535. // Material
  26536. if (parsedMesh.materialId) {
  26537. mesh.setMaterialByID(parsedMesh.materialId);
  26538. }
  26539. else {
  26540. mesh.material = null;
  26541. }
  26542. // Morph targets
  26543. if (parsedMesh.morphTargetManagerId > -1) {
  26544. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  26545. }
  26546. // Skeleton
  26547. if (parsedMesh.skeletonId > -1) {
  26548. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  26549. if (parsedMesh.numBoneInfluencers) {
  26550. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  26551. }
  26552. }
  26553. // Animations
  26554. if (parsedMesh.animations) {
  26555. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  26556. var parsedAnimation = parsedMesh.animations[animationIndex];
  26557. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26558. }
  26559. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  26560. }
  26561. if (parsedMesh.autoAnimate) {
  26562. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  26563. }
  26564. // Layer Mask
  26565. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  26566. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  26567. }
  26568. else {
  26569. mesh.layerMask = 0x0FFFFFFF;
  26570. }
  26571. // Physics
  26572. if (parsedMesh.physicsImpostor) {
  26573. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  26574. mass: parsedMesh.physicsMass,
  26575. friction: parsedMesh.physicsFriction,
  26576. restitution: parsedMesh.physicsRestitution
  26577. }, scene);
  26578. }
  26579. // Instances
  26580. if (parsedMesh.instances) {
  26581. for (var index = 0; index < parsedMesh.instances.length; index++) {
  26582. var parsedInstance = parsedMesh.instances[index];
  26583. var instance = mesh.createInstance(parsedInstance.name);
  26584. if (parsedInstance.id) {
  26585. instance.id = parsedInstance.id;
  26586. }
  26587. if (BABYLON.Tags) {
  26588. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  26589. }
  26590. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  26591. if (parsedInstance.parentId) {
  26592. instance._waitingParentId = parsedInstance.parentId;
  26593. }
  26594. if (parsedInstance.rotationQuaternion) {
  26595. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  26596. }
  26597. else if (parsedInstance.rotation) {
  26598. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  26599. }
  26600. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  26601. instance.checkCollisions = mesh.checkCollisions;
  26602. if (parsedMesh.animations) {
  26603. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  26604. parsedAnimation = parsedMesh.animations[animationIndex];
  26605. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26606. }
  26607. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  26608. }
  26609. }
  26610. }
  26611. return mesh;
  26612. };
  26613. /**
  26614. * Creates a ribbon mesh.
  26615. * Please consider using the same method from the MeshBuilder class instead.
  26616. * 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.
  26617. *
  26618. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  26619. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  26620. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  26621. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  26622. * 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.
  26623. * 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.
  26624. * 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
  26625. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26626. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26627. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26628. */
  26629. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  26630. if (closeArray === void 0) { closeArray = false; }
  26631. if (updatable === void 0) { updatable = false; }
  26632. return BABYLON.MeshBuilder.CreateRibbon(name, {
  26633. pathArray: pathArray,
  26634. closeArray: closeArray,
  26635. closePath: closePath,
  26636. offset: offset,
  26637. updatable: updatable,
  26638. sideOrientation: sideOrientation,
  26639. instance: instance
  26640. }, scene);
  26641. };
  26642. /**
  26643. * Creates a plane polygonal mesh. By default, this is a disc.
  26644. * Please consider using the same method from the MeshBuilder class instead.
  26645. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  26646. * 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.
  26647. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26648. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26649. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26650. */
  26651. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  26652. if (scene === void 0) { scene = null; }
  26653. var options = {
  26654. radius: radius,
  26655. tessellation: tessellation,
  26656. sideOrientation: sideOrientation,
  26657. updatable: updatable
  26658. };
  26659. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  26660. };
  26661. /**
  26662. * Creates a box mesh.
  26663. * Please consider using the same method from the MeshBuilder class instead.
  26664. * The parameter `size` sets the size (float) of each box side (default 1).
  26665. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26666. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26667. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26668. */
  26669. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  26670. if (scene === void 0) { scene = null; }
  26671. var options = {
  26672. size: size,
  26673. sideOrientation: sideOrientation,
  26674. updatable: updatable
  26675. };
  26676. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  26677. };
  26678. /**
  26679. * Creates a sphere mesh.
  26680. * Please consider using the same method from the MeshBuilder class instead.
  26681. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  26682. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  26683. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26684. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26685. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26686. */
  26687. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  26688. var options = {
  26689. segments: segments,
  26690. diameterX: diameter,
  26691. diameterY: diameter,
  26692. diameterZ: diameter,
  26693. sideOrientation: sideOrientation,
  26694. updatable: updatable
  26695. };
  26696. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  26697. };
  26698. /**
  26699. * Creates a cylinder or a cone mesh.
  26700. * Please consider using the same method from the MeshBuilder class instead.
  26701. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  26702. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  26703. * 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.
  26704. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  26705. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  26706. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26707. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26708. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26709. */
  26710. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  26711. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  26712. if (scene !== undefined) {
  26713. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  26714. updatable = scene;
  26715. }
  26716. scene = subdivisions;
  26717. subdivisions = 1;
  26718. }
  26719. var options = {
  26720. height: height,
  26721. diameterTop: diameterTop,
  26722. diameterBottom: diameterBottom,
  26723. tessellation: tessellation,
  26724. subdivisions: subdivisions,
  26725. sideOrientation: sideOrientation,
  26726. updatable: updatable
  26727. };
  26728. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  26729. };
  26730. // Torus (Code from SharpDX.org)
  26731. /**
  26732. * Creates a torus mesh.
  26733. * Please consider using the same method from the MeshBuilder class instead.
  26734. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  26735. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  26736. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  26737. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26738. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26739. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26740. */
  26741. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  26742. var options = {
  26743. diameter: diameter,
  26744. thickness: thickness,
  26745. tessellation: tessellation,
  26746. sideOrientation: sideOrientation,
  26747. updatable: updatable
  26748. };
  26749. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  26750. };
  26751. /**
  26752. * Creates a torus knot mesh.
  26753. * Please consider using the same method from the MeshBuilder class instead.
  26754. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  26755. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  26756. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  26757. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  26758. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26759. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26760. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26761. */
  26762. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  26763. var options = {
  26764. radius: radius,
  26765. tube: tube,
  26766. radialSegments: radialSegments,
  26767. tubularSegments: tubularSegments,
  26768. p: p,
  26769. q: q,
  26770. sideOrientation: sideOrientation,
  26771. updatable: updatable
  26772. };
  26773. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  26774. };
  26775. /**
  26776. * Creates a line mesh.
  26777. * Please consider using the same method from the MeshBuilder class instead.
  26778. * 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.
  26779. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  26780. * The parameter `points` is an array successive Vector3.
  26781. * 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
  26782. * When updating an instance, remember that only point positions can change, not the number of points.
  26783. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26784. */
  26785. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  26786. if (scene === void 0) { scene = null; }
  26787. if (updatable === void 0) { updatable = false; }
  26788. if (instance === void 0) { instance = null; }
  26789. var options = {
  26790. points: points,
  26791. updatable: updatable,
  26792. instance: instance
  26793. };
  26794. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  26795. };
  26796. /**
  26797. * Creates a dashed line mesh.
  26798. * Please consider using the same method from the MeshBuilder class instead.
  26799. * 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.
  26800. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  26801. * The parameter `points` is an array successive Vector3.
  26802. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  26803. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  26804. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  26805. * 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
  26806. * When updating an instance, remember that only point positions can change, not the number of points.
  26807. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26808. */
  26809. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  26810. if (scene === void 0) { scene = null; }
  26811. var options = {
  26812. points: points,
  26813. dashSize: dashSize,
  26814. gapSize: gapSize,
  26815. dashNb: dashNb,
  26816. updatable: updatable,
  26817. instance: instance
  26818. };
  26819. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  26820. };
  26821. /**
  26822. * Creates a polygon mesh.
  26823. * Please consider using the same method from the MeshBuilder class instead.
  26824. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  26825. * 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.
  26826. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26827. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26828. * Remember you can only change the shape positions, not their number when updating a polygon.
  26829. */
  26830. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  26831. var options = {
  26832. shape: shape,
  26833. holes: holes,
  26834. updatable: updatable,
  26835. sideOrientation: sideOrientation
  26836. };
  26837. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  26838. };
  26839. /**
  26840. * Creates an extruded polygon mesh, with depth in the Y direction.
  26841. * Please consider using the same method from the MeshBuilder class instead.
  26842. */
  26843. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  26844. var options = {
  26845. shape: shape,
  26846. holes: holes,
  26847. depth: depth,
  26848. updatable: updatable,
  26849. sideOrientation: sideOrientation
  26850. };
  26851. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  26852. };
  26853. /**
  26854. * Creates an extruded shape mesh.
  26855. * 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.
  26856. * Please consider using the same method from the MeshBuilder class instead.
  26857. *
  26858. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  26859. * 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
  26860. * extruded along the Z axis.
  26861. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  26862. * 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.
  26863. * The parameter `scale` (float, default 1) is the value to scale the shape.
  26864. * 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
  26865. * 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
  26866. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  26867. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26868. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26869. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26870. */
  26871. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  26872. if (scene === void 0) { scene = null; }
  26873. var options = {
  26874. shape: shape,
  26875. path: path,
  26876. scale: scale,
  26877. rotation: rotation,
  26878. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  26879. sideOrientation: sideOrientation,
  26880. instance: instance,
  26881. updatable: updatable
  26882. };
  26883. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  26884. };
  26885. /**
  26886. * Creates an custom extruded shape mesh.
  26887. * 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.
  26888. * Please consider using the same method from the MeshBuilder class instead.
  26889. *
  26890. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  26891. * 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
  26892. * extruded along the Z axis.
  26893. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  26894. * 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
  26895. * and the distance of this point from the begining of the path :
  26896. * ```javascript
  26897. * var rotationFunction = function(i, distance) {
  26898. * // do things
  26899. * return rotationValue; }
  26900. * ```
  26901. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  26902. * 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
  26903. * and the distance of this point from the begining of the path :
  26904. * ```javascript
  26905. * var scaleFunction = function(i, distance) {
  26906. * // do things
  26907. * return scaleValue;}
  26908. * ```
  26909. * It must returns a float value that will be the scale value applied to the shape on each path point.
  26910. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  26911. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  26912. * 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
  26913. * 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
  26914. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  26915. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26916. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26917. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26918. */
  26919. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  26920. var options = {
  26921. shape: shape,
  26922. path: path,
  26923. scaleFunction: scaleFunction,
  26924. rotationFunction: rotationFunction,
  26925. ribbonCloseArray: ribbonCloseArray,
  26926. ribbonClosePath: ribbonClosePath,
  26927. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  26928. sideOrientation: sideOrientation,
  26929. instance: instance,
  26930. updatable: updatable
  26931. };
  26932. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  26933. };
  26934. /**
  26935. * Creates lathe mesh.
  26936. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  26937. * Please consider using the same method from the MeshBuilder class instead.
  26938. * 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
  26939. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  26940. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  26941. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  26942. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26943. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26944. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26945. */
  26946. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  26947. var options = {
  26948. shape: shape,
  26949. radius: radius,
  26950. tessellation: tessellation,
  26951. sideOrientation: sideOrientation,
  26952. updatable: updatable
  26953. };
  26954. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  26955. };
  26956. /**
  26957. * Creates a plane mesh.
  26958. * Please consider using the same method from the MeshBuilder class instead.
  26959. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  26960. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26961. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26962. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26963. */
  26964. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  26965. var options = {
  26966. size: size,
  26967. width: size,
  26968. height: size,
  26969. sideOrientation: sideOrientation,
  26970. updatable: updatable
  26971. };
  26972. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  26973. };
  26974. /**
  26975. * Creates a ground mesh.
  26976. * Please consider using the same method from the MeshBuilder class instead.
  26977. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  26978. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  26979. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26980. */
  26981. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  26982. var options = {
  26983. width: width,
  26984. height: height,
  26985. subdivisions: subdivisions,
  26986. updatable: updatable
  26987. };
  26988. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  26989. };
  26990. /**
  26991. * Creates a tiled ground mesh.
  26992. * Please consider using the same method from the MeshBuilder class instead.
  26993. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  26994. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  26995. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  26996. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  26997. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  26998. * numbers of subdivisions on the ground width and height of each tile.
  26999. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27000. */
  27001. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  27002. var options = {
  27003. xmin: xmin,
  27004. zmin: zmin,
  27005. xmax: xmax,
  27006. zmax: zmax,
  27007. subdivisions: subdivisions,
  27008. precision: precision,
  27009. updatable: updatable
  27010. };
  27011. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  27012. };
  27013. /**
  27014. * Creates a ground mesh from a height map.
  27015. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  27016. * Please consider using the same method from the MeshBuilder class instead.
  27017. * The parameter `url` sets the URL of the height map image resource.
  27018. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  27019. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  27020. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  27021. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  27022. * 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).
  27023. * This function is passed the newly built mesh :
  27024. * ```javascript
  27025. * function(mesh) { // do things
  27026. * return; }
  27027. * ```
  27028. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27029. */
  27030. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  27031. var options = {
  27032. width: width,
  27033. height: height,
  27034. subdivisions: subdivisions,
  27035. minHeight: minHeight,
  27036. maxHeight: maxHeight,
  27037. updatable: updatable,
  27038. onReady: onReady
  27039. };
  27040. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  27041. };
  27042. /**
  27043. * Creates a tube mesh.
  27044. * 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.
  27045. * Please consider using the same method from the MeshBuilder class instead.
  27046. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  27047. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  27048. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  27049. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  27050. * 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.
  27051. * It must return a radius value (positive float) :
  27052. * ```javascript
  27053. * var radiusFunction = function(i, distance) {
  27054. * // do things
  27055. * return radius; }
  27056. * ```
  27057. * 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
  27058. * 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
  27059. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27060. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27061. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27062. */
  27063. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  27064. var options = {
  27065. path: path,
  27066. radius: radius,
  27067. tessellation: tessellation,
  27068. radiusFunction: radiusFunction,
  27069. arc: 1,
  27070. cap: cap,
  27071. updatable: updatable,
  27072. sideOrientation: sideOrientation,
  27073. instance: instance
  27074. };
  27075. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  27076. };
  27077. /**
  27078. * Creates a polyhedron mesh.
  27079. * Please consider using the same method from the MeshBuilder class instead.
  27080. * 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
  27081. * to choose the wanted type.
  27082. * The parameter `size` (positive float, default 1) sets the polygon size.
  27083. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  27084. * 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`.
  27085. * 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
  27086. * 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)`).
  27087. * 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
  27088. * 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.
  27089. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27090. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27091. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27092. */
  27093. Mesh.CreatePolyhedron = function (name, options, scene) {
  27094. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  27095. };
  27096. /**
  27097. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  27098. * Please consider using the same method from the MeshBuilder class instead.
  27099. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  27100. * 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`).
  27101. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  27102. * 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.
  27103. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27104. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27105. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27106. */
  27107. Mesh.CreateIcoSphere = function (name, options, scene) {
  27108. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  27109. };
  27110. /**
  27111. * Creates a decal mesh.
  27112. * Please consider using the same method from the MeshBuilder class instead.
  27113. * 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.
  27114. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  27115. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  27116. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  27117. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  27118. */
  27119. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  27120. var options = {
  27121. position: position,
  27122. normal: normal,
  27123. size: size,
  27124. angle: angle
  27125. };
  27126. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  27127. };
  27128. // Skeletons
  27129. /**
  27130. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  27131. */
  27132. Mesh.prototype.setPositionsForCPUSkinning = function () {
  27133. if (!this._sourcePositions) {
  27134. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27135. if (!source) {
  27136. return this._sourcePositions;
  27137. }
  27138. this._sourcePositions = new Float32Array(source);
  27139. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  27140. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  27141. }
  27142. }
  27143. return this._sourcePositions;
  27144. };
  27145. /**
  27146. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  27147. */
  27148. Mesh.prototype.setNormalsForCPUSkinning = function () {
  27149. if (!this._sourceNormals) {
  27150. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27151. if (!source) {
  27152. return this._sourceNormals;
  27153. }
  27154. this._sourceNormals = new Float32Array(source);
  27155. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  27156. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  27157. }
  27158. }
  27159. return this._sourceNormals;
  27160. };
  27161. /**
  27162. * Updates the vertex buffer by applying transformation from the bones.
  27163. * Returns the Mesh.
  27164. *
  27165. * @param {skeleton} skeleton to apply
  27166. */
  27167. Mesh.prototype.applySkeleton = function (skeleton) {
  27168. if (!this.geometry) {
  27169. return this;
  27170. }
  27171. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  27172. return this;
  27173. }
  27174. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  27175. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27176. return this;
  27177. }
  27178. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27179. return this;
  27180. }
  27181. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27182. return this;
  27183. }
  27184. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27185. return this;
  27186. }
  27187. if (!this._sourcePositions) {
  27188. var submeshes = this.subMeshes.slice();
  27189. this.setPositionsForCPUSkinning();
  27190. this.subMeshes = submeshes;
  27191. }
  27192. if (!this._sourceNormals) {
  27193. this.setNormalsForCPUSkinning();
  27194. }
  27195. // positionsData checks for not being Float32Array will only pass at most once
  27196. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27197. if (!positionsData) {
  27198. return this;
  27199. }
  27200. if (!(positionsData instanceof Float32Array)) {
  27201. positionsData = new Float32Array(positionsData);
  27202. }
  27203. // normalsData checks for not being Float32Array will only pass at most once
  27204. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27205. if (!normalsData) {
  27206. return this;
  27207. }
  27208. if (!(normalsData instanceof Float32Array)) {
  27209. normalsData = new Float32Array(normalsData);
  27210. }
  27211. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27212. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27213. if (!matricesWeightsData || !matricesIndicesData) {
  27214. return this;
  27215. }
  27216. var needExtras = this.numBoneInfluencers > 4;
  27217. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27218. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27219. var skeletonMatrices = skeleton.getTransformMatrices(this);
  27220. var tempVector3 = BABYLON.Vector3.Zero();
  27221. var finalMatrix = new BABYLON.Matrix();
  27222. var tempMatrix = new BABYLON.Matrix();
  27223. var matWeightIdx = 0;
  27224. var inf;
  27225. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  27226. var weight;
  27227. for (inf = 0; inf < 4; inf++) {
  27228. weight = matricesWeightsData[matWeightIdx + inf];
  27229. if (weight > 0) {
  27230. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27231. finalMatrix.addToSelf(tempMatrix);
  27232. }
  27233. else
  27234. break;
  27235. }
  27236. if (needExtras) {
  27237. for (inf = 0; inf < 4; inf++) {
  27238. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27239. if (weight > 0) {
  27240. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27241. finalMatrix.addToSelf(tempMatrix);
  27242. }
  27243. else
  27244. break;
  27245. }
  27246. }
  27247. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  27248. tempVector3.toArray(positionsData, index);
  27249. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  27250. tempVector3.toArray(normalsData, index);
  27251. finalMatrix.reset();
  27252. }
  27253. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  27254. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  27255. return this;
  27256. };
  27257. // Tools
  27258. /**
  27259. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  27260. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  27261. */
  27262. Mesh.MinMax = function (meshes) {
  27263. var minVector = null;
  27264. var maxVector = null;
  27265. meshes.forEach(function (mesh, index, array) {
  27266. var boundingInfo = mesh.getBoundingInfo();
  27267. var boundingBox = boundingInfo.boundingBox;
  27268. if (!minVector || !maxVector) {
  27269. minVector = boundingBox.minimumWorld;
  27270. maxVector = boundingBox.maximumWorld;
  27271. }
  27272. else {
  27273. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  27274. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  27275. }
  27276. });
  27277. if (!minVector || !maxVector) {
  27278. return {
  27279. min: BABYLON.Vector3.Zero(),
  27280. max: BABYLON.Vector3.Zero()
  27281. };
  27282. }
  27283. return {
  27284. min: minVector,
  27285. max: maxVector
  27286. };
  27287. };
  27288. /**
  27289. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  27290. */
  27291. Mesh.Center = function (meshesOrMinMaxVector) {
  27292. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  27293. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  27294. };
  27295. /**
  27296. * Merge the array of meshes into a single mesh for performance reasons.
  27297. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  27298. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  27299. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  27300. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  27301. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  27302. */
  27303. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  27304. if (disposeSource === void 0) { disposeSource = true; }
  27305. var index;
  27306. if (!allow32BitsIndices) {
  27307. var totalVertices = 0;
  27308. // Counting vertices
  27309. for (index = 0; index < meshes.length; index++) {
  27310. if (meshes[index]) {
  27311. totalVertices += meshes[index].getTotalVertices();
  27312. if (totalVertices > 65536) {
  27313. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  27314. return null;
  27315. }
  27316. }
  27317. }
  27318. }
  27319. // Merge
  27320. var vertexData = null;
  27321. var otherVertexData;
  27322. var indiceArray = new Array();
  27323. var source = null;
  27324. for (index = 0; index < meshes.length; index++) {
  27325. if (meshes[index]) {
  27326. meshes[index].computeWorldMatrix(true);
  27327. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  27328. otherVertexData.transform(meshes[index].getWorldMatrix());
  27329. if (vertexData) {
  27330. vertexData.merge(otherVertexData);
  27331. }
  27332. else {
  27333. vertexData = otherVertexData;
  27334. source = meshes[index];
  27335. }
  27336. if (subdivideWithSubMeshes) {
  27337. indiceArray.push(meshes[index].getTotalIndices());
  27338. }
  27339. }
  27340. }
  27341. source = source;
  27342. if (!meshSubclass) {
  27343. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  27344. }
  27345. vertexData.applyToMesh(meshSubclass);
  27346. // Setting properties
  27347. meshSubclass.material = source.material;
  27348. meshSubclass.checkCollisions = source.checkCollisions;
  27349. // Cleaning
  27350. if (disposeSource) {
  27351. for (index = 0; index < meshes.length; index++) {
  27352. if (meshes[index]) {
  27353. meshes[index].dispose();
  27354. }
  27355. }
  27356. }
  27357. // Subdivide
  27358. if (subdivideWithSubMeshes) {
  27359. //-- Suppresions du submesh global
  27360. meshSubclass.releaseSubMeshes();
  27361. index = 0;
  27362. var offset = 0;
  27363. //-- aplique la subdivision en fonction du tableau d'indices
  27364. while (index < indiceArray.length) {
  27365. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  27366. offset += indiceArray[index];
  27367. index++;
  27368. }
  27369. }
  27370. return meshSubclass;
  27371. };
  27372. // Consts
  27373. Mesh._FRONTSIDE = 0;
  27374. Mesh._BACKSIDE = 1;
  27375. Mesh._DOUBLESIDE = 2;
  27376. Mesh._DEFAULTSIDE = 0;
  27377. Mesh._NO_CAP = 0;
  27378. Mesh._CAP_START = 1;
  27379. Mesh._CAP_END = 2;
  27380. Mesh._CAP_ALL = 3;
  27381. return Mesh;
  27382. }(BABYLON.AbstractMesh));
  27383. BABYLON.Mesh = Mesh;
  27384. })(BABYLON || (BABYLON = {}));
  27385. //# sourceMappingURL=babylon.mesh.js.map
  27386. var BABYLON;
  27387. (function (BABYLON) {
  27388. var BaseSubMesh = /** @class */ (function () {
  27389. function BaseSubMesh() {
  27390. }
  27391. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  27392. get: function () {
  27393. return this._materialEffect;
  27394. },
  27395. enumerable: true,
  27396. configurable: true
  27397. });
  27398. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  27399. if (defines === void 0) { defines = null; }
  27400. if (this._materialEffect === effect) {
  27401. if (!effect) {
  27402. this._materialDefines = null;
  27403. }
  27404. return;
  27405. }
  27406. this._materialDefines = defines;
  27407. this._materialEffect = effect;
  27408. };
  27409. return BaseSubMesh;
  27410. }());
  27411. BABYLON.BaseSubMesh = BaseSubMesh;
  27412. var SubMesh = /** @class */ (function (_super) {
  27413. __extends(SubMesh, _super);
  27414. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  27415. if (createBoundingBox === void 0) { createBoundingBox = true; }
  27416. var _this = _super.call(this) || this;
  27417. _this.materialIndex = materialIndex;
  27418. _this.verticesStart = verticesStart;
  27419. _this.verticesCount = verticesCount;
  27420. _this.indexStart = indexStart;
  27421. _this.indexCount = indexCount;
  27422. _this._renderId = 0;
  27423. _this._mesh = mesh;
  27424. _this._renderingMesh = renderingMesh || mesh;
  27425. mesh.subMeshes.push(_this);
  27426. _this._trianglePlanes = [];
  27427. _this._id = mesh.subMeshes.length - 1;
  27428. if (createBoundingBox) {
  27429. _this.refreshBoundingInfo();
  27430. mesh.computeWorldMatrix(true);
  27431. }
  27432. return _this;
  27433. }
  27434. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  27435. if (createBoundingBox === void 0) { createBoundingBox = true; }
  27436. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  27437. };
  27438. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  27439. get: function () {
  27440. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  27441. },
  27442. enumerable: true,
  27443. configurable: true
  27444. });
  27445. /**
  27446. * Returns the submesh BoudingInfo object.
  27447. */
  27448. SubMesh.prototype.getBoundingInfo = function () {
  27449. if (this.IsGlobal) {
  27450. return this._mesh.getBoundingInfo();
  27451. }
  27452. return this._boundingInfo;
  27453. };
  27454. /**
  27455. * Sets the submesh BoundingInfo.
  27456. * Return the SubMesh.
  27457. */
  27458. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  27459. this._boundingInfo = boundingInfo;
  27460. return this;
  27461. };
  27462. /**
  27463. * Returns the mesh of the current submesh.
  27464. */
  27465. SubMesh.prototype.getMesh = function () {
  27466. return this._mesh;
  27467. };
  27468. /**
  27469. * Returns the rendering mesh of the submesh.
  27470. */
  27471. SubMesh.prototype.getRenderingMesh = function () {
  27472. return this._renderingMesh;
  27473. };
  27474. /**
  27475. * Returns the submesh material.
  27476. */
  27477. SubMesh.prototype.getMaterial = function () {
  27478. var rootMaterial = this._renderingMesh.material;
  27479. if (rootMaterial === null || rootMaterial === undefined) {
  27480. return this._mesh.getScene().defaultMaterial;
  27481. }
  27482. else if (rootMaterial.getSubMaterial) {
  27483. var multiMaterial = rootMaterial;
  27484. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  27485. if (this._currentMaterial !== effectiveMaterial) {
  27486. this._currentMaterial = effectiveMaterial;
  27487. this._materialDefines = null;
  27488. }
  27489. return effectiveMaterial;
  27490. }
  27491. return rootMaterial;
  27492. };
  27493. // Methods
  27494. /**
  27495. * Sets a new updated BoundingInfo object to the submesh.
  27496. * Returns the SubMesh.
  27497. */
  27498. SubMesh.prototype.refreshBoundingInfo = function () {
  27499. this._lastColliderWorldVertices = null;
  27500. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  27501. return this;
  27502. }
  27503. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27504. if (!data) {
  27505. this._boundingInfo = this._mesh.getBoundingInfo();
  27506. return this;
  27507. }
  27508. var indices = this._renderingMesh.getIndices();
  27509. var extend;
  27510. //is this the only submesh?
  27511. if (this.indexStart === 0 && this.indexCount === indices.length) {
  27512. var boundingInfo = this._renderingMesh.getBoundingInfo();
  27513. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  27514. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  27515. }
  27516. else {
  27517. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  27518. }
  27519. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27520. return this;
  27521. };
  27522. SubMesh.prototype._checkCollision = function (collider) {
  27523. var boundingInfo = this._renderingMesh.getBoundingInfo();
  27524. return boundingInfo._checkCollision(collider);
  27525. };
  27526. /**
  27527. * Updates the submesh BoundingInfo.
  27528. * Returns the Submesh.
  27529. */
  27530. SubMesh.prototype.updateBoundingInfo = function (world) {
  27531. var boundingInfo = this.getBoundingInfo();
  27532. if (!boundingInfo) {
  27533. this.refreshBoundingInfo();
  27534. boundingInfo = this.getBoundingInfo();
  27535. }
  27536. boundingInfo.update(world);
  27537. return this;
  27538. };
  27539. /**
  27540. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  27541. * Boolean returned.
  27542. */
  27543. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  27544. var boundingInfo = this.getBoundingInfo();
  27545. if (!boundingInfo) {
  27546. return false;
  27547. }
  27548. return boundingInfo.isInFrustum(frustumPlanes);
  27549. };
  27550. /**
  27551. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  27552. * Boolean returned.
  27553. */
  27554. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  27555. var boundingInfo = this.getBoundingInfo();
  27556. if (!boundingInfo) {
  27557. return false;
  27558. }
  27559. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  27560. };
  27561. /**
  27562. * Renders the submesh.
  27563. * Returns it.
  27564. */
  27565. SubMesh.prototype.render = function (enableAlphaMode) {
  27566. this._renderingMesh.render(this, enableAlphaMode);
  27567. return this;
  27568. };
  27569. /**
  27570. * Returns a new Index Buffer.
  27571. * Type returned : WebGLBuffer.
  27572. */
  27573. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  27574. if (!this._linesIndexBuffer) {
  27575. var linesIndices = [];
  27576. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  27577. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  27578. }
  27579. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  27580. this.linesIndexCount = linesIndices.length;
  27581. }
  27582. return this._linesIndexBuffer;
  27583. };
  27584. /**
  27585. * True is the passed Ray intersects the submesh bounding box.
  27586. * Boolean returned.
  27587. */
  27588. SubMesh.prototype.canIntersects = function (ray) {
  27589. var boundingInfo = this.getBoundingInfo();
  27590. if (!boundingInfo) {
  27591. return false;
  27592. }
  27593. return ray.intersectsBox(boundingInfo.boundingBox);
  27594. };
  27595. /**
  27596. * Returns an object IntersectionInfo.
  27597. */
  27598. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  27599. var intersectInfo = null;
  27600. // LineMesh first as it's also a Mesh...
  27601. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  27602. var lineMesh = this._mesh;
  27603. // Line test
  27604. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  27605. var p0 = positions[indices[index]];
  27606. var p1 = positions[indices[index + 1]];
  27607. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  27608. if (length < 0) {
  27609. continue;
  27610. }
  27611. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  27612. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  27613. if (fastCheck) {
  27614. break;
  27615. }
  27616. }
  27617. }
  27618. }
  27619. else {
  27620. // Triangles test
  27621. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  27622. var p0 = positions[indices[index]];
  27623. var p1 = positions[indices[index + 1]];
  27624. var p2 = positions[indices[index + 2]];
  27625. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  27626. if (currentIntersectInfo) {
  27627. if (currentIntersectInfo.distance < 0) {
  27628. continue;
  27629. }
  27630. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  27631. intersectInfo = currentIntersectInfo;
  27632. intersectInfo.faceId = index / 3;
  27633. if (fastCheck) {
  27634. break;
  27635. }
  27636. }
  27637. }
  27638. }
  27639. }
  27640. return intersectInfo;
  27641. };
  27642. SubMesh.prototype._rebuild = function () {
  27643. if (this._linesIndexBuffer) {
  27644. this._linesIndexBuffer = null;
  27645. }
  27646. };
  27647. // Clone
  27648. /**
  27649. * Creates a new Submesh from the passed Mesh.
  27650. */
  27651. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  27652. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  27653. if (!this.IsGlobal) {
  27654. var boundingInfo = this.getBoundingInfo();
  27655. if (!boundingInfo) {
  27656. return result;
  27657. }
  27658. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  27659. }
  27660. return result;
  27661. };
  27662. // Dispose
  27663. /**
  27664. * Disposes the Submesh.
  27665. * Returns nothing.
  27666. */
  27667. SubMesh.prototype.dispose = function () {
  27668. if (this._linesIndexBuffer) {
  27669. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  27670. this._linesIndexBuffer = null;
  27671. }
  27672. // Remove from mesh
  27673. var index = this._mesh.subMeshes.indexOf(this);
  27674. this._mesh.subMeshes.splice(index, 1);
  27675. };
  27676. // Statics
  27677. /**
  27678. * Creates a new Submesh from the passed parameters :
  27679. * - materialIndex (integer) : the index of the main mesh material.
  27680. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  27681. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  27682. * - mesh (Mesh) : the main mesh to create the submesh from.
  27683. * - renderingMesh (optional Mesh) : rendering mesh.
  27684. */
  27685. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  27686. var minVertexIndex = Number.MAX_VALUE;
  27687. var maxVertexIndex = -Number.MAX_VALUE;
  27688. renderingMesh = (renderingMesh || mesh);
  27689. var indices = renderingMesh.getIndices();
  27690. for (var index = startIndex; index < startIndex + indexCount; index++) {
  27691. var vertexIndex = indices[index];
  27692. if (vertexIndex < minVertexIndex)
  27693. minVertexIndex = vertexIndex;
  27694. if (vertexIndex > maxVertexIndex)
  27695. maxVertexIndex = vertexIndex;
  27696. }
  27697. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  27698. };
  27699. return SubMesh;
  27700. }(BaseSubMesh));
  27701. BABYLON.SubMesh = SubMesh;
  27702. })(BABYLON || (BABYLON = {}));
  27703. //# sourceMappingURL=babylon.subMesh.js.map
  27704. var __assign = (this && this.__assign) || Object.assign || function(t) {
  27705. for (var s, i = 1, n = arguments.length; i < n; i++) {
  27706. s = arguments[i];
  27707. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  27708. t[p] = s[p];
  27709. }
  27710. return t;
  27711. };
  27712. var BABYLON;
  27713. (function (BABYLON) {
  27714. var MaterialDefines = /** @class */ (function () {
  27715. function MaterialDefines() {
  27716. this._isDirty = true;
  27717. this._areLightsDirty = true;
  27718. this._areAttributesDirty = true;
  27719. this._areTexturesDirty = true;
  27720. this._areFresnelDirty = true;
  27721. this._areMiscDirty = true;
  27722. this._areImageProcessingDirty = true;
  27723. this._normals = false;
  27724. this._uvs = false;
  27725. this._needNormals = false;
  27726. this._needUVs = false;
  27727. }
  27728. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  27729. get: function () {
  27730. return this._isDirty;
  27731. },
  27732. enumerable: true,
  27733. configurable: true
  27734. });
  27735. MaterialDefines.prototype.markAsProcessed = function () {
  27736. this._isDirty = false;
  27737. this._areAttributesDirty = false;
  27738. this._areTexturesDirty = false;
  27739. this._areFresnelDirty = false;
  27740. this._areLightsDirty = false;
  27741. this._areMiscDirty = false;
  27742. this._areImageProcessingDirty = false;
  27743. };
  27744. MaterialDefines.prototype.markAsUnprocessed = function () {
  27745. this._isDirty = true;
  27746. };
  27747. MaterialDefines.prototype.markAllAsDirty = function () {
  27748. this._areTexturesDirty = true;
  27749. this._areAttributesDirty = true;
  27750. this._areLightsDirty = true;
  27751. this._areFresnelDirty = true;
  27752. this._areMiscDirty = true;
  27753. this._areImageProcessingDirty = true;
  27754. this._isDirty = true;
  27755. };
  27756. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  27757. this._areImageProcessingDirty = true;
  27758. this._isDirty = true;
  27759. };
  27760. MaterialDefines.prototype.markAsLightDirty = function () {
  27761. this._areLightsDirty = true;
  27762. this._isDirty = true;
  27763. };
  27764. MaterialDefines.prototype.markAsAttributesDirty = function () {
  27765. this._areAttributesDirty = true;
  27766. this._isDirty = true;
  27767. };
  27768. MaterialDefines.prototype.markAsTexturesDirty = function () {
  27769. this._areTexturesDirty = true;
  27770. this._isDirty = true;
  27771. };
  27772. MaterialDefines.prototype.markAsFresnelDirty = function () {
  27773. this._areFresnelDirty = true;
  27774. this._isDirty = true;
  27775. };
  27776. MaterialDefines.prototype.markAsMiscDirty = function () {
  27777. this._areMiscDirty = true;
  27778. this._isDirty = true;
  27779. };
  27780. MaterialDefines.prototype.rebuild = function () {
  27781. if (this._keys) {
  27782. delete this._keys;
  27783. }
  27784. this._keys = [];
  27785. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  27786. var key = _a[_i];
  27787. if (key[0] === "_") {
  27788. continue;
  27789. }
  27790. this._keys.push(key);
  27791. }
  27792. };
  27793. MaterialDefines.prototype.isEqual = function (other) {
  27794. if (this._keys.length !== other._keys.length) {
  27795. return false;
  27796. }
  27797. for (var index = 0; index < this._keys.length; index++) {
  27798. var prop = this._keys[index];
  27799. if (this[prop] !== other[prop]) {
  27800. return false;
  27801. }
  27802. }
  27803. return true;
  27804. };
  27805. MaterialDefines.prototype.cloneTo = function (other) {
  27806. if (this._keys.length !== other._keys.length) {
  27807. other._keys = this._keys.slice(0);
  27808. }
  27809. for (var index = 0; index < this._keys.length; index++) {
  27810. var prop = this._keys[index];
  27811. other[prop] = this[prop];
  27812. }
  27813. };
  27814. MaterialDefines.prototype.reset = function () {
  27815. for (var index = 0; index < this._keys.length; index++) {
  27816. var prop = this._keys[index];
  27817. if (typeof (this[prop]) === "number") {
  27818. this[prop] = 0;
  27819. }
  27820. else {
  27821. this[prop] = false;
  27822. }
  27823. }
  27824. };
  27825. MaterialDefines.prototype.toString = function () {
  27826. var result = "";
  27827. for (var index = 0; index < this._keys.length; index++) {
  27828. var prop = this._keys[index];
  27829. var value = this[prop];
  27830. if (typeof (value) === "number") {
  27831. result += "#define " + prop + " " + this[prop] + "\n";
  27832. }
  27833. else if (value) {
  27834. result += "#define " + prop + "\n";
  27835. }
  27836. }
  27837. return result;
  27838. };
  27839. return MaterialDefines;
  27840. }());
  27841. BABYLON.MaterialDefines = MaterialDefines;
  27842. var Material = /** @class */ (function () {
  27843. function Material(name, scene, doNotAdd) {
  27844. this.checkReadyOnEveryCall = false;
  27845. this.checkReadyOnlyOnce = false;
  27846. this.state = "";
  27847. this.alpha = 1.0;
  27848. this._backFaceCulling = true;
  27849. this.doNotSerialize = false;
  27850. this.storeEffectOnSubMeshes = false;
  27851. /**
  27852. * An event triggered when the material is disposed.
  27853. * @type {BABYLON.Observable}
  27854. */
  27855. this.onDisposeObservable = new BABYLON.Observable();
  27856. /**
  27857. * An event triggered when the material is bound.
  27858. * @type {BABYLON.Observable}
  27859. */
  27860. this.onBindObservable = new BABYLON.Observable();
  27861. /**
  27862. * An event triggered when the material is unbound.
  27863. * @type {BABYLON.Observable}
  27864. */
  27865. this.onUnBindObservable = new BABYLON.Observable();
  27866. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  27867. this._needDepthPrePass = false;
  27868. this.disableDepthWrite = false;
  27869. this.forceDepthWrite = false;
  27870. this.separateCullingPass = false;
  27871. this._fogEnabled = true;
  27872. this.pointSize = 1.0;
  27873. this.zOffset = 0;
  27874. this._wasPreviouslyReady = false;
  27875. this._fillMode = Material.TriangleFillMode;
  27876. this.name = name;
  27877. this.id = name || BABYLON.Tools.RandomId();
  27878. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  27879. if (this._scene.useRightHandedSystem) {
  27880. this.sideOrientation = Material.ClockWiseSideOrientation;
  27881. }
  27882. else {
  27883. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  27884. }
  27885. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  27886. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  27887. if (!doNotAdd) {
  27888. this._scene.materials.push(this);
  27889. }
  27890. }
  27891. Object.defineProperty(Material, "TriangleFillMode", {
  27892. get: function () {
  27893. return Material._TriangleFillMode;
  27894. },
  27895. enumerable: true,
  27896. configurable: true
  27897. });
  27898. Object.defineProperty(Material, "WireFrameFillMode", {
  27899. get: function () {
  27900. return Material._WireFrameFillMode;
  27901. },
  27902. enumerable: true,
  27903. configurable: true
  27904. });
  27905. Object.defineProperty(Material, "PointFillMode", {
  27906. get: function () {
  27907. return Material._PointFillMode;
  27908. },
  27909. enumerable: true,
  27910. configurable: true
  27911. });
  27912. Object.defineProperty(Material, "PointListDrawMode", {
  27913. get: function () {
  27914. return Material._PointListDrawMode;
  27915. },
  27916. enumerable: true,
  27917. configurable: true
  27918. });
  27919. Object.defineProperty(Material, "LineListDrawMode", {
  27920. get: function () {
  27921. return Material._LineListDrawMode;
  27922. },
  27923. enumerable: true,
  27924. configurable: true
  27925. });
  27926. Object.defineProperty(Material, "LineLoopDrawMode", {
  27927. get: function () {
  27928. return Material._LineLoopDrawMode;
  27929. },
  27930. enumerable: true,
  27931. configurable: true
  27932. });
  27933. Object.defineProperty(Material, "LineStripDrawMode", {
  27934. get: function () {
  27935. return Material._LineStripDrawMode;
  27936. },
  27937. enumerable: true,
  27938. configurable: true
  27939. });
  27940. Object.defineProperty(Material, "TriangleStripDrawMode", {
  27941. get: function () {
  27942. return Material._TriangleStripDrawMode;
  27943. },
  27944. enumerable: true,
  27945. configurable: true
  27946. });
  27947. Object.defineProperty(Material, "TriangleFanDrawMode", {
  27948. get: function () {
  27949. return Material._TriangleFanDrawMode;
  27950. },
  27951. enumerable: true,
  27952. configurable: true
  27953. });
  27954. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  27955. get: function () {
  27956. return Material._ClockWiseSideOrientation;
  27957. },
  27958. enumerable: true,
  27959. configurable: true
  27960. });
  27961. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  27962. get: function () {
  27963. return Material._CounterClockWiseSideOrientation;
  27964. },
  27965. enumerable: true,
  27966. configurable: true
  27967. });
  27968. Object.defineProperty(Material, "TextureDirtyFlag", {
  27969. get: function () {
  27970. return Material._TextureDirtyFlag;
  27971. },
  27972. enumerable: true,
  27973. configurable: true
  27974. });
  27975. Object.defineProperty(Material, "LightDirtyFlag", {
  27976. get: function () {
  27977. return Material._LightDirtyFlag;
  27978. },
  27979. enumerable: true,
  27980. configurable: true
  27981. });
  27982. Object.defineProperty(Material, "FresnelDirtyFlag", {
  27983. get: function () {
  27984. return Material._FresnelDirtyFlag;
  27985. },
  27986. enumerable: true,
  27987. configurable: true
  27988. });
  27989. Object.defineProperty(Material, "AttributesDirtyFlag", {
  27990. get: function () {
  27991. return Material._AttributesDirtyFlag;
  27992. },
  27993. enumerable: true,
  27994. configurable: true
  27995. });
  27996. Object.defineProperty(Material, "MiscDirtyFlag", {
  27997. get: function () {
  27998. return Material._MiscDirtyFlag;
  27999. },
  28000. enumerable: true,
  28001. configurable: true
  28002. });
  28003. Object.defineProperty(Material.prototype, "backFaceCulling", {
  28004. get: function () {
  28005. return this._backFaceCulling;
  28006. },
  28007. set: function (value) {
  28008. if (this._backFaceCulling === value) {
  28009. return;
  28010. }
  28011. this._backFaceCulling = value;
  28012. this.markAsDirty(Material.TextureDirtyFlag);
  28013. },
  28014. enumerable: true,
  28015. configurable: true
  28016. });
  28017. Object.defineProperty(Material.prototype, "onDispose", {
  28018. set: function (callback) {
  28019. if (this._onDisposeObserver) {
  28020. this.onDisposeObservable.remove(this._onDisposeObserver);
  28021. }
  28022. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28023. },
  28024. enumerable: true,
  28025. configurable: true
  28026. });
  28027. Object.defineProperty(Material.prototype, "onBind", {
  28028. set: function (callback) {
  28029. if (this._onBindObserver) {
  28030. this.onBindObservable.remove(this._onBindObserver);
  28031. }
  28032. this._onBindObserver = this.onBindObservable.add(callback);
  28033. },
  28034. enumerable: true,
  28035. configurable: true
  28036. });
  28037. Object.defineProperty(Material.prototype, "alphaMode", {
  28038. get: function () {
  28039. return this._alphaMode;
  28040. },
  28041. set: function (value) {
  28042. if (this._alphaMode === value) {
  28043. return;
  28044. }
  28045. this._alphaMode = value;
  28046. this.markAsDirty(Material.TextureDirtyFlag);
  28047. },
  28048. enumerable: true,
  28049. configurable: true
  28050. });
  28051. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  28052. get: function () {
  28053. return this._needDepthPrePass;
  28054. },
  28055. set: function (value) {
  28056. if (this._needDepthPrePass === value) {
  28057. return;
  28058. }
  28059. this._needDepthPrePass = value;
  28060. if (this._needDepthPrePass) {
  28061. this.checkReadyOnEveryCall = true;
  28062. }
  28063. },
  28064. enumerable: true,
  28065. configurable: true
  28066. });
  28067. Object.defineProperty(Material.prototype, "fogEnabled", {
  28068. get: function () {
  28069. return this._fogEnabled;
  28070. },
  28071. set: function (value) {
  28072. if (this._fogEnabled === value) {
  28073. return;
  28074. }
  28075. this._fogEnabled = value;
  28076. this.markAsDirty(Material.MiscDirtyFlag);
  28077. },
  28078. enumerable: true,
  28079. configurable: true
  28080. });
  28081. Object.defineProperty(Material.prototype, "wireframe", {
  28082. get: function () {
  28083. return this._fillMode === Material.WireFrameFillMode;
  28084. },
  28085. set: function (value) {
  28086. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  28087. },
  28088. enumerable: true,
  28089. configurable: true
  28090. });
  28091. Object.defineProperty(Material.prototype, "pointsCloud", {
  28092. get: function () {
  28093. return this._fillMode === Material.PointFillMode;
  28094. },
  28095. set: function (value) {
  28096. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  28097. },
  28098. enumerable: true,
  28099. configurable: true
  28100. });
  28101. Object.defineProperty(Material.prototype, "fillMode", {
  28102. get: function () {
  28103. return this._fillMode;
  28104. },
  28105. set: function (value) {
  28106. if (this._fillMode === value) {
  28107. return;
  28108. }
  28109. this._fillMode = value;
  28110. this.markAsDirty(Material.MiscDirtyFlag);
  28111. },
  28112. enumerable: true,
  28113. configurable: true
  28114. });
  28115. /**
  28116. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28117. * subclasses should override adding information pertainent to themselves
  28118. */
  28119. Material.prototype.toString = function (fullDetails) {
  28120. var ret = "Name: " + this.name;
  28121. if (fullDetails) {
  28122. }
  28123. return ret;
  28124. };
  28125. /**
  28126. * Child classes can use it to update shaders
  28127. */
  28128. Material.prototype.getClassName = function () {
  28129. return "Material";
  28130. };
  28131. Object.defineProperty(Material.prototype, "isFrozen", {
  28132. get: function () {
  28133. return this.checkReadyOnlyOnce;
  28134. },
  28135. enumerable: true,
  28136. configurable: true
  28137. });
  28138. Material.prototype.freeze = function () {
  28139. this.checkReadyOnlyOnce = true;
  28140. };
  28141. Material.prototype.unfreeze = function () {
  28142. this.checkReadyOnlyOnce = false;
  28143. };
  28144. Material.prototype.isReady = function (mesh, useInstances) {
  28145. return true;
  28146. };
  28147. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  28148. return false;
  28149. };
  28150. Material.prototype.getEffect = function () {
  28151. return this._effect;
  28152. };
  28153. Material.prototype.getScene = function () {
  28154. return this._scene;
  28155. };
  28156. Material.prototype.needAlphaBlending = function () {
  28157. return (this.alpha < 1.0);
  28158. };
  28159. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  28160. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  28161. };
  28162. Material.prototype.needAlphaTesting = function () {
  28163. return false;
  28164. };
  28165. Material.prototype.getAlphaTestTexture = function () {
  28166. return null;
  28167. };
  28168. Material.prototype.markDirty = function () {
  28169. this._wasPreviouslyReady = false;
  28170. };
  28171. Material.prototype._preBind = function (effect, overrideOrientation) {
  28172. if (overrideOrientation === void 0) { overrideOrientation = null; }
  28173. var engine = this._scene.getEngine();
  28174. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  28175. var reverse = orientation === Material.ClockWiseSideOrientation;
  28176. engine.enableEffect(effect ? effect : this._effect);
  28177. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  28178. return reverse;
  28179. };
  28180. Material.prototype.bind = function (world, mesh) {
  28181. };
  28182. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  28183. };
  28184. Material.prototype.bindOnlyWorldMatrix = function (world) {
  28185. };
  28186. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  28187. sceneUbo.bindToEffect(effect, "Scene");
  28188. };
  28189. Material.prototype.bindView = function (effect) {
  28190. if (!this._useUBO) {
  28191. effect.setMatrix("view", this.getScene().getViewMatrix());
  28192. }
  28193. else {
  28194. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  28195. }
  28196. };
  28197. Material.prototype.bindViewProjection = function (effect) {
  28198. if (!this._useUBO) {
  28199. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  28200. }
  28201. else {
  28202. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  28203. }
  28204. };
  28205. Material.prototype._afterBind = function (mesh) {
  28206. this._scene._cachedMaterial = this;
  28207. if (mesh) {
  28208. this._scene._cachedVisibility = mesh.visibility;
  28209. }
  28210. else {
  28211. this._scene._cachedVisibility = 1;
  28212. }
  28213. if (mesh) {
  28214. this.onBindObservable.notifyObservers(mesh);
  28215. }
  28216. if (this.disableDepthWrite) {
  28217. var engine = this._scene.getEngine();
  28218. this._cachedDepthWriteState = engine.getDepthWrite();
  28219. engine.setDepthWrite(false);
  28220. }
  28221. };
  28222. Material.prototype.unbind = function () {
  28223. this.onUnBindObservable.notifyObservers(this);
  28224. if (this.disableDepthWrite) {
  28225. var engine = this._scene.getEngine();
  28226. engine.setDepthWrite(this._cachedDepthWriteState);
  28227. }
  28228. };
  28229. Material.prototype.getActiveTextures = function () {
  28230. return [];
  28231. };
  28232. Material.prototype.hasTexture = function (texture) {
  28233. return false;
  28234. };
  28235. Material.prototype.clone = function (name) {
  28236. return null;
  28237. };
  28238. Material.prototype.getBindedMeshes = function () {
  28239. var result = new Array();
  28240. for (var index = 0; index < this._scene.meshes.length; index++) {
  28241. var mesh = this._scene.meshes[index];
  28242. if (mesh.material === this) {
  28243. result.push(mesh);
  28244. }
  28245. }
  28246. return result;
  28247. };
  28248. /**
  28249. * Force shader compilation including textures ready check
  28250. */
  28251. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  28252. var _this = this;
  28253. var localOptions = __assign({ alphaTest: null, clipPlane: false }, options);
  28254. var subMesh = new BABYLON.BaseSubMesh();
  28255. var scene = this.getScene();
  28256. var engine = scene.getEngine();
  28257. var checkReady = function () {
  28258. if (!_this._scene || !_this._scene.getEngine()) {
  28259. return;
  28260. }
  28261. if (subMesh._materialDefines) {
  28262. subMesh._materialDefines._renderId = -1;
  28263. }
  28264. var alphaTestState = engine.getAlphaTesting();
  28265. var clipPlaneState = scene.clipPlane;
  28266. engine.setAlphaTesting(localOptions.alphaTest || (!_this.needAlphaBlendingForMesh(mesh) && _this.needAlphaTesting()));
  28267. if (localOptions.clipPlane) {
  28268. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  28269. }
  28270. if (_this.storeEffectOnSubMeshes) {
  28271. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  28272. if (onCompiled) {
  28273. onCompiled(_this);
  28274. }
  28275. }
  28276. else {
  28277. setTimeout(checkReady, 16);
  28278. }
  28279. }
  28280. else {
  28281. if (_this.isReady(mesh)) {
  28282. if (onCompiled) {
  28283. onCompiled(_this);
  28284. }
  28285. }
  28286. else {
  28287. setTimeout(checkReady, 16);
  28288. }
  28289. }
  28290. engine.setAlphaTesting(alphaTestState);
  28291. if (options && options.clipPlane) {
  28292. scene.clipPlane = clipPlaneState;
  28293. }
  28294. };
  28295. checkReady();
  28296. };
  28297. Material.prototype.markAsDirty = function (flag) {
  28298. if (flag & Material.TextureDirtyFlag) {
  28299. this._markAllSubMeshesAsTexturesDirty();
  28300. }
  28301. if (flag & Material.LightDirtyFlag) {
  28302. this._markAllSubMeshesAsLightsDirty();
  28303. }
  28304. if (flag & Material.FresnelDirtyFlag) {
  28305. this._markAllSubMeshesAsFresnelDirty();
  28306. }
  28307. if (flag & Material.AttributesDirtyFlag) {
  28308. this._markAllSubMeshesAsAttributesDirty();
  28309. }
  28310. if (flag & Material.MiscDirtyFlag) {
  28311. this._markAllSubMeshesAsMiscDirty();
  28312. }
  28313. this.getScene().resetCachedMaterial();
  28314. };
  28315. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  28316. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  28317. var mesh = _a[_i];
  28318. if (!mesh.subMeshes) {
  28319. continue;
  28320. }
  28321. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  28322. var subMesh = _c[_b];
  28323. if (subMesh.getMaterial() !== this) {
  28324. continue;
  28325. }
  28326. if (!subMesh._materialDefines) {
  28327. continue;
  28328. }
  28329. func(subMesh._materialDefines);
  28330. }
  28331. }
  28332. };
  28333. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  28334. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  28335. };
  28336. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  28337. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  28338. };
  28339. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  28340. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  28341. };
  28342. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  28343. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  28344. };
  28345. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  28346. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  28347. };
  28348. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  28349. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  28350. };
  28351. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  28352. // Animations
  28353. this.getScene().stopAnimation(this);
  28354. // Remove from scene
  28355. var index = this._scene.materials.indexOf(this);
  28356. if (index >= 0) {
  28357. this._scene.materials.splice(index, 1);
  28358. }
  28359. // Remove from meshes
  28360. for (index = 0; index < this._scene.meshes.length; index++) {
  28361. var mesh = this._scene.meshes[index];
  28362. if (mesh.material === this) {
  28363. mesh.material = null;
  28364. if (mesh.geometry) {
  28365. var geometry = (mesh.geometry);
  28366. if (this.storeEffectOnSubMeshes) {
  28367. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  28368. var subMesh = _a[_i];
  28369. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  28370. if (forceDisposeEffect && subMesh._materialEffect) {
  28371. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  28372. }
  28373. }
  28374. }
  28375. else {
  28376. geometry._releaseVertexArrayObject(this._effect);
  28377. }
  28378. }
  28379. }
  28380. }
  28381. this._uniformBuffer.dispose();
  28382. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  28383. if (forceDisposeEffect && this._effect) {
  28384. if (!this.storeEffectOnSubMeshes) {
  28385. this._scene.getEngine()._releaseEffect(this._effect);
  28386. }
  28387. this._effect = null;
  28388. }
  28389. // Callback
  28390. this.onDisposeObservable.notifyObservers(this);
  28391. this.onDisposeObservable.clear();
  28392. this.onBindObservable.clear();
  28393. this.onUnBindObservable.clear();
  28394. };
  28395. Material.prototype.serialize = function () {
  28396. return BABYLON.SerializationHelper.Serialize(this);
  28397. };
  28398. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  28399. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  28400. multiMaterial.id = parsedMultiMaterial.id;
  28401. if (BABYLON.Tags) {
  28402. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  28403. }
  28404. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  28405. var subMatId = parsedMultiMaterial.materials[matIndex];
  28406. if (subMatId) {
  28407. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  28408. }
  28409. else {
  28410. multiMaterial.subMaterials.push(null);
  28411. }
  28412. }
  28413. return multiMaterial;
  28414. };
  28415. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  28416. if (!parsedMaterial.customType) {
  28417. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  28418. }
  28419. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  28420. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  28421. if (!BABYLON.LegacyPBRMaterial) {
  28422. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  28423. return;
  28424. }
  28425. }
  28426. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  28427. return materialType.Parse(parsedMaterial, scene, rootUrl);
  28428. ;
  28429. };
  28430. // Triangle views
  28431. Material._TriangleFillMode = 0;
  28432. Material._WireFrameFillMode = 1;
  28433. Material._PointFillMode = 2;
  28434. // Draw modes
  28435. Material._PointListDrawMode = 3;
  28436. Material._LineListDrawMode = 4;
  28437. Material._LineLoopDrawMode = 5;
  28438. Material._LineStripDrawMode = 6;
  28439. Material._TriangleStripDrawMode = 7;
  28440. Material._TriangleFanDrawMode = 8;
  28441. Material._ClockWiseSideOrientation = 0;
  28442. Material._CounterClockWiseSideOrientation = 1;
  28443. Material._TextureDirtyFlag = 1;
  28444. Material._LightDirtyFlag = 2;
  28445. Material._FresnelDirtyFlag = 4;
  28446. Material._AttributesDirtyFlag = 8;
  28447. Material._MiscDirtyFlag = 16;
  28448. __decorate([
  28449. BABYLON.serialize()
  28450. ], Material.prototype, "id", void 0);
  28451. __decorate([
  28452. BABYLON.serialize()
  28453. ], Material.prototype, "name", void 0);
  28454. __decorate([
  28455. BABYLON.serialize()
  28456. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  28457. __decorate([
  28458. BABYLON.serialize()
  28459. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  28460. __decorate([
  28461. BABYLON.serialize()
  28462. ], Material.prototype, "state", void 0);
  28463. __decorate([
  28464. BABYLON.serialize()
  28465. ], Material.prototype, "alpha", void 0);
  28466. __decorate([
  28467. BABYLON.serialize("backFaceCulling")
  28468. ], Material.prototype, "_backFaceCulling", void 0);
  28469. __decorate([
  28470. BABYLON.serialize()
  28471. ], Material.prototype, "sideOrientation", void 0);
  28472. __decorate([
  28473. BABYLON.serialize("alphaMode")
  28474. ], Material.prototype, "_alphaMode", void 0);
  28475. __decorate([
  28476. BABYLON.serialize()
  28477. ], Material.prototype, "_needDepthPrePass", void 0);
  28478. __decorate([
  28479. BABYLON.serialize()
  28480. ], Material.prototype, "disableDepthWrite", void 0);
  28481. __decorate([
  28482. BABYLON.serialize()
  28483. ], Material.prototype, "forceDepthWrite", void 0);
  28484. __decorate([
  28485. BABYLON.serialize()
  28486. ], Material.prototype, "separateCullingPass", void 0);
  28487. __decorate([
  28488. BABYLON.serialize("fogEnabled")
  28489. ], Material.prototype, "_fogEnabled", void 0);
  28490. __decorate([
  28491. BABYLON.serialize()
  28492. ], Material.prototype, "pointSize", void 0);
  28493. __decorate([
  28494. BABYLON.serialize()
  28495. ], Material.prototype, "zOffset", void 0);
  28496. __decorate([
  28497. BABYLON.serialize()
  28498. ], Material.prototype, "wireframe", null);
  28499. __decorate([
  28500. BABYLON.serialize()
  28501. ], Material.prototype, "pointsCloud", null);
  28502. __decorate([
  28503. BABYLON.serialize()
  28504. ], Material.prototype, "fillMode", null);
  28505. return Material;
  28506. }());
  28507. BABYLON.Material = Material;
  28508. })(BABYLON || (BABYLON = {}));
  28509. //# sourceMappingURL=babylon.material.js.map
  28510. var BABYLON;
  28511. (function (BABYLON) {
  28512. var UniformBuffer = /** @class */ (function () {
  28513. /**
  28514. * Uniform buffer objects.
  28515. *
  28516. * Handles blocks of uniform on the GPU.
  28517. *
  28518. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  28519. *
  28520. * For more information, please refer to :
  28521. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  28522. */
  28523. function UniformBuffer(engine, data, dynamic) {
  28524. this._engine = engine;
  28525. this._noUBO = !engine.supportsUniformBuffers;
  28526. this._dynamic = dynamic;
  28527. this._data = data || [];
  28528. this._uniformLocations = {};
  28529. this._uniformSizes = {};
  28530. this._uniformLocationPointer = 0;
  28531. this._needSync = false;
  28532. if (this._noUBO) {
  28533. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  28534. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  28535. this.updateFloat = this._updateFloatForEffect;
  28536. this.updateFloat2 = this._updateFloat2ForEffect;
  28537. this.updateFloat3 = this._updateFloat3ForEffect;
  28538. this.updateFloat4 = this._updateFloat4ForEffect;
  28539. this.updateMatrix = this._updateMatrixForEffect;
  28540. this.updateVector3 = this._updateVector3ForEffect;
  28541. this.updateVector4 = this._updateVector4ForEffect;
  28542. this.updateColor3 = this._updateColor3ForEffect;
  28543. this.updateColor4 = this._updateColor4ForEffect;
  28544. }
  28545. else {
  28546. this._engine._uniformBuffers.push(this);
  28547. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  28548. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  28549. this.updateFloat = this._updateFloatForUniform;
  28550. this.updateFloat2 = this._updateFloat2ForUniform;
  28551. this.updateFloat3 = this._updateFloat3ForUniform;
  28552. this.updateFloat4 = this._updateFloat4ForUniform;
  28553. this.updateMatrix = this._updateMatrixForUniform;
  28554. this.updateVector3 = this._updateVector3ForUniform;
  28555. this.updateVector4 = this._updateVector4ForUniform;
  28556. this.updateColor3 = this._updateColor3ForUniform;
  28557. this.updateColor4 = this._updateColor4ForUniform;
  28558. }
  28559. }
  28560. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  28561. // Properties
  28562. /**
  28563. * Indicates if the buffer is using the WebGL2 UBO implementation,
  28564. * or just falling back on setUniformXXX calls.
  28565. */
  28566. get: function () {
  28567. return !this._noUBO;
  28568. },
  28569. enumerable: true,
  28570. configurable: true
  28571. });
  28572. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  28573. /**
  28574. * Indicates if the WebGL underlying uniform buffer is in sync
  28575. * with the javascript cache data.
  28576. */
  28577. get: function () {
  28578. return !this._needSync;
  28579. },
  28580. enumerable: true,
  28581. configurable: true
  28582. });
  28583. /**
  28584. * Indicates if the WebGL underlying uniform buffer is dynamic.
  28585. * Also, a dynamic UniformBuffer will disable cache verification and always
  28586. * update the underlying WebGL uniform buffer to the GPU.
  28587. */
  28588. UniformBuffer.prototype.isDynamic = function () {
  28589. return this._dynamic !== undefined;
  28590. };
  28591. /**
  28592. * The data cache on JS side.
  28593. */
  28594. UniformBuffer.prototype.getData = function () {
  28595. return this._bufferData;
  28596. };
  28597. /**
  28598. * The underlying WebGL Uniform buffer.
  28599. */
  28600. UniformBuffer.prototype.getBuffer = function () {
  28601. return this._buffer;
  28602. };
  28603. /**
  28604. * std140 layout specifies how to align data within an UBO structure.
  28605. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  28606. * for specs.
  28607. */
  28608. UniformBuffer.prototype._fillAlignment = function (size) {
  28609. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  28610. // and 4x4 matrices
  28611. // TODO : change if other types are used
  28612. var alignment;
  28613. if (size <= 2) {
  28614. alignment = size;
  28615. }
  28616. else {
  28617. alignment = 4;
  28618. }
  28619. if ((this._uniformLocationPointer % alignment) !== 0) {
  28620. var oldPointer = this._uniformLocationPointer;
  28621. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  28622. var diff = this._uniformLocationPointer - oldPointer;
  28623. for (var i = 0; i < diff; i++) {
  28624. this._data.push(0);
  28625. }
  28626. }
  28627. };
  28628. /**
  28629. * Adds an uniform in the buffer.
  28630. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  28631. * for the layout to be correct !
  28632. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28633. * @param {number|number[]} size Data size, or data directly.
  28634. */
  28635. UniformBuffer.prototype.addUniform = function (name, size) {
  28636. if (this._noUBO) {
  28637. return;
  28638. }
  28639. if (this._uniformLocations[name] !== undefined) {
  28640. // Already existing uniform
  28641. return;
  28642. }
  28643. // This function must be called in the order of the shader layout !
  28644. // size can be the size of the uniform, or data directly
  28645. var data;
  28646. if (size instanceof Array) {
  28647. data = size;
  28648. size = data.length;
  28649. }
  28650. else {
  28651. size = size;
  28652. data = [];
  28653. // Fill with zeros
  28654. for (var i = 0; i < size; i++) {
  28655. data.push(0);
  28656. }
  28657. }
  28658. this._fillAlignment(size);
  28659. this._uniformSizes[name] = size;
  28660. this._uniformLocations[name] = this._uniformLocationPointer;
  28661. this._uniformLocationPointer += size;
  28662. for (var i = 0; i < size; i++) {
  28663. this._data.push(data[i]);
  28664. }
  28665. this._needSync = true;
  28666. };
  28667. /**
  28668. * Wrapper for addUniform.
  28669. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28670. * @param {Matrix} mat A 4x4 matrix.
  28671. */
  28672. UniformBuffer.prototype.addMatrix = function (name, mat) {
  28673. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  28674. };
  28675. /**
  28676. * Wrapper for addUniform.
  28677. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28678. * @param {number} x
  28679. * @param {number} y
  28680. */
  28681. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  28682. var temp = [x, y];
  28683. this.addUniform(name, temp);
  28684. };
  28685. /**
  28686. * Wrapper for addUniform.
  28687. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28688. * @param {number} x
  28689. * @param {number} y
  28690. * @param {number} z
  28691. */
  28692. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  28693. var temp = [x, y, z];
  28694. this.addUniform(name, temp);
  28695. };
  28696. /**
  28697. * Wrapper for addUniform.
  28698. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28699. * @param {Color3} color
  28700. */
  28701. UniformBuffer.prototype.addColor3 = function (name, color) {
  28702. var temp = new Array();
  28703. color.toArray(temp);
  28704. this.addUniform(name, temp);
  28705. };
  28706. /**
  28707. * Wrapper for addUniform.
  28708. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28709. * @param {Color3} color
  28710. * @param {number} alpha
  28711. */
  28712. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  28713. var temp = new Array();
  28714. color.toArray(temp);
  28715. temp.push(alpha);
  28716. this.addUniform(name, temp);
  28717. };
  28718. /**
  28719. * Wrapper for addUniform.
  28720. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28721. * @param {Vector3} vector
  28722. */
  28723. UniformBuffer.prototype.addVector3 = function (name, vector) {
  28724. var temp = new Array();
  28725. vector.toArray(temp);
  28726. this.addUniform(name, temp);
  28727. };
  28728. /**
  28729. * Wrapper for addUniform.
  28730. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28731. */
  28732. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  28733. this.addUniform(name, 12);
  28734. };
  28735. /**
  28736. * Wrapper for addUniform.
  28737. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28738. */
  28739. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  28740. this.addUniform(name, 8);
  28741. };
  28742. /**
  28743. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  28744. */
  28745. UniformBuffer.prototype.create = function () {
  28746. if (this._noUBO) {
  28747. return;
  28748. }
  28749. if (this._buffer) {
  28750. return; // nothing to do
  28751. }
  28752. // See spec, alignment must be filled as a vec4
  28753. this._fillAlignment(4);
  28754. this._bufferData = new Float32Array(this._data);
  28755. this._rebuild();
  28756. this._needSync = true;
  28757. };
  28758. UniformBuffer.prototype._rebuild = function () {
  28759. if (this._noUBO) {
  28760. return;
  28761. }
  28762. if (this._dynamic) {
  28763. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  28764. }
  28765. else {
  28766. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  28767. }
  28768. };
  28769. /**
  28770. * Updates the WebGL Uniform Buffer on the GPU.
  28771. * If the `dynamic` flag is set to true, no cache comparison is done.
  28772. * Otherwise, the buffer will be updated only if the cache differs.
  28773. */
  28774. UniformBuffer.prototype.update = function () {
  28775. if (!this._buffer) {
  28776. this.create();
  28777. return;
  28778. }
  28779. if (!this._dynamic && !this._needSync) {
  28780. return;
  28781. }
  28782. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  28783. this._needSync = false;
  28784. };
  28785. /**
  28786. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  28787. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  28788. * @param {number[]|Float32Array} data Flattened data
  28789. * @param {number} size Size of the data.
  28790. */
  28791. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  28792. var location = this._uniformLocations[uniformName];
  28793. if (location === undefined) {
  28794. if (this._buffer) {
  28795. // Cannot add an uniform if the buffer is already created
  28796. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  28797. return;
  28798. }
  28799. this.addUniform(uniformName, size);
  28800. location = this._uniformLocations[uniformName];
  28801. }
  28802. if (!this._buffer) {
  28803. this.create();
  28804. }
  28805. if (!this._dynamic) {
  28806. // Cache for static uniform buffers
  28807. var changed = false;
  28808. for (var i = 0; i < size; i++) {
  28809. if (this._bufferData[location + i] !== data[i]) {
  28810. changed = true;
  28811. this._bufferData[location + i] = data[i];
  28812. }
  28813. }
  28814. this._needSync = this._needSync || changed;
  28815. }
  28816. else {
  28817. // No cache for dynamic
  28818. for (var i = 0; i < size; i++) {
  28819. this._bufferData[location + i] = data[i];
  28820. }
  28821. }
  28822. };
  28823. // Update methods
  28824. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  28825. // To match std140, matrix must be realigned
  28826. for (var i = 0; i < 3; i++) {
  28827. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  28828. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  28829. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  28830. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  28831. }
  28832. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  28833. };
  28834. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  28835. this._currentEffect.setMatrix3x3(name, matrix);
  28836. };
  28837. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  28838. this._currentEffect.setMatrix2x2(name, matrix);
  28839. };
  28840. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  28841. // To match std140, matrix must be realigned
  28842. for (var i = 0; i < 2; i++) {
  28843. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  28844. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  28845. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  28846. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  28847. }
  28848. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  28849. };
  28850. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  28851. this._currentEffect.setFloat(name, x);
  28852. };
  28853. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  28854. UniformBuffer._tempBuffer[0] = x;
  28855. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  28856. };
  28857. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  28858. if (suffix === void 0) { suffix = ""; }
  28859. this._currentEffect.setFloat2(name + suffix, x, y);
  28860. };
  28861. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  28862. if (suffix === void 0) { suffix = ""; }
  28863. UniformBuffer._tempBuffer[0] = x;
  28864. UniformBuffer._tempBuffer[1] = y;
  28865. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  28866. };
  28867. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  28868. if (suffix === void 0) { suffix = ""; }
  28869. this._currentEffect.setFloat3(name + suffix, x, y, z);
  28870. };
  28871. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  28872. if (suffix === void 0) { suffix = ""; }
  28873. UniformBuffer._tempBuffer[0] = x;
  28874. UniformBuffer._tempBuffer[1] = y;
  28875. UniformBuffer._tempBuffer[2] = z;
  28876. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28877. };
  28878. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  28879. if (suffix === void 0) { suffix = ""; }
  28880. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  28881. };
  28882. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  28883. if (suffix === void 0) { suffix = ""; }
  28884. UniformBuffer._tempBuffer[0] = x;
  28885. UniformBuffer._tempBuffer[1] = y;
  28886. UniformBuffer._tempBuffer[2] = z;
  28887. UniformBuffer._tempBuffer[3] = w;
  28888. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28889. };
  28890. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  28891. this._currentEffect.setMatrix(name, mat);
  28892. };
  28893. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  28894. this.updateUniform(name, mat.toArray(), 16);
  28895. };
  28896. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  28897. this._currentEffect.setVector3(name, vector);
  28898. };
  28899. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  28900. vector.toArray(UniformBuffer._tempBuffer);
  28901. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28902. };
  28903. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  28904. this._currentEffect.setVector4(name, vector);
  28905. };
  28906. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  28907. vector.toArray(UniformBuffer._tempBuffer);
  28908. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28909. };
  28910. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  28911. if (suffix === void 0) { suffix = ""; }
  28912. this._currentEffect.setColor3(name + suffix, color);
  28913. };
  28914. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  28915. if (suffix === void 0) { suffix = ""; }
  28916. color.toArray(UniformBuffer._tempBuffer);
  28917. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28918. };
  28919. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  28920. if (suffix === void 0) { suffix = ""; }
  28921. this._currentEffect.setColor4(name + suffix, color, alpha);
  28922. };
  28923. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  28924. if (suffix === void 0) { suffix = ""; }
  28925. color.toArray(UniformBuffer._tempBuffer);
  28926. UniformBuffer._tempBuffer[3] = alpha;
  28927. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28928. };
  28929. /**
  28930. * Sets a sampler uniform on the effect.
  28931. * @param {string} name Name of the sampler.
  28932. * @param {Texture} texture
  28933. */
  28934. UniformBuffer.prototype.setTexture = function (name, texture) {
  28935. this._currentEffect.setTexture(name, texture);
  28936. };
  28937. /**
  28938. * Directly updates the value of the uniform in the cache AND on the GPU.
  28939. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  28940. * @param {number[]|Float32Array} data Flattened data
  28941. */
  28942. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  28943. this.updateUniform(uniformName, data, data.length);
  28944. this.update();
  28945. };
  28946. /**
  28947. * Binds this uniform buffer to an effect.
  28948. * @param {Effect} effect
  28949. * @param {string} name Name of the uniform block in the shader.
  28950. */
  28951. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  28952. this._currentEffect = effect;
  28953. if (this._noUBO || !this._buffer) {
  28954. return;
  28955. }
  28956. effect.bindUniformBuffer(this._buffer, name);
  28957. };
  28958. /**
  28959. * Disposes the uniform buffer.
  28960. */
  28961. UniformBuffer.prototype.dispose = function () {
  28962. if (this._noUBO) {
  28963. return;
  28964. }
  28965. var index = this._engine._uniformBuffers.indexOf(this);
  28966. if (index !== -1) {
  28967. this._engine._uniformBuffers.splice(index, 1);
  28968. }
  28969. if (!this._buffer) {
  28970. return;
  28971. }
  28972. if (this._engine._releaseBuffer(this._buffer)) {
  28973. this._buffer = null;
  28974. }
  28975. };
  28976. // Pool for avoiding memory leaks
  28977. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  28978. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  28979. return UniformBuffer;
  28980. }());
  28981. BABYLON.UniformBuffer = UniformBuffer;
  28982. })(BABYLON || (BABYLON = {}));
  28983. //# sourceMappingURL=babylon.uniformBuffer.js.map
  28984. var BABYLON;
  28985. (function (BABYLON) {
  28986. var VertexData = /** @class */ (function () {
  28987. function VertexData() {
  28988. }
  28989. VertexData.prototype.set = function (data, kind) {
  28990. switch (kind) {
  28991. case BABYLON.VertexBuffer.PositionKind:
  28992. this.positions = data;
  28993. break;
  28994. case BABYLON.VertexBuffer.NormalKind:
  28995. this.normals = data;
  28996. break;
  28997. case BABYLON.VertexBuffer.TangentKind:
  28998. this.tangents = data;
  28999. break;
  29000. case BABYLON.VertexBuffer.UVKind:
  29001. this.uvs = data;
  29002. break;
  29003. case BABYLON.VertexBuffer.UV2Kind:
  29004. this.uvs2 = data;
  29005. break;
  29006. case BABYLON.VertexBuffer.UV3Kind:
  29007. this.uvs3 = data;
  29008. break;
  29009. case BABYLON.VertexBuffer.UV4Kind:
  29010. this.uvs4 = data;
  29011. break;
  29012. case BABYLON.VertexBuffer.UV5Kind:
  29013. this.uvs5 = data;
  29014. break;
  29015. case BABYLON.VertexBuffer.UV6Kind:
  29016. this.uvs6 = data;
  29017. break;
  29018. case BABYLON.VertexBuffer.ColorKind:
  29019. this.colors = data;
  29020. break;
  29021. case BABYLON.VertexBuffer.MatricesIndicesKind:
  29022. this.matricesIndices = data;
  29023. break;
  29024. case BABYLON.VertexBuffer.MatricesWeightsKind:
  29025. this.matricesWeights = data;
  29026. break;
  29027. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  29028. this.matricesIndicesExtra = data;
  29029. break;
  29030. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  29031. this.matricesWeightsExtra = data;
  29032. break;
  29033. }
  29034. };
  29035. /**
  29036. * Associates the vertexData to the passed Mesh.
  29037. * Sets it as updatable or not (default `false`).
  29038. * Returns the VertexData.
  29039. */
  29040. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  29041. this._applyTo(mesh, updatable);
  29042. return this;
  29043. };
  29044. /**
  29045. * Associates the vertexData to the passed Geometry.
  29046. * Sets it as updatable or not (default `false`).
  29047. * Returns the VertexData.
  29048. */
  29049. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  29050. this._applyTo(geometry, updatable);
  29051. return this;
  29052. };
  29053. /**
  29054. * Updates the associated mesh.
  29055. * Returns the VertexData.
  29056. */
  29057. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  29058. this._update(mesh);
  29059. return this;
  29060. };
  29061. /**
  29062. * Updates the associated geometry.
  29063. * Returns the VertexData.
  29064. */
  29065. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  29066. this._update(geometry);
  29067. return this;
  29068. };
  29069. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  29070. if (updatable === void 0) { updatable = false; }
  29071. if (this.positions) {
  29072. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  29073. }
  29074. if (this.normals) {
  29075. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  29076. }
  29077. if (this.tangents) {
  29078. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  29079. }
  29080. if (this.uvs) {
  29081. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  29082. }
  29083. if (this.uvs2) {
  29084. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  29085. }
  29086. if (this.uvs3) {
  29087. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  29088. }
  29089. if (this.uvs4) {
  29090. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  29091. }
  29092. if (this.uvs5) {
  29093. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  29094. }
  29095. if (this.uvs6) {
  29096. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  29097. }
  29098. if (this.colors) {
  29099. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  29100. }
  29101. if (this.matricesIndices) {
  29102. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  29103. }
  29104. if (this.matricesWeights) {
  29105. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  29106. }
  29107. if (this.matricesIndicesExtra) {
  29108. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  29109. }
  29110. if (this.matricesWeightsExtra) {
  29111. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  29112. }
  29113. if (this.indices) {
  29114. meshOrGeometry.setIndices(this.indices, null, updatable);
  29115. }
  29116. return this;
  29117. };
  29118. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  29119. if (this.positions) {
  29120. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  29121. }
  29122. if (this.normals) {
  29123. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  29124. }
  29125. if (this.tangents) {
  29126. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  29127. }
  29128. if (this.uvs) {
  29129. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  29130. }
  29131. if (this.uvs2) {
  29132. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  29133. }
  29134. if (this.uvs3) {
  29135. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  29136. }
  29137. if (this.uvs4) {
  29138. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  29139. }
  29140. if (this.uvs5) {
  29141. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  29142. }
  29143. if (this.uvs6) {
  29144. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  29145. }
  29146. if (this.colors) {
  29147. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  29148. }
  29149. if (this.matricesIndices) {
  29150. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  29151. }
  29152. if (this.matricesWeights) {
  29153. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  29154. }
  29155. if (this.matricesIndicesExtra) {
  29156. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  29157. }
  29158. if (this.matricesWeightsExtra) {
  29159. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  29160. }
  29161. if (this.indices) {
  29162. meshOrGeometry.setIndices(this.indices, null);
  29163. }
  29164. return this;
  29165. };
  29166. /**
  29167. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  29168. * Returns the VertexData.
  29169. */
  29170. VertexData.prototype.transform = function (matrix) {
  29171. var transformed = BABYLON.Vector3.Zero();
  29172. var index;
  29173. if (this.positions) {
  29174. var position = BABYLON.Vector3.Zero();
  29175. for (index = 0; index < this.positions.length; index += 3) {
  29176. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  29177. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  29178. this.positions[index] = transformed.x;
  29179. this.positions[index + 1] = transformed.y;
  29180. this.positions[index + 2] = transformed.z;
  29181. }
  29182. }
  29183. if (this.normals) {
  29184. var normal = BABYLON.Vector3.Zero();
  29185. for (index = 0; index < this.normals.length; index += 3) {
  29186. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  29187. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  29188. this.normals[index] = transformed.x;
  29189. this.normals[index + 1] = transformed.y;
  29190. this.normals[index + 2] = transformed.z;
  29191. }
  29192. }
  29193. if (this.tangents) {
  29194. var tangent = BABYLON.Vector4.Zero();
  29195. var tangentTransformed = BABYLON.Vector4.Zero();
  29196. for (index = 0; index < this.tangents.length; index += 4) {
  29197. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  29198. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  29199. this.tangents[index] = tangentTransformed.x;
  29200. this.tangents[index + 1] = tangentTransformed.y;
  29201. this.tangents[index + 2] = tangentTransformed.z;
  29202. this.tangents[index + 3] = tangentTransformed.w;
  29203. }
  29204. }
  29205. return this;
  29206. };
  29207. /**
  29208. * Merges the passed VertexData into the current one.
  29209. * Returns the modified VertexData.
  29210. */
  29211. VertexData.prototype.merge = function (other, options) {
  29212. options = options || {};
  29213. if (other.indices) {
  29214. if (!this.indices) {
  29215. this.indices = [];
  29216. }
  29217. var offset = this.positions ? this.positions.length / 3 : 0;
  29218. for (var index = 0; index < other.indices.length; index++) {
  29219. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  29220. this.indices.push(other.indices[index] + offset);
  29221. }
  29222. }
  29223. this.positions = this._mergeElement(this.positions, other.positions);
  29224. if (!this.positions) {
  29225. return this;
  29226. }
  29227. var count = this.positions.length / 3;
  29228. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  29229. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  29230. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  29231. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  29232. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  29233. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  29234. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  29235. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  29236. this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
  29237. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  29238. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  29239. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  29240. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  29241. return this;
  29242. };
  29243. VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
  29244. if (length === void 0) { length = 0; }
  29245. if (defaultValue === void 0) { defaultValue = 0; }
  29246. if (!other && !source) {
  29247. return null;
  29248. }
  29249. if (!other) {
  29250. var padding = new Float32Array(source.length);
  29251. padding.fill(defaultValue);
  29252. return this._mergeElement(source, padding, length);
  29253. }
  29254. if (!source) {
  29255. if (length === 0 || length === other.length) {
  29256. return other;
  29257. }
  29258. var padding = new Float32Array(length - other.length);
  29259. padding.fill(defaultValue);
  29260. return this._mergeElement(padding, other, length);
  29261. }
  29262. var len = other.length + source.length;
  29263. var isSrcTypedArray = source instanceof Float32Array;
  29264. var isOthTypedArray = other instanceof Float32Array;
  29265. // use non-loop method when the source is Float32Array
  29266. if (isSrcTypedArray) {
  29267. var ret32 = new Float32Array(len);
  29268. ret32.set(source);
  29269. ret32.set(other, source.length);
  29270. return ret32;
  29271. // source is number[], when other is also use concat
  29272. }
  29273. else if (!isOthTypedArray) {
  29274. return source.concat(other);
  29275. // source is a number[], but other is a Float32Array, loop required
  29276. }
  29277. else {
  29278. var ret = source.slice(0); // copy source to a separate array
  29279. for (var i = 0, len = other.length; i < len; i++) {
  29280. ret.push(other[i]);
  29281. }
  29282. return ret;
  29283. }
  29284. };
  29285. /**
  29286. * Serializes the VertexData.
  29287. * Returns a serialized object.
  29288. */
  29289. VertexData.prototype.serialize = function () {
  29290. var serializationObject = this.serialize();
  29291. if (this.positions) {
  29292. serializationObject.positions = this.positions;
  29293. }
  29294. if (this.normals) {
  29295. serializationObject.normals = this.normals;
  29296. }
  29297. if (this.tangents) {
  29298. serializationObject.tangents = this.tangents;
  29299. }
  29300. if (this.uvs) {
  29301. serializationObject.uvs = this.uvs;
  29302. }
  29303. if (this.uvs2) {
  29304. serializationObject.uvs2 = this.uvs2;
  29305. }
  29306. if (this.uvs3) {
  29307. serializationObject.uvs3 = this.uvs3;
  29308. }
  29309. if (this.uvs4) {
  29310. serializationObject.uvs4 = this.uvs4;
  29311. }
  29312. if (this.uvs5) {
  29313. serializationObject.uvs5 = this.uvs5;
  29314. }
  29315. if (this.uvs6) {
  29316. serializationObject.uvs6 = this.uvs6;
  29317. }
  29318. if (this.colors) {
  29319. serializationObject.colors = this.colors;
  29320. }
  29321. if (this.matricesIndices) {
  29322. serializationObject.matricesIndices = this.matricesIndices;
  29323. serializationObject.matricesIndices._isExpanded = true;
  29324. }
  29325. if (this.matricesWeights) {
  29326. serializationObject.matricesWeights = this.matricesWeights;
  29327. }
  29328. if (this.matricesIndicesExtra) {
  29329. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  29330. serializationObject.matricesIndicesExtra._isExpanded = true;
  29331. }
  29332. if (this.matricesWeightsExtra) {
  29333. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  29334. }
  29335. serializationObject.indices = this.indices;
  29336. return serializationObject;
  29337. };
  29338. // Statics
  29339. /**
  29340. * Returns the object VertexData associated to the passed mesh.
  29341. */
  29342. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  29343. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  29344. };
  29345. /**
  29346. * Returns the object VertexData associated to the passed geometry.
  29347. */
  29348. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  29349. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  29350. };
  29351. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  29352. var result = new VertexData();
  29353. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29354. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  29355. }
  29356. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29357. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  29358. }
  29359. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  29360. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  29361. }
  29362. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29363. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  29364. }
  29365. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29366. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  29367. }
  29368. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29369. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  29370. }
  29371. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29372. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  29373. }
  29374. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29375. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  29376. }
  29377. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29378. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  29379. }
  29380. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29381. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  29382. }
  29383. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29384. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  29385. }
  29386. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29387. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  29388. }
  29389. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  29390. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  29391. }
  29392. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  29393. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  29394. }
  29395. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  29396. return result;
  29397. };
  29398. /**
  29399. * Creates the vertexData of the Ribbon.
  29400. */
  29401. VertexData.CreateRibbon = function (options) {
  29402. var pathArray = options.pathArray;
  29403. var closeArray = options.closeArray || false;
  29404. var closePath = options.closePath || false;
  29405. var invertUV = options.invertUV || false;
  29406. var defaultOffset = Math.floor(pathArray[0].length / 2);
  29407. var offset = options.offset || defaultOffset;
  29408. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  29409. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29410. var customUV = options.uvs;
  29411. var customColors = options.colors;
  29412. var positions = [];
  29413. var indices = [];
  29414. var normals = [];
  29415. var uvs = [];
  29416. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  29417. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  29418. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  29419. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  29420. var minlg; // minimal length among all paths from pathArray
  29421. var lg = []; // array of path lengths : nb of vertex per path
  29422. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  29423. var p; // path iterator
  29424. var i; // point iterator
  29425. var j; // point iterator
  29426. // if single path in pathArray
  29427. if (pathArray.length < 2) {
  29428. var ar1 = [];
  29429. var ar2 = [];
  29430. for (i = 0; i < pathArray[0].length - offset; i++) {
  29431. ar1.push(pathArray[0][i]);
  29432. ar2.push(pathArray[0][i + offset]);
  29433. }
  29434. pathArray = [ar1, ar2];
  29435. }
  29436. // positions and horizontal distances (u)
  29437. var idc = 0;
  29438. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  29439. var path;
  29440. var l;
  29441. minlg = pathArray[0].length;
  29442. var vectlg;
  29443. var dist;
  29444. for (p = 0; p < pathArray.length; p++) {
  29445. uTotalDistance[p] = 0;
  29446. us[p] = [0];
  29447. path = pathArray[p];
  29448. l = path.length;
  29449. minlg = (minlg < l) ? minlg : l;
  29450. j = 0;
  29451. while (j < l) {
  29452. positions.push(path[j].x, path[j].y, path[j].z);
  29453. if (j > 0) {
  29454. vectlg = path[j].subtract(path[j - 1]).length();
  29455. dist = vectlg + uTotalDistance[p];
  29456. us[p].push(dist);
  29457. uTotalDistance[p] = dist;
  29458. }
  29459. j++;
  29460. }
  29461. if (closePath) {
  29462. j--;
  29463. positions.push(path[0].x, path[0].y, path[0].z);
  29464. vectlg = path[j].subtract(path[0]).length();
  29465. dist = vectlg + uTotalDistance[p];
  29466. us[p].push(dist);
  29467. uTotalDistance[p] = dist;
  29468. }
  29469. lg[p] = l + closePathCorr;
  29470. idx[p] = idc;
  29471. idc += (l + closePathCorr);
  29472. }
  29473. // vertical distances (v)
  29474. var path1;
  29475. var path2;
  29476. var vertex1 = null;
  29477. var vertex2 = null;
  29478. for (i = 0; i < minlg + closePathCorr; i++) {
  29479. vTotalDistance[i] = 0;
  29480. vs[i] = [0];
  29481. for (p = 0; p < pathArray.length - 1; p++) {
  29482. path1 = pathArray[p];
  29483. path2 = pathArray[p + 1];
  29484. if (i === minlg) {
  29485. vertex1 = path1[0];
  29486. vertex2 = path2[0];
  29487. }
  29488. else {
  29489. vertex1 = path1[i];
  29490. vertex2 = path2[i];
  29491. }
  29492. vectlg = vertex2.subtract(vertex1).length();
  29493. dist = vectlg + vTotalDistance[i];
  29494. vs[i].push(dist);
  29495. vTotalDistance[i] = dist;
  29496. }
  29497. if (closeArray && vertex2 && vertex1) {
  29498. path1 = pathArray[p];
  29499. path2 = pathArray[0];
  29500. if (i === minlg) {
  29501. vertex2 = path2[0];
  29502. }
  29503. vectlg = vertex2.subtract(vertex1).length();
  29504. dist = vectlg + vTotalDistance[i];
  29505. vTotalDistance[i] = dist;
  29506. }
  29507. }
  29508. // uvs
  29509. var u;
  29510. var v;
  29511. if (customUV) {
  29512. for (p = 0; p < customUV.length; p++) {
  29513. uvs.push(customUV[p].x, customUV[p].y);
  29514. }
  29515. }
  29516. else {
  29517. for (p = 0; p < pathArray.length; p++) {
  29518. for (i = 0; i < minlg + closePathCorr; i++) {
  29519. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  29520. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  29521. if (invertUV) {
  29522. uvs.push(v, u);
  29523. }
  29524. else {
  29525. uvs.push(u, v);
  29526. }
  29527. }
  29528. }
  29529. }
  29530. // indices
  29531. p = 0; // path index
  29532. var pi = 0; // positions array index
  29533. var l1 = lg[p] - 1; // path1 length
  29534. var l2 = lg[p + 1] - 1; // path2 length
  29535. var min = (l1 < l2) ? l1 : l2; // current path stop index
  29536. var shft = idx[1] - idx[0]; // shift
  29537. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  29538. while (pi <= min && p < path1nb) {
  29539. // 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
  29540. indices.push(pi, pi + shft, pi + 1);
  29541. indices.push(pi + shft + 1, pi + 1, pi + shft);
  29542. pi += 1;
  29543. if (pi === min) {
  29544. p++;
  29545. if (p === lg.length - 1) {
  29546. shft = idx[0] - idx[p];
  29547. l1 = lg[p] - 1;
  29548. l2 = lg[0] - 1;
  29549. }
  29550. else {
  29551. shft = idx[p + 1] - idx[p];
  29552. l1 = lg[p] - 1;
  29553. l2 = lg[p + 1] - 1;
  29554. }
  29555. pi = idx[p];
  29556. min = (l1 < l2) ? l1 + pi : l2 + pi;
  29557. }
  29558. }
  29559. // normals
  29560. VertexData.ComputeNormals(positions, indices, normals);
  29561. if (closePath) {
  29562. var indexFirst = 0;
  29563. var indexLast = 0;
  29564. for (p = 0; p < pathArray.length; p++) {
  29565. indexFirst = idx[p] * 3;
  29566. if (p + 1 < pathArray.length) {
  29567. indexLast = (idx[p + 1] - 1) * 3;
  29568. }
  29569. else {
  29570. indexLast = normals.length - 3;
  29571. }
  29572. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  29573. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  29574. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  29575. normals[indexLast] = normals[indexFirst];
  29576. normals[indexLast + 1] = normals[indexFirst + 1];
  29577. normals[indexLast + 2] = normals[indexFirst + 2];
  29578. }
  29579. }
  29580. // sides
  29581. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29582. // Colors
  29583. var colors = null;
  29584. if (customColors) {
  29585. colors = new Float32Array(customColors.length * 4);
  29586. for (var c = 0; c < customColors.length; c++) {
  29587. colors[c * 4] = customColors[c].r;
  29588. colors[c * 4 + 1] = customColors[c].g;
  29589. colors[c * 4 + 2] = customColors[c].b;
  29590. colors[c * 4 + 3] = customColors[c].a;
  29591. }
  29592. }
  29593. // Result
  29594. var vertexData = new VertexData();
  29595. var positions32 = new Float32Array(positions);
  29596. var normals32 = new Float32Array(normals);
  29597. var uvs32 = new Float32Array(uvs);
  29598. vertexData.indices = indices;
  29599. vertexData.positions = positions32;
  29600. vertexData.normals = normals32;
  29601. vertexData.uvs = uvs32;
  29602. if (colors) {
  29603. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  29604. }
  29605. if (closePath) {
  29606. vertexData._idx = idx;
  29607. }
  29608. return vertexData;
  29609. };
  29610. /**
  29611. * Creates the VertexData of the Box.
  29612. */
  29613. VertexData.CreateBox = function (options) {
  29614. var normalsSource = [
  29615. new BABYLON.Vector3(0, 0, 1),
  29616. new BABYLON.Vector3(0, 0, -1),
  29617. new BABYLON.Vector3(1, 0, 0),
  29618. new BABYLON.Vector3(-1, 0, 0),
  29619. new BABYLON.Vector3(0, 1, 0),
  29620. new BABYLON.Vector3(0, -1, 0)
  29621. ];
  29622. var indices = [];
  29623. var positions = [];
  29624. var normals = [];
  29625. var uvs = [];
  29626. var width = options.width || options.size || 1;
  29627. var height = options.height || options.size || 1;
  29628. var depth = options.depth || options.size || 1;
  29629. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29630. var faceUV = options.faceUV || new Array(6);
  29631. var faceColors = options.faceColors;
  29632. var colors = [];
  29633. // default face colors and UV if undefined
  29634. for (var f = 0; f < 6; f++) {
  29635. if (faceUV[f] === undefined) {
  29636. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29637. }
  29638. if (faceColors && faceColors[f] === undefined) {
  29639. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29640. }
  29641. }
  29642. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  29643. // Create each face in turn.
  29644. for (var index = 0; index < normalsSource.length; index++) {
  29645. var normal = normalsSource[index];
  29646. // Get two vectors perpendicular to the face normal and to each other.
  29647. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  29648. var side2 = BABYLON.Vector3.Cross(normal, side1);
  29649. // Six indices (two triangles) per face.
  29650. var verticesLength = positions.length / 3;
  29651. indices.push(verticesLength);
  29652. indices.push(verticesLength + 1);
  29653. indices.push(verticesLength + 2);
  29654. indices.push(verticesLength);
  29655. indices.push(verticesLength + 2);
  29656. indices.push(verticesLength + 3);
  29657. // Four vertices per face.
  29658. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  29659. positions.push(vertex.x, vertex.y, vertex.z);
  29660. normals.push(normal.x, normal.y, normal.z);
  29661. uvs.push(faceUV[index].z, faceUV[index].w);
  29662. if (faceColors) {
  29663. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29664. }
  29665. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  29666. positions.push(vertex.x, vertex.y, vertex.z);
  29667. normals.push(normal.x, normal.y, normal.z);
  29668. uvs.push(faceUV[index].x, faceUV[index].w);
  29669. if (faceColors) {
  29670. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29671. }
  29672. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  29673. positions.push(vertex.x, vertex.y, vertex.z);
  29674. normals.push(normal.x, normal.y, normal.z);
  29675. uvs.push(faceUV[index].x, faceUV[index].y);
  29676. if (faceColors) {
  29677. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29678. }
  29679. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  29680. positions.push(vertex.x, vertex.y, vertex.z);
  29681. normals.push(normal.x, normal.y, normal.z);
  29682. uvs.push(faceUV[index].z, faceUV[index].y);
  29683. if (faceColors) {
  29684. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29685. }
  29686. }
  29687. // sides
  29688. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29689. // Result
  29690. var vertexData = new VertexData();
  29691. vertexData.indices = indices;
  29692. vertexData.positions = positions;
  29693. vertexData.normals = normals;
  29694. vertexData.uvs = uvs;
  29695. if (faceColors) {
  29696. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29697. vertexData.colors = totalColors;
  29698. }
  29699. return vertexData;
  29700. };
  29701. /**
  29702. * Creates the VertexData of the Sphere.
  29703. */
  29704. VertexData.CreateSphere = function (options) {
  29705. var segments = options.segments || 32;
  29706. var diameterX = options.diameterX || options.diameter || 1;
  29707. var diameterY = options.diameterY || options.diameter || 1;
  29708. var diameterZ = options.diameterZ || options.diameter || 1;
  29709. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29710. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  29711. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29712. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  29713. var totalZRotationSteps = 2 + segments;
  29714. var totalYRotationSteps = 2 * totalZRotationSteps;
  29715. var indices = [];
  29716. var positions = [];
  29717. var normals = [];
  29718. var uvs = [];
  29719. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  29720. var normalizedZ = zRotationStep / totalZRotationSteps;
  29721. var angleZ = normalizedZ * Math.PI * slice;
  29722. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  29723. var normalizedY = yRotationStep / totalYRotationSteps;
  29724. var angleY = normalizedY * Math.PI * 2 * arc;
  29725. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  29726. var rotationY = BABYLON.Matrix.RotationY(angleY);
  29727. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  29728. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  29729. var vertex = complete.multiply(radius);
  29730. var normal = complete.divide(radius).normalize();
  29731. positions.push(vertex.x, vertex.y, vertex.z);
  29732. normals.push(normal.x, normal.y, normal.z);
  29733. uvs.push(normalizedY, normalizedZ);
  29734. }
  29735. if (zRotationStep > 0) {
  29736. var verticesCount = positions.length / 3;
  29737. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  29738. indices.push((firstIndex));
  29739. indices.push((firstIndex + 1));
  29740. indices.push(firstIndex + totalYRotationSteps + 1);
  29741. indices.push((firstIndex + totalYRotationSteps + 1));
  29742. indices.push((firstIndex + 1));
  29743. indices.push((firstIndex + totalYRotationSteps + 2));
  29744. }
  29745. }
  29746. }
  29747. // Sides
  29748. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29749. // Result
  29750. var vertexData = new VertexData();
  29751. vertexData.indices = indices;
  29752. vertexData.positions = positions;
  29753. vertexData.normals = normals;
  29754. vertexData.uvs = uvs;
  29755. return vertexData;
  29756. };
  29757. /**
  29758. * Creates the VertexData of the Cylinder or Cone.
  29759. */
  29760. VertexData.CreateCylinder = function (options) {
  29761. var height = options.height || 2;
  29762. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  29763. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  29764. var tessellation = options.tessellation || 24;
  29765. var subdivisions = options.subdivisions || 1;
  29766. var hasRings = options.hasRings ? true : false;
  29767. var enclose = options.enclose ? true : false;
  29768. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29769. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29770. var faceUV = options.faceUV || new Array(3);
  29771. var faceColors = options.faceColors;
  29772. // default face colors and UV if undefined
  29773. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  29774. var ringNb = (hasRings) ? subdivisions : 1;
  29775. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  29776. var f;
  29777. for (f = 0; f < surfaceNb; f++) {
  29778. if (faceColors && faceColors[f] === undefined) {
  29779. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29780. }
  29781. }
  29782. for (f = 0; f < surfaceNb; f++) {
  29783. if (faceUV && faceUV[f] === undefined) {
  29784. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29785. }
  29786. }
  29787. var indices = new Array();
  29788. var positions = new Array();
  29789. var normals = new Array();
  29790. var uvs = new Array();
  29791. var colors = new Array();
  29792. var angle_step = Math.PI * 2 * arc / tessellation;
  29793. var angle;
  29794. var h;
  29795. var radius;
  29796. var tan = (diameterBottom - diameterTop) / 2 / height;
  29797. var ringVertex = BABYLON.Vector3.Zero();
  29798. var ringNormal = BABYLON.Vector3.Zero();
  29799. var ringFirstVertex = BABYLON.Vector3.Zero();
  29800. var ringFirstNormal = BABYLON.Vector3.Zero();
  29801. var quadNormal = BABYLON.Vector3.Zero();
  29802. var Y = BABYLON.Axis.Y;
  29803. // positions, normals, uvs
  29804. var i;
  29805. var j;
  29806. var r;
  29807. var ringIdx = 1;
  29808. var s = 1; // surface index
  29809. var cs = 0;
  29810. var v = 0;
  29811. for (i = 0; i <= subdivisions; i++) {
  29812. h = i / subdivisions;
  29813. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  29814. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  29815. for (r = 0; r < ringIdx; r++) {
  29816. if (hasRings) {
  29817. s += r;
  29818. }
  29819. if (enclose) {
  29820. s += 2 * r;
  29821. }
  29822. for (j = 0; j <= tessellation; j++) {
  29823. angle = j * angle_step;
  29824. // position
  29825. ringVertex.x = Math.cos(-angle) * radius;
  29826. ringVertex.y = -height / 2 + h * height;
  29827. ringVertex.z = Math.sin(-angle) * radius;
  29828. // normal
  29829. if (diameterTop === 0 && i === subdivisions) {
  29830. // if no top cap, reuse former normals
  29831. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  29832. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  29833. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  29834. }
  29835. else {
  29836. ringNormal.x = ringVertex.x;
  29837. ringNormal.z = ringVertex.z;
  29838. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  29839. ringNormal.normalize();
  29840. }
  29841. // keep first ring vertex values for enclose
  29842. if (j === 0) {
  29843. ringFirstVertex.copyFrom(ringVertex);
  29844. ringFirstNormal.copyFrom(ringNormal);
  29845. }
  29846. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29847. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  29848. if (hasRings) {
  29849. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  29850. }
  29851. else {
  29852. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  29853. }
  29854. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  29855. if (faceColors) {
  29856. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  29857. }
  29858. }
  29859. // if enclose, add four vertices and their dedicated normals
  29860. if (arc !== 1 && enclose) {
  29861. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29862. positions.push(0, ringVertex.y, 0);
  29863. positions.push(0, ringVertex.y, 0);
  29864. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  29865. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  29866. quadNormal.normalize();
  29867. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29868. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  29869. quadNormal.normalize();
  29870. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29871. if (hasRings) {
  29872. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  29873. }
  29874. else {
  29875. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  29876. }
  29877. uvs.push(faceUV[s + 1].x, v);
  29878. uvs.push(faceUV[s + 1].z, v);
  29879. if (hasRings) {
  29880. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  29881. }
  29882. else {
  29883. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  29884. }
  29885. uvs.push(faceUV[s + 2].x, v);
  29886. uvs.push(faceUV[s + 2].z, v);
  29887. if (faceColors) {
  29888. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29889. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29890. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29891. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29892. }
  29893. }
  29894. if (cs !== s) {
  29895. cs = s;
  29896. }
  29897. }
  29898. }
  29899. // indices
  29900. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  29901. var s;
  29902. i = 0;
  29903. for (s = 0; s < subdivisions; s++) {
  29904. var i0 = 0;
  29905. var i1 = 0;
  29906. var i2 = 0;
  29907. var i3 = 0;
  29908. for (j = 0; j < tessellation; j++) {
  29909. i0 = i * (e + 1) + j;
  29910. i1 = (i + 1) * (e + 1) + j;
  29911. i2 = i * (e + 1) + (j + 1);
  29912. i3 = (i + 1) * (e + 1) + (j + 1);
  29913. indices.push(i0, i1, i2);
  29914. indices.push(i3, i2, i1);
  29915. }
  29916. if (arc !== 1 && enclose) {
  29917. indices.push(i0 + 2, i1 + 2, i2 + 2);
  29918. indices.push(i3 + 2, i2 + 2, i1 + 2);
  29919. indices.push(i0 + 4, i1 + 4, i2 + 4);
  29920. indices.push(i3 + 4, i2 + 4, i1 + 4);
  29921. }
  29922. i = (hasRings) ? (i + 2) : (i + 1);
  29923. }
  29924. // Caps
  29925. var createCylinderCap = function (isTop) {
  29926. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  29927. if (radius === 0) {
  29928. return;
  29929. }
  29930. // Cap positions, normals & uvs
  29931. var angle;
  29932. var circleVector;
  29933. var i;
  29934. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  29935. var c = null;
  29936. if (faceColors) {
  29937. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  29938. }
  29939. // cap center
  29940. var vbase = positions.length / 3;
  29941. var offset = isTop ? height / 2 : -height / 2;
  29942. var center = new BABYLON.Vector3(0, offset, 0);
  29943. positions.push(center.x, center.y, center.z);
  29944. normals.push(0, isTop ? 1 : -1, 0);
  29945. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  29946. if (c) {
  29947. colors.push(c.r, c.g, c.b, c.a);
  29948. }
  29949. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  29950. for (i = 0; i <= tessellation; i++) {
  29951. angle = Math.PI * 2 * i * arc / tessellation;
  29952. var cos = Math.cos(-angle);
  29953. var sin = Math.sin(-angle);
  29954. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  29955. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  29956. positions.push(circleVector.x, circleVector.y, circleVector.z);
  29957. normals.push(0, isTop ? 1 : -1, 0);
  29958. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  29959. if (c) {
  29960. colors.push(c.r, c.g, c.b, c.a);
  29961. }
  29962. }
  29963. // Cap indices
  29964. for (i = 0; i < tessellation; i++) {
  29965. if (!isTop) {
  29966. indices.push(vbase);
  29967. indices.push(vbase + (i + 1));
  29968. indices.push(vbase + (i + 2));
  29969. }
  29970. else {
  29971. indices.push(vbase);
  29972. indices.push(vbase + (i + 2));
  29973. indices.push(vbase + (i + 1));
  29974. }
  29975. }
  29976. };
  29977. // add caps to geometry
  29978. createCylinderCap(false);
  29979. createCylinderCap(true);
  29980. // Sides
  29981. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29982. var vertexData = new VertexData();
  29983. vertexData.indices = indices;
  29984. vertexData.positions = positions;
  29985. vertexData.normals = normals;
  29986. vertexData.uvs = uvs;
  29987. if (faceColors) {
  29988. vertexData.colors = colors;
  29989. }
  29990. return vertexData;
  29991. };
  29992. /**
  29993. * Creates the VertexData of the Torus.
  29994. */
  29995. VertexData.CreateTorus = function (options) {
  29996. var indices = [];
  29997. var positions = [];
  29998. var normals = [];
  29999. var uvs = [];
  30000. var diameter = options.diameter || 1;
  30001. var thickness = options.thickness || 0.5;
  30002. var tessellation = options.tessellation || 16;
  30003. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30004. var stride = tessellation + 1;
  30005. for (var i = 0; i <= tessellation; i++) {
  30006. var u = i / tessellation;
  30007. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  30008. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  30009. for (var j = 0; j <= tessellation; j++) {
  30010. var v = 1 - j / tessellation;
  30011. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  30012. var dx = Math.cos(innerAngle);
  30013. var dy = Math.sin(innerAngle);
  30014. // Create a vertex.
  30015. var normal = new BABYLON.Vector3(dx, dy, 0);
  30016. var position = normal.scale(thickness / 2);
  30017. var textureCoordinate = new BABYLON.Vector2(u, v);
  30018. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  30019. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  30020. positions.push(position.x, position.y, position.z);
  30021. normals.push(normal.x, normal.y, normal.z);
  30022. uvs.push(textureCoordinate.x, textureCoordinate.y);
  30023. // And create indices for two triangles.
  30024. var nextI = (i + 1) % stride;
  30025. var nextJ = (j + 1) % stride;
  30026. indices.push(i * stride + j);
  30027. indices.push(i * stride + nextJ);
  30028. indices.push(nextI * stride + j);
  30029. indices.push(i * stride + nextJ);
  30030. indices.push(nextI * stride + nextJ);
  30031. indices.push(nextI * stride + j);
  30032. }
  30033. }
  30034. // Sides
  30035. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30036. // Result
  30037. var vertexData = new VertexData();
  30038. vertexData.indices = indices;
  30039. vertexData.positions = positions;
  30040. vertexData.normals = normals;
  30041. vertexData.uvs = uvs;
  30042. return vertexData;
  30043. };
  30044. /**
  30045. * Creates the VertexData of the LineSystem.
  30046. */
  30047. VertexData.CreateLineSystem = function (options) {
  30048. var indices = [];
  30049. var positions = [];
  30050. var lines = options.lines;
  30051. var colors = options.colors;
  30052. var vertexColors = [];
  30053. var idx = 0;
  30054. for (var l = 0; l < lines.length; l++) {
  30055. var points = lines[l];
  30056. for (var index = 0; index < points.length; index++) {
  30057. positions.push(points[index].x, points[index].y, points[index].z);
  30058. if (colors) {
  30059. var color = colors[l];
  30060. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  30061. }
  30062. if (index > 0) {
  30063. indices.push(idx - 1);
  30064. indices.push(idx);
  30065. }
  30066. idx++;
  30067. }
  30068. }
  30069. var vertexData = new VertexData();
  30070. vertexData.indices = indices;
  30071. vertexData.positions = positions;
  30072. if (colors) {
  30073. vertexData.colors = vertexColors;
  30074. }
  30075. return vertexData;
  30076. };
  30077. /**
  30078. * Create the VertexData of the DashedLines.
  30079. */
  30080. VertexData.CreateDashedLines = function (options) {
  30081. var dashSize = options.dashSize || 3;
  30082. var gapSize = options.gapSize || 1;
  30083. var dashNb = options.dashNb || 200;
  30084. var points = options.points;
  30085. var positions = new Array();
  30086. var indices = new Array();
  30087. var curvect = BABYLON.Vector3.Zero();
  30088. var lg = 0;
  30089. var nb = 0;
  30090. var shft = 0;
  30091. var dashshft = 0;
  30092. var curshft = 0;
  30093. var idx = 0;
  30094. var i = 0;
  30095. for (i = 0; i < points.length - 1; i++) {
  30096. points[i + 1].subtractToRef(points[i], curvect);
  30097. lg += curvect.length();
  30098. }
  30099. shft = lg / dashNb;
  30100. dashshft = dashSize * shft / (dashSize + gapSize);
  30101. for (i = 0; i < points.length - 1; i++) {
  30102. points[i + 1].subtractToRef(points[i], curvect);
  30103. nb = Math.floor(curvect.length() / shft);
  30104. curvect.normalize();
  30105. for (var j = 0; j < nb; j++) {
  30106. curshft = shft * j;
  30107. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  30108. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  30109. indices.push(idx, idx + 1);
  30110. idx += 2;
  30111. }
  30112. }
  30113. // Result
  30114. var vertexData = new VertexData();
  30115. vertexData.positions = positions;
  30116. vertexData.indices = indices;
  30117. return vertexData;
  30118. };
  30119. /**
  30120. * Creates the VertexData of the Ground.
  30121. */
  30122. VertexData.CreateGround = function (options) {
  30123. var indices = [];
  30124. var positions = [];
  30125. var normals = [];
  30126. var uvs = [];
  30127. var row, col;
  30128. var width = options.width || 1;
  30129. var height = options.height || 1;
  30130. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  30131. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  30132. for (row = 0; row <= subdivisionsY; row++) {
  30133. for (col = 0; col <= subdivisionsX; col++) {
  30134. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  30135. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30136. positions.push(position.x, position.y, position.z);
  30137. normals.push(normal.x, normal.y, normal.z);
  30138. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  30139. }
  30140. }
  30141. for (row = 0; row < subdivisionsY; row++) {
  30142. for (col = 0; col < subdivisionsX; col++) {
  30143. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  30144. indices.push(col + 1 + row * (subdivisionsX + 1));
  30145. indices.push(col + row * (subdivisionsX + 1));
  30146. indices.push(col + (row + 1) * (subdivisionsX + 1));
  30147. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  30148. indices.push(col + row * (subdivisionsX + 1));
  30149. }
  30150. }
  30151. // Result
  30152. var vertexData = new VertexData();
  30153. vertexData.indices = indices;
  30154. vertexData.positions = positions;
  30155. vertexData.normals = normals;
  30156. vertexData.uvs = uvs;
  30157. return vertexData;
  30158. };
  30159. /**
  30160. * Creates the VertexData of the TiledGround.
  30161. */
  30162. VertexData.CreateTiledGround = function (options) {
  30163. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  30164. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  30165. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  30166. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  30167. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  30168. var precision = options.precision || { w: 1, h: 1 };
  30169. var indices = new Array();
  30170. var positions = new Array();
  30171. var normals = new Array();
  30172. var uvs = new Array();
  30173. var row, col, tileRow, tileCol;
  30174. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  30175. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  30176. precision.w = (precision.w < 1) ? 1 : precision.w;
  30177. precision.h = (precision.h < 1) ? 1 : precision.h;
  30178. var tileSize = {
  30179. 'w': (xmax - xmin) / subdivisions.w,
  30180. 'h': (zmax - zmin) / subdivisions.h
  30181. };
  30182. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  30183. // Indices
  30184. var base = positions.length / 3;
  30185. var rowLength = precision.w + 1;
  30186. for (row = 0; row < precision.h; row++) {
  30187. for (col = 0; col < precision.w; col++) {
  30188. var square = [
  30189. base + col + row * rowLength,
  30190. base + (col + 1) + row * rowLength,
  30191. base + (col + 1) + (row + 1) * rowLength,
  30192. base + col + (row + 1) * rowLength
  30193. ];
  30194. indices.push(square[1]);
  30195. indices.push(square[2]);
  30196. indices.push(square[3]);
  30197. indices.push(square[0]);
  30198. indices.push(square[1]);
  30199. indices.push(square[3]);
  30200. }
  30201. }
  30202. // Position, normals and uvs
  30203. var position = BABYLON.Vector3.Zero();
  30204. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30205. for (row = 0; row <= precision.h; row++) {
  30206. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  30207. for (col = 0; col <= precision.w; col++) {
  30208. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  30209. position.y = 0;
  30210. positions.push(position.x, position.y, position.z);
  30211. normals.push(normal.x, normal.y, normal.z);
  30212. uvs.push(col / precision.w, row / precision.h);
  30213. }
  30214. }
  30215. }
  30216. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  30217. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  30218. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  30219. }
  30220. }
  30221. // Result
  30222. var vertexData = new VertexData();
  30223. vertexData.indices = indices;
  30224. vertexData.positions = positions;
  30225. vertexData.normals = normals;
  30226. vertexData.uvs = uvs;
  30227. return vertexData;
  30228. };
  30229. /**
  30230. * Creates the VertexData of the Ground designed from a heightmap.
  30231. */
  30232. VertexData.CreateGroundFromHeightMap = function (options) {
  30233. var indices = [];
  30234. var positions = [];
  30235. var normals = [];
  30236. var uvs = [];
  30237. var row, col;
  30238. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  30239. // Vertices
  30240. for (row = 0; row <= options.subdivisions; row++) {
  30241. for (col = 0; col <= options.subdivisions; col++) {
  30242. 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));
  30243. // Compute height
  30244. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  30245. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  30246. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  30247. var r = options.buffer[pos] / 255.0;
  30248. var g = options.buffer[pos + 1] / 255.0;
  30249. var b = options.buffer[pos + 2] / 255.0;
  30250. var gradient = r * filter.r + g * filter.g + b * filter.b;
  30251. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  30252. // Add vertex
  30253. positions.push(position.x, position.y, position.z);
  30254. normals.push(0, 0, 0);
  30255. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  30256. }
  30257. }
  30258. // Indices
  30259. for (row = 0; row < options.subdivisions; row++) {
  30260. for (col = 0; col < options.subdivisions; col++) {
  30261. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30262. indices.push(col + 1 + row * (options.subdivisions + 1));
  30263. indices.push(col + row * (options.subdivisions + 1));
  30264. indices.push(col + (row + 1) * (options.subdivisions + 1));
  30265. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30266. indices.push(col + row * (options.subdivisions + 1));
  30267. }
  30268. }
  30269. // Normals
  30270. VertexData.ComputeNormals(positions, indices, normals);
  30271. // Result
  30272. var vertexData = new VertexData();
  30273. vertexData.indices = indices;
  30274. vertexData.positions = positions;
  30275. vertexData.normals = normals;
  30276. vertexData.uvs = uvs;
  30277. return vertexData;
  30278. };
  30279. /**
  30280. * Creates the VertexData of the Plane.
  30281. */
  30282. VertexData.CreatePlane = function (options) {
  30283. var indices = [];
  30284. var positions = [];
  30285. var normals = [];
  30286. var uvs = [];
  30287. var width = options.width || options.size || 1;
  30288. var height = options.height || options.size || 1;
  30289. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30290. // Vertices
  30291. var halfWidth = width / 2.0;
  30292. var halfHeight = height / 2.0;
  30293. positions.push(-halfWidth, -halfHeight, 0);
  30294. normals.push(0, 0, -1.0);
  30295. uvs.push(0.0, 0.0);
  30296. positions.push(halfWidth, -halfHeight, 0);
  30297. normals.push(0, 0, -1.0);
  30298. uvs.push(1.0, 0.0);
  30299. positions.push(halfWidth, halfHeight, 0);
  30300. normals.push(0, 0, -1.0);
  30301. uvs.push(1.0, 1.0);
  30302. positions.push(-halfWidth, halfHeight, 0);
  30303. normals.push(0, 0, -1.0);
  30304. uvs.push(0.0, 1.0);
  30305. // Indices
  30306. indices.push(0);
  30307. indices.push(1);
  30308. indices.push(2);
  30309. indices.push(0);
  30310. indices.push(2);
  30311. indices.push(3);
  30312. // Sides
  30313. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30314. // Result
  30315. var vertexData = new VertexData();
  30316. vertexData.indices = indices;
  30317. vertexData.positions = positions;
  30318. vertexData.normals = normals;
  30319. vertexData.uvs = uvs;
  30320. return vertexData;
  30321. };
  30322. /**
  30323. * Creates the VertexData of the Disc or regular Polygon.
  30324. */
  30325. VertexData.CreateDisc = function (options) {
  30326. var positions = new Array();
  30327. var indices = new Array();
  30328. var normals = new Array();
  30329. var uvs = new Array();
  30330. var radius = options.radius || 0.5;
  30331. var tessellation = options.tessellation || 64;
  30332. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30333. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30334. // positions and uvs
  30335. positions.push(0, 0, 0); // disc center first
  30336. uvs.push(0.5, 0.5);
  30337. var theta = Math.PI * 2 * arc;
  30338. var step = theta / tessellation;
  30339. for (var a = 0; a < theta; a += step) {
  30340. var x = Math.cos(a);
  30341. var y = Math.sin(a);
  30342. var u = (x + 1) / 2;
  30343. var v = (1 - y) / 2;
  30344. positions.push(radius * x, radius * y, 0);
  30345. uvs.push(u, v);
  30346. }
  30347. if (arc === 1) {
  30348. positions.push(positions[3], positions[4], positions[5]); // close the circle
  30349. uvs.push(uvs[2], uvs[3]);
  30350. }
  30351. //indices
  30352. var vertexNb = positions.length / 3;
  30353. for (var i = 1; i < vertexNb - 1; i++) {
  30354. indices.push(i + 1, 0, i);
  30355. }
  30356. // result
  30357. VertexData.ComputeNormals(positions, indices, normals);
  30358. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30359. var vertexData = new VertexData();
  30360. vertexData.indices = indices;
  30361. vertexData.positions = positions;
  30362. vertexData.normals = normals;
  30363. vertexData.uvs = uvs;
  30364. return vertexData;
  30365. };
  30366. /**
  30367. * Re-creates the VertexData of the Polygon for sideOrientation.
  30368. */
  30369. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  30370. var faceUV = fUV || new Array(3);
  30371. var faceColors = fColors;
  30372. var colors = [];
  30373. // default face colors and UV if undefined
  30374. for (var f = 0; f < 3; f++) {
  30375. if (faceUV[f] === undefined) {
  30376. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30377. }
  30378. if (faceColors && faceColors[f] === undefined) {
  30379. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30380. }
  30381. }
  30382. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30383. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30384. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30385. var indices = polygon.getIndices();
  30386. // set face colours and textures
  30387. var idx = 0;
  30388. var face = 0;
  30389. for (var index = 0; index < normals.length; index += 3) {
  30390. //Edge Face no. 1
  30391. if (Math.abs(normals[index + 1]) < 0.001) {
  30392. face = 1;
  30393. }
  30394. //Top Face no. 0
  30395. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  30396. face = 0;
  30397. }
  30398. //Bottom Face no. 2
  30399. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  30400. face = 2;
  30401. }
  30402. idx = index / 3;
  30403. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  30404. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  30405. if (faceColors) {
  30406. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  30407. }
  30408. }
  30409. // sides
  30410. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  30411. // Result
  30412. var vertexData = new VertexData();
  30413. vertexData.indices = indices;
  30414. vertexData.positions = positions;
  30415. vertexData.normals = normals;
  30416. vertexData.uvs = uvs;
  30417. if (faceColors) {
  30418. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30419. vertexData.colors = totalColors;
  30420. }
  30421. return vertexData;
  30422. };
  30423. /**
  30424. * Creates the VertexData of the IcoSphere.
  30425. */
  30426. VertexData.CreateIcoSphere = function (options) {
  30427. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30428. var radius = options.radius || 1;
  30429. var flat = (options.flat === undefined) ? true : options.flat;
  30430. var subdivisions = options.subdivisions || 4;
  30431. var radiusX = options.radiusX || radius;
  30432. var radiusY = options.radiusY || radius;
  30433. var radiusZ = options.radiusZ || radius;
  30434. var t = (1 + Math.sqrt(5)) / 2;
  30435. // 12 vertex x,y,z
  30436. var ico_vertices = [
  30437. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  30438. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  30439. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  30440. ];
  30441. // index of 3 vertex makes a face of icopshere
  30442. var ico_indices = [
  30443. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  30444. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  30445. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  30446. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  30447. ];
  30448. // vertex for uv have aliased position, not for UV
  30449. var vertices_unalias_id = [
  30450. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  30451. // vertex alias
  30452. 0,
  30453. 2,
  30454. 3,
  30455. 3,
  30456. 3,
  30457. 4,
  30458. 7,
  30459. 8,
  30460. 9,
  30461. 9,
  30462. 10,
  30463. 11 // 23: B + 12
  30464. ];
  30465. // uv as integer step (not pixels !)
  30466. var ico_vertexuv = [
  30467. 5, 1, 3, 1, 6, 4, 0, 0,
  30468. 5, 3, 4, 2, 2, 2, 4, 0,
  30469. 2, 0, 1, 1, 6, 0, 6, 2,
  30470. // vertex alias (for same vertex on different faces)
  30471. 0, 4,
  30472. 3, 3,
  30473. 4, 4,
  30474. 3, 1,
  30475. 4, 2,
  30476. 4, 4,
  30477. 0, 2,
  30478. 1, 1,
  30479. 2, 2,
  30480. 3, 3,
  30481. 1, 3,
  30482. 2, 4 // 23: B + 12
  30483. ];
  30484. // Vertices[0, 1, ...9, A, B] : position on UV plane
  30485. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  30486. // First island of uv mapping
  30487. // v = 4h 3+ 2
  30488. // v = 3h 9+ 4
  30489. // v = 2h 9+ 5 B
  30490. // v = 1h 9 1 0
  30491. // v = 0h 3 8 7 A
  30492. // u = 0 1 2 3 4 5 6 *a
  30493. // Second island of uv mapping
  30494. // v = 4h 0+ B+ 4+
  30495. // v = 3h A+ 2+
  30496. // v = 2h 7+ 6 3+
  30497. // v = 1h 8+ 3+
  30498. // v = 0h
  30499. // u = 0 1 2 3 4 5 6 *a
  30500. // Face layout on texture UV mapping
  30501. // ============
  30502. // \ 4 /\ 16 / ======
  30503. // \ / \ / /\ 11 /
  30504. // \/ 7 \/ / \ /
  30505. // ======= / 10 \/
  30506. // /\ 17 /\ =======
  30507. // / \ / \ \ 15 /\
  30508. // / 8 \/ 12 \ \ / \
  30509. // ============ \/ 6 \
  30510. // \ 18 /\ ============
  30511. // \ / \ \ 5 /\ 0 /
  30512. // \/ 13 \ \ / \ /
  30513. // ======= \/ 1 \/
  30514. // =============
  30515. // /\ 19 /\ 2 /\
  30516. // / \ / \ / \
  30517. // / 14 \/ 9 \/ 3 \
  30518. // ===================
  30519. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  30520. var ustep = 138 / 1024;
  30521. var vstep = 239 / 1024;
  30522. var uoffset = 60 / 1024;
  30523. var voffset = 26 / 1024;
  30524. // Second island should have margin, not to touch the first island
  30525. // avoid any borderline artefact in pixel rounding
  30526. var island_u_offset = -40 / 1024;
  30527. var island_v_offset = +20 / 1024;
  30528. // face is either island 0 or 1 :
  30529. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  30530. var island = [
  30531. 0, 0, 0, 0, 1,
  30532. 0, 0, 1, 1, 0,
  30533. 0, 0, 1, 1, 0,
  30534. 0, 1, 1, 1, 0 // 15 - 19
  30535. ];
  30536. var indices = new Array();
  30537. var positions = new Array();
  30538. var normals = new Array();
  30539. var uvs = new Array();
  30540. var current_indice = 0;
  30541. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  30542. var face_vertex_pos = new Array(3);
  30543. var face_vertex_uv = new Array(3);
  30544. var v012;
  30545. for (v012 = 0; v012 < 3; v012++) {
  30546. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  30547. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  30548. }
  30549. // create all with normals
  30550. for (var face = 0; face < 20; face++) {
  30551. // 3 vertex per face
  30552. for (v012 = 0; v012 < 3; v012++) {
  30553. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  30554. var v_id = ico_indices[3 * face + v012];
  30555. // vertex have 3D position (x,y,z)
  30556. 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]);
  30557. // Normalize to get normal, then scale to radius
  30558. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  30559. // uv Coordinates from vertex ID
  30560. 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);
  30561. }
  30562. // Subdivide the face (interpolate pos, norm, uv)
  30563. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  30564. // - norm is linear interpolation of vertex corner normal
  30565. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  30566. // - uv is linear interpolation
  30567. //
  30568. // Topology is as below for sub-divide by 2
  30569. // vertex shown as v0,v1,v2
  30570. // interp index is i1 to progress in range [v0,v1[
  30571. // interp index is i2 to progress in range [v0,v2[
  30572. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  30573. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30574. //
  30575. //
  30576. // i2 v2
  30577. // ^ ^
  30578. // / / \
  30579. // / / \
  30580. // / / \
  30581. // / / (0,1) \
  30582. // / #---------\
  30583. // / / \ (0,0)'/ \
  30584. // / / \ / \
  30585. // / / \ / \
  30586. // / / (0,0) \ / (1,0) \
  30587. // / #---------#---------\
  30588. // v0 v1
  30589. //
  30590. // --------------------> i1
  30591. //
  30592. // interp of (i1,i2):
  30593. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  30594. // along i1 : lerp(x0,x1, i1/(S-i2))
  30595. //
  30596. // centroid of triangle is needed to get help normal computation
  30597. // (c1,c2) are used for centroid location
  30598. var interp_vertex = function (i1, i2, c1, c2) {
  30599. // vertex is interpolated from
  30600. // - face_vertex_pos[0..2]
  30601. // - face_vertex_uv[0..2]
  30602. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  30603. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  30604. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  30605. pos_interp.normalize();
  30606. var vertex_normal;
  30607. if (flat) {
  30608. // in flat mode, recalculate normal as face centroid normal
  30609. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  30610. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  30611. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  30612. }
  30613. else {
  30614. // in smooth mode, recalculate normal from each single vertex position
  30615. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  30616. }
  30617. // Vertex normal need correction due to X,Y,Z radius scaling
  30618. vertex_normal.x /= radiusX;
  30619. vertex_normal.y /= radiusY;
  30620. vertex_normal.z /= radiusZ;
  30621. vertex_normal.normalize();
  30622. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  30623. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  30624. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  30625. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  30626. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  30627. uvs.push(uv_interp.x, uv_interp.y);
  30628. // push each vertex has member of a face
  30629. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  30630. indices.push(current_indice);
  30631. current_indice++;
  30632. };
  30633. for (var i2 = 0; i2 < subdivisions; i2++) {
  30634. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  30635. // face : (i1,i2) for /\ :
  30636. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  30637. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30638. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30639. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30640. if (i1 + i2 + 1 < subdivisions) {
  30641. // face : (i1,i2)' for \/ :
  30642. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30643. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30644. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30645. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30646. }
  30647. }
  30648. }
  30649. }
  30650. // Sides
  30651. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30652. // Result
  30653. var vertexData = new VertexData();
  30654. vertexData.indices = indices;
  30655. vertexData.positions = positions;
  30656. vertexData.normals = normals;
  30657. vertexData.uvs = uvs;
  30658. return vertexData;
  30659. };
  30660. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  30661. /**
  30662. * Creates the VertexData of the Polyhedron.
  30663. */
  30664. VertexData.CreatePolyhedron = function (options) {
  30665. // provided polyhedron types :
  30666. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  30667. // 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)
  30668. var polyhedra = [];
  30669. 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]] };
  30670. 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]] };
  30671. polyhedra[2] = {
  30672. 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]],
  30673. 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]]
  30674. };
  30675. polyhedra[3] = {
  30676. 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]],
  30677. 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]]
  30678. };
  30679. polyhedra[4] = {
  30680. 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]],
  30681. 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]]
  30682. };
  30683. 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]] };
  30684. 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]] };
  30685. 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]] };
  30686. 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]] };
  30687. 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]] };
  30688. 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]] };
  30689. 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]] };
  30690. 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]] };
  30691. 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]] };
  30692. polyhedra[14] = {
  30693. 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]],
  30694. 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]]
  30695. };
  30696. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  30697. var size = options.size;
  30698. var sizeX = options.sizeX || size || 1;
  30699. var sizeY = options.sizeY || size || 1;
  30700. var sizeZ = options.sizeZ || size || 1;
  30701. var data = options.custom || polyhedra[type];
  30702. var nbfaces = data.face.length;
  30703. var faceUV = options.faceUV || new Array(nbfaces);
  30704. var faceColors = options.faceColors;
  30705. var flat = (options.flat === undefined) ? true : options.flat;
  30706. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30707. var positions = new Array();
  30708. var indices = new Array();
  30709. var normals = new Array();
  30710. var uvs = new Array();
  30711. var colors = new Array();
  30712. var index = 0;
  30713. var faceIdx = 0; // face cursor in the array "indexes"
  30714. var indexes = new Array();
  30715. var i = 0;
  30716. var f = 0;
  30717. var u, v, ang, x, y, tmp;
  30718. // default face colors and UV if undefined
  30719. if (flat) {
  30720. for (f = 0; f < nbfaces; f++) {
  30721. if (faceColors && faceColors[f] === undefined) {
  30722. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30723. }
  30724. if (faceUV && faceUV[f] === undefined) {
  30725. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30726. }
  30727. }
  30728. }
  30729. if (!flat) {
  30730. for (i = 0; i < data.vertex.length; i++) {
  30731. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  30732. uvs.push(0, 0);
  30733. }
  30734. for (f = 0; f < nbfaces; f++) {
  30735. for (i = 0; i < data.face[f].length - 2; i++) {
  30736. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  30737. }
  30738. }
  30739. }
  30740. else {
  30741. for (f = 0; f < nbfaces; f++) {
  30742. var fl = data.face[f].length; // number of vertices of the current face
  30743. ang = 2 * Math.PI / fl;
  30744. x = 0.5 * Math.tan(ang / 2);
  30745. y = 0.5;
  30746. // positions, uvs, colors
  30747. for (i = 0; i < fl; i++) {
  30748. // positions
  30749. 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);
  30750. indexes.push(index);
  30751. index++;
  30752. // uvs
  30753. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  30754. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  30755. uvs.push(u, v);
  30756. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  30757. y = x * Math.sin(ang) + y * Math.cos(ang);
  30758. x = tmp;
  30759. // colors
  30760. if (faceColors) {
  30761. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  30762. }
  30763. }
  30764. // indices from indexes
  30765. for (i = 0; i < fl - 2; i++) {
  30766. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  30767. }
  30768. faceIdx += fl;
  30769. }
  30770. }
  30771. VertexData.ComputeNormals(positions, indices, normals);
  30772. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30773. var vertexData = new VertexData();
  30774. vertexData.positions = positions;
  30775. vertexData.indices = indices;
  30776. vertexData.normals = normals;
  30777. vertexData.uvs = uvs;
  30778. if (faceColors && flat) {
  30779. vertexData.colors = colors;
  30780. }
  30781. return vertexData;
  30782. };
  30783. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  30784. /**
  30785. * Creates the VertexData of the Torus Knot.
  30786. */
  30787. VertexData.CreateTorusKnot = function (options) {
  30788. var indices = new Array();
  30789. var positions = new Array();
  30790. var normals = new Array();
  30791. var uvs = new Array();
  30792. var radius = options.radius || 2;
  30793. var tube = options.tube || 0.5;
  30794. var radialSegments = options.radialSegments || 32;
  30795. var tubularSegments = options.tubularSegments || 32;
  30796. var p = options.p || 2;
  30797. var q = options.q || 3;
  30798. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30799. // Helper
  30800. var getPos = function (angle) {
  30801. var cu = Math.cos(angle);
  30802. var su = Math.sin(angle);
  30803. var quOverP = q / p * angle;
  30804. var cs = Math.cos(quOverP);
  30805. var tx = radius * (2 + cs) * 0.5 * cu;
  30806. var ty = radius * (2 + cs) * su * 0.5;
  30807. var tz = radius * Math.sin(quOverP) * 0.5;
  30808. return new BABYLON.Vector3(tx, ty, tz);
  30809. };
  30810. // Vertices
  30811. var i;
  30812. var j;
  30813. for (i = 0; i <= radialSegments; i++) {
  30814. var modI = i % radialSegments;
  30815. var u = modI / radialSegments * 2 * p * Math.PI;
  30816. var p1 = getPos(u);
  30817. var p2 = getPos(u + 0.01);
  30818. var tang = p2.subtract(p1);
  30819. var n = p2.add(p1);
  30820. var bitan = BABYLON.Vector3.Cross(tang, n);
  30821. n = BABYLON.Vector3.Cross(bitan, tang);
  30822. bitan.normalize();
  30823. n.normalize();
  30824. for (j = 0; j < tubularSegments; j++) {
  30825. var modJ = j % tubularSegments;
  30826. var v = modJ / tubularSegments * 2 * Math.PI;
  30827. var cx = -tube * Math.cos(v);
  30828. var cy = tube * Math.sin(v);
  30829. positions.push(p1.x + cx * n.x + cy * bitan.x);
  30830. positions.push(p1.y + cx * n.y + cy * bitan.y);
  30831. positions.push(p1.z + cx * n.z + cy * bitan.z);
  30832. uvs.push(i / radialSegments);
  30833. uvs.push(j / tubularSegments);
  30834. }
  30835. }
  30836. for (i = 0; i < radialSegments; i++) {
  30837. for (j = 0; j < tubularSegments; j++) {
  30838. var jNext = (j + 1) % tubularSegments;
  30839. var a = i * tubularSegments + j;
  30840. var b = (i + 1) * tubularSegments + j;
  30841. var c = (i + 1) * tubularSegments + jNext;
  30842. var d = i * tubularSegments + jNext;
  30843. indices.push(d);
  30844. indices.push(b);
  30845. indices.push(a);
  30846. indices.push(d);
  30847. indices.push(c);
  30848. indices.push(b);
  30849. }
  30850. }
  30851. // Normals
  30852. VertexData.ComputeNormals(positions, indices, normals);
  30853. // Sides
  30854. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30855. // Result
  30856. var vertexData = new VertexData();
  30857. vertexData.indices = indices;
  30858. vertexData.positions = positions;
  30859. vertexData.normals = normals;
  30860. vertexData.uvs = uvs;
  30861. return vertexData;
  30862. };
  30863. // Tools
  30864. /**
  30865. * @param {any} - positions (number[] or Float32Array)
  30866. * @param {any} - indices (number[] or Uint16Array)
  30867. * @param {any} - normals (number[] or Float32Array)
  30868. * options (optional) :
  30869. * facetPositions : optional array of facet positions (vector3)
  30870. * facetNormals : optional array of facet normals (vector3)
  30871. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  30872. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  30873. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  30874. * bbSize : optional bounding box size data, required for facetPartitioning computation
  30875. * bInfo : optional bounding info, required for facetPartitioning computation
  30876. * useRightHandedSystem: optional boolean to for right handed system computation
  30877. * depthSort : optional boolean to enable the facet depth sort computation
  30878. * distanceTo : optional Vector3 to compute the facet depth from this location
  30879. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  30880. */
  30881. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  30882. // temporary scalar variables
  30883. var index = 0; // facet index
  30884. var p1p2x = 0.0; // p1p2 vector x coordinate
  30885. var p1p2y = 0.0; // p1p2 vector y coordinate
  30886. var p1p2z = 0.0; // p1p2 vector z coordinate
  30887. var p3p2x = 0.0; // p3p2 vector x coordinate
  30888. var p3p2y = 0.0; // p3p2 vector y coordinate
  30889. var p3p2z = 0.0; // p3p2 vector z coordinate
  30890. var faceNormalx = 0.0; // facet normal x coordinate
  30891. var faceNormaly = 0.0; // facet normal y coordinate
  30892. var faceNormalz = 0.0; // facet normal z coordinate
  30893. var length = 0.0; // facet normal length before normalization
  30894. var v1x = 0; // vector1 x index in the positions array
  30895. var v1y = 0; // vector1 y index in the positions array
  30896. var v1z = 0; // vector1 z index in the positions array
  30897. var v2x = 0; // vector2 x index in the positions array
  30898. var v2y = 0; // vector2 y index in the positions array
  30899. var v2z = 0; // vector2 z index in the positions array
  30900. var v3x = 0; // vector3 x index in the positions array
  30901. var v3y = 0; // vector3 y index in the positions array
  30902. var v3z = 0; // vector3 z index in the positions array
  30903. var computeFacetNormals = false;
  30904. var computeFacetPositions = false;
  30905. var computeFacetPartitioning = false;
  30906. var computeDepthSort = false;
  30907. var faceNormalSign = 1;
  30908. var ratio = 0;
  30909. var distanceTo = null;
  30910. if (options) {
  30911. computeFacetNormals = (options.facetNormals) ? true : false;
  30912. computeFacetPositions = (options.facetPositions) ? true : false;
  30913. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  30914. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  30915. ratio = options.ratio || 0;
  30916. computeDepthSort = (options.depthSort) ? true : false;
  30917. distanceTo = (options.distanceTo);
  30918. if (computeDepthSort) {
  30919. if (distanceTo === undefined) {
  30920. distanceTo = BABYLON.Vector3.Zero();
  30921. }
  30922. var depthSortedFacets = options.depthSortedFacets;
  30923. }
  30924. }
  30925. // facetPartitioning reinit if needed
  30926. var xSubRatio = 0;
  30927. var ySubRatio = 0;
  30928. var zSubRatio = 0;
  30929. var subSq = 0;
  30930. if (computeFacetPartitioning && options && options.bbSize) {
  30931. var ox = 0; // X partitioning index for facet position
  30932. var oy = 0; // Y partinioning index for facet position
  30933. var oz = 0; // Z partinioning index for facet position
  30934. var b1x = 0; // X partitioning index for facet v1 vertex
  30935. var b1y = 0; // Y partitioning index for facet v1 vertex
  30936. var b1z = 0; // z partitioning index for facet v1 vertex
  30937. var b2x = 0; // X partitioning index for facet v2 vertex
  30938. var b2y = 0; // Y partitioning index for facet v2 vertex
  30939. var b2z = 0; // Z partitioning index for facet v2 vertex
  30940. var b3x = 0; // X partitioning index for facet v3 vertex
  30941. var b3y = 0; // Y partitioning index for facet v3 vertex
  30942. var b3z = 0; // Z partitioning index for facet v3 vertex
  30943. var block_idx_o = 0; // facet barycenter block index
  30944. var block_idx_v1 = 0; // v1 vertex block index
  30945. var block_idx_v2 = 0; // v2 vertex block index
  30946. var block_idx_v3 = 0; // v3 vertex block index
  30947. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  30948. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  30949. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  30950. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  30951. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  30952. subSq = options.subDiv.max * options.subDiv.max;
  30953. options.facetPartitioning.length = 0;
  30954. }
  30955. // reset the normals
  30956. for (index = 0; index < positions.length; index++) {
  30957. normals[index] = 0.0;
  30958. }
  30959. // Loop : 1 indice triplet = 1 facet
  30960. var nbFaces = (indices.length / 3) | 0;
  30961. for (index = 0; index < nbFaces; index++) {
  30962. // get the indexes of the coordinates of each vertex of the facet
  30963. v1x = indices[index * 3] * 3;
  30964. v1y = v1x + 1;
  30965. v1z = v1x + 2;
  30966. v2x = indices[index * 3 + 1] * 3;
  30967. v2y = v2x + 1;
  30968. v2z = v2x + 2;
  30969. v3x = indices[index * 3 + 2] * 3;
  30970. v3y = v3x + 1;
  30971. v3z = v3x + 2;
  30972. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  30973. p1p2y = positions[v1y] - positions[v2y];
  30974. p1p2z = positions[v1z] - positions[v2z];
  30975. p3p2x = positions[v3x] - positions[v2x];
  30976. p3p2y = positions[v3y] - positions[v2y];
  30977. p3p2z = positions[v3z] - positions[v2z];
  30978. // compute the face normal with the cross product
  30979. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  30980. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  30981. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  30982. // normalize this normal and store it in the array facetData
  30983. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30984. length = (length === 0) ? 1.0 : length;
  30985. faceNormalx /= length;
  30986. faceNormaly /= length;
  30987. faceNormalz /= length;
  30988. if (computeFacetNormals && options) {
  30989. options.facetNormals[index].x = faceNormalx;
  30990. options.facetNormals[index].y = faceNormaly;
  30991. options.facetNormals[index].z = faceNormalz;
  30992. }
  30993. if (computeFacetPositions && options) {
  30994. // compute and the facet barycenter coordinates in the array facetPositions
  30995. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  30996. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  30997. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  30998. }
  30999. if (computeFacetPartitioning && options) {
  31000. // store the facet indexes in arrays in the main facetPartitioning array :
  31001. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  31002. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  31003. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  31004. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  31005. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31006. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31007. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31008. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31009. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31010. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31011. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31012. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31013. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31014. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  31015. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  31016. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  31017. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  31018. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  31019. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  31020. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  31021. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  31022. // push each facet index in each block containing the vertex
  31023. options.facetPartitioning[block_idx_v1].push(index);
  31024. if (block_idx_v2 != block_idx_v1) {
  31025. options.facetPartitioning[block_idx_v2].push(index);
  31026. }
  31027. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  31028. options.facetPartitioning[block_idx_v3].push(index);
  31029. }
  31030. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  31031. options.facetPartitioning[block_idx_o].push(index);
  31032. }
  31033. }
  31034. if (computeDepthSort && options && options.facetPositions) {
  31035. var dsf = depthSortedFacets[index];
  31036. dsf.ind = index * 3;
  31037. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  31038. }
  31039. // compute the normals anyway
  31040. normals[v1x] += faceNormalx; // accumulate all the normals per face
  31041. normals[v1y] += faceNormaly;
  31042. normals[v1z] += faceNormalz;
  31043. normals[v2x] += faceNormalx;
  31044. normals[v2y] += faceNormaly;
  31045. normals[v2z] += faceNormalz;
  31046. normals[v3x] += faceNormalx;
  31047. normals[v3y] += faceNormaly;
  31048. normals[v3z] += faceNormalz;
  31049. }
  31050. // last normalization of each normal
  31051. for (index = 0; index < normals.length / 3; index++) {
  31052. faceNormalx = normals[index * 3];
  31053. faceNormaly = normals[index * 3 + 1];
  31054. faceNormalz = normals[index * 3 + 2];
  31055. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31056. length = (length === 0) ? 1.0 : length;
  31057. faceNormalx /= length;
  31058. faceNormaly /= length;
  31059. faceNormalz /= length;
  31060. normals[index * 3] = faceNormalx;
  31061. normals[index * 3 + 1] = faceNormaly;
  31062. normals[index * 3 + 2] = faceNormalz;
  31063. }
  31064. };
  31065. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  31066. var li = indices.length;
  31067. var ln = normals.length;
  31068. var i;
  31069. var n;
  31070. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31071. switch (sideOrientation) {
  31072. case BABYLON.Mesh.FRONTSIDE:
  31073. // nothing changed
  31074. break;
  31075. case BABYLON.Mesh.BACKSIDE:
  31076. var tmp;
  31077. // indices
  31078. for (i = 0; i < li; i += 3) {
  31079. tmp = indices[i];
  31080. indices[i] = indices[i + 2];
  31081. indices[i + 2] = tmp;
  31082. }
  31083. // normals
  31084. for (n = 0; n < ln; n++) {
  31085. normals[n] = -normals[n];
  31086. }
  31087. break;
  31088. case BABYLON.Mesh.DOUBLESIDE:
  31089. // positions
  31090. var lp = positions.length;
  31091. var l = lp / 3;
  31092. for (var p = 0; p < lp; p++) {
  31093. positions[lp + p] = positions[p];
  31094. }
  31095. // indices
  31096. for (i = 0; i < li; i += 3) {
  31097. indices[i + li] = indices[i + 2] + l;
  31098. indices[i + 1 + li] = indices[i + 1] + l;
  31099. indices[i + 2 + li] = indices[i] + l;
  31100. }
  31101. // normals
  31102. for (n = 0; n < ln; n++) {
  31103. normals[ln + n] = -normals[n];
  31104. }
  31105. // uvs
  31106. var lu = uvs.length;
  31107. var u = 0;
  31108. for (u = 0; u < lu; u++) {
  31109. uvs[u + lu] = uvs[u];
  31110. }
  31111. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  31112. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  31113. u = 0;
  31114. for (i = 0; i < lu / 2; i++) {
  31115. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  31116. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  31117. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  31118. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  31119. u += 2;
  31120. }
  31121. break;
  31122. }
  31123. };
  31124. /**
  31125. * Creates a new VertexData from the imported parameters.
  31126. */
  31127. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  31128. var vertexData = new VertexData();
  31129. // positions
  31130. var positions = parsedVertexData.positions;
  31131. if (positions) {
  31132. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  31133. }
  31134. // normals
  31135. var normals = parsedVertexData.normals;
  31136. if (normals) {
  31137. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  31138. }
  31139. // tangents
  31140. var tangents = parsedVertexData.tangents;
  31141. if (tangents) {
  31142. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  31143. }
  31144. // uvs
  31145. var uvs = parsedVertexData.uvs;
  31146. if (uvs) {
  31147. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  31148. }
  31149. // uv2s
  31150. var uv2s = parsedVertexData.uv2s;
  31151. if (uv2s) {
  31152. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  31153. }
  31154. // uv3s
  31155. var uv3s = parsedVertexData.uv3s;
  31156. if (uv3s) {
  31157. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  31158. }
  31159. // uv4s
  31160. var uv4s = parsedVertexData.uv4s;
  31161. if (uv4s) {
  31162. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  31163. }
  31164. // uv5s
  31165. var uv5s = parsedVertexData.uv5s;
  31166. if (uv5s) {
  31167. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  31168. }
  31169. // uv6s
  31170. var uv6s = parsedVertexData.uv6s;
  31171. if (uv6s) {
  31172. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  31173. }
  31174. // colors
  31175. var colors = parsedVertexData.colors;
  31176. if (colors) {
  31177. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  31178. }
  31179. // matricesIndices
  31180. var matricesIndices = parsedVertexData.matricesIndices;
  31181. if (matricesIndices) {
  31182. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  31183. }
  31184. // matricesWeights
  31185. var matricesWeights = parsedVertexData.matricesWeights;
  31186. if (matricesWeights) {
  31187. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  31188. }
  31189. // indices
  31190. var indices = parsedVertexData.indices;
  31191. if (indices) {
  31192. vertexData.indices = indices;
  31193. }
  31194. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  31195. };
  31196. return VertexData;
  31197. }());
  31198. BABYLON.VertexData = VertexData;
  31199. })(BABYLON || (BABYLON = {}));
  31200. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  31201. var BABYLON;
  31202. (function (BABYLON) {
  31203. var Geometry = /** @class */ (function () {
  31204. function Geometry(id, scene, vertexData, updatable, mesh) {
  31205. if (updatable === void 0) { updatable = false; }
  31206. if (mesh === void 0) { mesh = null; }
  31207. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31208. this._totalVertices = 0;
  31209. this._isDisposed = false;
  31210. this._indexBufferIsUpdatable = false;
  31211. this.id = id;
  31212. this._engine = scene.getEngine();
  31213. this._meshes = [];
  31214. this._scene = scene;
  31215. //Init vertex buffer cache
  31216. this._vertexBuffers = {};
  31217. this._indices = [];
  31218. this._updatable = updatable;
  31219. // vertexData
  31220. if (vertexData) {
  31221. this.setAllVerticesData(vertexData, updatable);
  31222. }
  31223. else {
  31224. this._totalVertices = 0;
  31225. this._indices = [];
  31226. }
  31227. if (this._engine.getCaps().vertexArrayObject) {
  31228. this._vertexArrayObjects = {};
  31229. }
  31230. // applyToMesh
  31231. if (mesh) {
  31232. if (mesh.getClassName() === "LinesMesh") {
  31233. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  31234. this.updateExtend();
  31235. }
  31236. this.applyToMesh(mesh);
  31237. mesh.computeWorldMatrix(true);
  31238. }
  31239. }
  31240. Object.defineProperty(Geometry.prototype, "boundingBias", {
  31241. /**
  31242. * 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
  31243. * @returns The Bias Vector
  31244. */
  31245. get: function () {
  31246. return this._boundingBias;
  31247. },
  31248. set: function (value) {
  31249. if (this._boundingBias && this._boundingBias.equals(value)) {
  31250. return;
  31251. }
  31252. this._boundingBias = value.clone();
  31253. this.updateBoundingInfo(true, null);
  31254. },
  31255. enumerable: true,
  31256. configurable: true
  31257. });
  31258. Geometry.CreateGeometryForMesh = function (mesh) {
  31259. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  31260. geometry.applyToMesh(mesh);
  31261. return geometry;
  31262. };
  31263. Object.defineProperty(Geometry.prototype, "extend", {
  31264. get: function () {
  31265. return this._extend;
  31266. },
  31267. enumerable: true,
  31268. configurable: true
  31269. });
  31270. Geometry.prototype.getScene = function () {
  31271. return this._scene;
  31272. };
  31273. Geometry.prototype.getEngine = function () {
  31274. return this._engine;
  31275. };
  31276. Geometry.prototype.isReady = function () {
  31277. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  31278. };
  31279. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  31280. get: function () {
  31281. for (var index = 0; index < this._meshes.length; index++) {
  31282. if (!this._meshes[index].doNotSerialize) {
  31283. return false;
  31284. }
  31285. }
  31286. return true;
  31287. },
  31288. enumerable: true,
  31289. configurable: true
  31290. });
  31291. Geometry.prototype._rebuild = function () {
  31292. if (this._vertexArrayObjects) {
  31293. this._vertexArrayObjects = {};
  31294. }
  31295. // Index buffer
  31296. if (this._meshes.length !== 0 && this._indices) {
  31297. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31298. }
  31299. // Vertex buffers
  31300. for (var key in this._vertexBuffers) {
  31301. var vertexBuffer = this._vertexBuffers[key];
  31302. vertexBuffer._rebuild();
  31303. }
  31304. };
  31305. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  31306. vertexData.applyToGeometry(this, updatable);
  31307. this.notifyUpdate();
  31308. };
  31309. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31310. if (updatable === void 0) { updatable = false; }
  31311. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  31312. this.setVerticesBuffer(buffer);
  31313. };
  31314. Geometry.prototype.removeVerticesData = function (kind) {
  31315. if (this._vertexBuffers[kind]) {
  31316. this._vertexBuffers[kind].dispose();
  31317. delete this._vertexBuffers[kind];
  31318. }
  31319. };
  31320. Geometry.prototype.setVerticesBuffer = function (buffer) {
  31321. var kind = buffer.getKind();
  31322. if (this._vertexBuffers[kind]) {
  31323. this._vertexBuffers[kind].dispose();
  31324. }
  31325. this._vertexBuffers[kind] = buffer;
  31326. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31327. var data = buffer.getData();
  31328. var stride = buffer.getStrideSize();
  31329. this._totalVertices = data.length / stride;
  31330. this.updateExtend(data, stride);
  31331. this._resetPointsArrayCache();
  31332. var meshes = this._meshes;
  31333. var numOfMeshes = meshes.length;
  31334. for (var index = 0; index < numOfMeshes; index++) {
  31335. var mesh = meshes[index];
  31336. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31337. mesh._createGlobalSubMesh(false);
  31338. mesh.computeWorldMatrix(true);
  31339. }
  31340. }
  31341. this.notifyUpdate(kind);
  31342. if (this._vertexArrayObjects) {
  31343. this._disposeVertexArrayObjects();
  31344. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  31345. }
  31346. };
  31347. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  31348. var vertexBuffer = this.getVertexBuffer(kind);
  31349. if (!vertexBuffer) {
  31350. return;
  31351. }
  31352. vertexBuffer.updateDirectly(data, offset);
  31353. this.notifyUpdate(kind);
  31354. };
  31355. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  31356. if (updateExtends === void 0) { updateExtends = false; }
  31357. var vertexBuffer = this.getVertexBuffer(kind);
  31358. if (!vertexBuffer) {
  31359. return;
  31360. }
  31361. vertexBuffer.update(data);
  31362. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31363. var stride = vertexBuffer.getStrideSize();
  31364. this._totalVertices = data.length / stride;
  31365. this.updateBoundingInfo(updateExtends, data);
  31366. }
  31367. this.notifyUpdate(kind);
  31368. };
  31369. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  31370. if (updateExtends) {
  31371. this.updateExtend(data);
  31372. }
  31373. var meshes = this._meshes;
  31374. var numOfMeshes = meshes.length;
  31375. this._resetPointsArrayCache();
  31376. for (var index = 0; index < numOfMeshes; index++) {
  31377. var mesh = meshes[index];
  31378. if (updateExtends) {
  31379. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31380. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31381. var subMesh = mesh.subMeshes[subIndex];
  31382. subMesh.refreshBoundingInfo();
  31383. }
  31384. }
  31385. }
  31386. };
  31387. Geometry.prototype._bind = function (effect, indexToBind) {
  31388. if (!effect) {
  31389. return;
  31390. }
  31391. if (indexToBind === undefined) {
  31392. indexToBind = this._indexBuffer;
  31393. }
  31394. var vbs = this.getVertexBuffers();
  31395. if (!vbs) {
  31396. return;
  31397. }
  31398. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  31399. this._engine.bindBuffers(vbs, indexToBind, effect);
  31400. return;
  31401. }
  31402. // Using VAO
  31403. if (!this._vertexArrayObjects[effect.key]) {
  31404. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  31405. }
  31406. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  31407. };
  31408. Geometry.prototype.getTotalVertices = function () {
  31409. if (!this.isReady()) {
  31410. return 0;
  31411. }
  31412. return this._totalVertices;
  31413. };
  31414. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31415. var vertexBuffer = this.getVertexBuffer(kind);
  31416. if (!vertexBuffer) {
  31417. return null;
  31418. }
  31419. var orig = vertexBuffer.getData();
  31420. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  31421. return orig;
  31422. }
  31423. else {
  31424. var len = orig.length;
  31425. var copy = [];
  31426. for (var i = 0; i < len; i++) {
  31427. copy.push(orig[i]);
  31428. }
  31429. return copy;
  31430. }
  31431. };
  31432. /**
  31433. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31434. * Possible `kind` values :
  31435. * - BABYLON.VertexBuffer.PositionKind
  31436. * - BABYLON.VertexBuffer.UVKind
  31437. * - BABYLON.VertexBuffer.UV2Kind
  31438. * - BABYLON.VertexBuffer.UV3Kind
  31439. * - BABYLON.VertexBuffer.UV4Kind
  31440. * - BABYLON.VertexBuffer.UV5Kind
  31441. * - BABYLON.VertexBuffer.UV6Kind
  31442. * - BABYLON.VertexBuffer.ColorKind
  31443. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31444. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31445. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31446. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31447. */
  31448. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  31449. var vb = this._vertexBuffers[kind];
  31450. if (!vb) {
  31451. return false;
  31452. }
  31453. return vb.isUpdatable();
  31454. };
  31455. Geometry.prototype.getVertexBuffer = function (kind) {
  31456. if (!this.isReady()) {
  31457. return null;
  31458. }
  31459. return this._vertexBuffers[kind];
  31460. };
  31461. Geometry.prototype.getVertexBuffers = function () {
  31462. if (!this.isReady()) {
  31463. return null;
  31464. }
  31465. return this._vertexBuffers;
  31466. };
  31467. Geometry.prototype.isVerticesDataPresent = function (kind) {
  31468. if (!this._vertexBuffers) {
  31469. if (this._delayInfo) {
  31470. return this._delayInfo.indexOf(kind) !== -1;
  31471. }
  31472. return false;
  31473. }
  31474. return this._vertexBuffers[kind] !== undefined;
  31475. };
  31476. Geometry.prototype.getVerticesDataKinds = function () {
  31477. var result = [];
  31478. var kind;
  31479. if (!this._vertexBuffers && this._delayInfo) {
  31480. for (kind in this._delayInfo) {
  31481. result.push(kind);
  31482. }
  31483. }
  31484. else {
  31485. for (kind in this._vertexBuffers) {
  31486. result.push(kind);
  31487. }
  31488. }
  31489. return result;
  31490. };
  31491. Geometry.prototype.updateIndices = function (indices, offset) {
  31492. if (!this._indexBuffer) {
  31493. return;
  31494. }
  31495. if (!this._indexBufferIsUpdatable) {
  31496. this.setIndices(indices, null, true);
  31497. }
  31498. else {
  31499. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  31500. }
  31501. };
  31502. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  31503. if (totalVertices === void 0) { totalVertices = null; }
  31504. if (updatable === void 0) { updatable = false; }
  31505. if (this._indexBuffer) {
  31506. this._engine._releaseBuffer(this._indexBuffer);
  31507. }
  31508. this._disposeVertexArrayObjects();
  31509. this._indices = indices;
  31510. this._indexBufferIsUpdatable = updatable;
  31511. if (this._meshes.length !== 0 && this._indices) {
  31512. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  31513. }
  31514. if (totalVertices != undefined) {
  31515. this._totalVertices = totalVertices;
  31516. }
  31517. var meshes = this._meshes;
  31518. var numOfMeshes = meshes.length;
  31519. for (var index = 0; index < numOfMeshes; index++) {
  31520. meshes[index]._createGlobalSubMesh(true);
  31521. }
  31522. this.notifyUpdate();
  31523. };
  31524. Geometry.prototype.getTotalIndices = function () {
  31525. if (!this.isReady()) {
  31526. return 0;
  31527. }
  31528. return this._indices.length;
  31529. };
  31530. Geometry.prototype.getIndices = function (copyWhenShared) {
  31531. if (!this.isReady()) {
  31532. return null;
  31533. }
  31534. var orig = this._indices;
  31535. if (!copyWhenShared || this._meshes.length === 1) {
  31536. return orig;
  31537. }
  31538. else {
  31539. var len = orig.length;
  31540. var copy = [];
  31541. for (var i = 0; i < len; i++) {
  31542. copy.push(orig[i]);
  31543. }
  31544. return copy;
  31545. }
  31546. };
  31547. Geometry.prototype.getIndexBuffer = function () {
  31548. if (!this.isReady()) {
  31549. return null;
  31550. }
  31551. return this._indexBuffer;
  31552. };
  31553. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  31554. if (effect === void 0) { effect = null; }
  31555. if (!effect || !this._vertexArrayObjects) {
  31556. return;
  31557. }
  31558. if (this._vertexArrayObjects[effect.key]) {
  31559. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  31560. delete this._vertexArrayObjects[effect.key];
  31561. }
  31562. };
  31563. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  31564. var meshes = this._meshes;
  31565. var index = meshes.indexOf(mesh);
  31566. if (index === -1) {
  31567. return;
  31568. }
  31569. meshes.splice(index, 1);
  31570. mesh._geometry = null;
  31571. if (meshes.length === 0 && shouldDispose) {
  31572. this.dispose();
  31573. }
  31574. };
  31575. Geometry.prototype.applyToMesh = function (mesh) {
  31576. if (mesh._geometry === this) {
  31577. return;
  31578. }
  31579. var previousGeometry = mesh._geometry;
  31580. if (previousGeometry) {
  31581. previousGeometry.releaseForMesh(mesh);
  31582. }
  31583. var meshes = this._meshes;
  31584. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  31585. mesh._geometry = this;
  31586. this._scene.pushGeometry(this);
  31587. meshes.push(mesh);
  31588. if (this.isReady()) {
  31589. this._applyToMesh(mesh);
  31590. }
  31591. else {
  31592. mesh._boundingInfo = this._boundingInfo;
  31593. }
  31594. };
  31595. Geometry.prototype.updateExtend = function (data, stride) {
  31596. if (data === void 0) { data = null; }
  31597. if (!data) {
  31598. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  31599. }
  31600. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  31601. };
  31602. Geometry.prototype._applyToMesh = function (mesh) {
  31603. var numOfMeshes = this._meshes.length;
  31604. // vertexBuffers
  31605. for (var kind in this._vertexBuffers) {
  31606. if (numOfMeshes === 1) {
  31607. this._vertexBuffers[kind].create();
  31608. }
  31609. var buffer = this._vertexBuffers[kind].getBuffer();
  31610. if (buffer)
  31611. buffer.references = numOfMeshes;
  31612. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31613. if (!this._extend) {
  31614. this.updateExtend(this._vertexBuffers[kind].getData());
  31615. }
  31616. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31617. mesh._createGlobalSubMesh(false);
  31618. //bounding info was just created again, world matrix should be applied again.
  31619. mesh._updateBoundingInfo();
  31620. }
  31621. }
  31622. // indexBuffer
  31623. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  31624. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31625. }
  31626. if (this._indexBuffer) {
  31627. this._indexBuffer.references = numOfMeshes;
  31628. }
  31629. };
  31630. Geometry.prototype.notifyUpdate = function (kind) {
  31631. if (this.onGeometryUpdated) {
  31632. this.onGeometryUpdated(this, kind);
  31633. }
  31634. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  31635. var mesh = _a[_i];
  31636. mesh._markSubMeshesAsAttributesDirty();
  31637. }
  31638. };
  31639. Geometry.prototype.load = function (scene, onLoaded) {
  31640. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31641. return;
  31642. }
  31643. if (this.isReady()) {
  31644. if (onLoaded) {
  31645. onLoaded();
  31646. }
  31647. return;
  31648. }
  31649. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31650. this._queueLoad(scene, onLoaded);
  31651. };
  31652. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  31653. var _this = this;
  31654. if (!this.delayLoadingFile) {
  31655. return;
  31656. }
  31657. scene._addPendingData(this);
  31658. scene._loadFile(this.delayLoadingFile, function (data) {
  31659. if (!_this._delayLoadingFunction) {
  31660. return;
  31661. }
  31662. _this._delayLoadingFunction(JSON.parse(data), _this);
  31663. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31664. _this._delayInfo = [];
  31665. scene._removePendingData(_this);
  31666. var meshes = _this._meshes;
  31667. var numOfMeshes = meshes.length;
  31668. for (var index = 0; index < numOfMeshes; index++) {
  31669. _this._applyToMesh(meshes[index]);
  31670. }
  31671. if (onLoaded) {
  31672. onLoaded();
  31673. }
  31674. }, undefined, true);
  31675. };
  31676. /**
  31677. * Invert the geometry to move from a right handed system to a left handed one.
  31678. */
  31679. Geometry.prototype.toLeftHanded = function () {
  31680. // Flip faces
  31681. var tIndices = this.getIndices(false);
  31682. if (tIndices != null && tIndices.length > 0) {
  31683. for (var i = 0; i < tIndices.length; i += 3) {
  31684. var tTemp = tIndices[i + 0];
  31685. tIndices[i + 0] = tIndices[i + 2];
  31686. tIndices[i + 2] = tTemp;
  31687. }
  31688. this.setIndices(tIndices);
  31689. }
  31690. // Negate position.z
  31691. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  31692. if (tPositions != null && tPositions.length > 0) {
  31693. for (var i = 0; i < tPositions.length; i += 3) {
  31694. tPositions[i + 2] = -tPositions[i + 2];
  31695. }
  31696. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  31697. }
  31698. // Negate normal.z
  31699. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  31700. if (tNormals != null && tNormals.length > 0) {
  31701. for (var i = 0; i < tNormals.length; i += 3) {
  31702. tNormals[i + 2] = -tNormals[i + 2];
  31703. }
  31704. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  31705. }
  31706. };
  31707. // Cache
  31708. Geometry.prototype._resetPointsArrayCache = function () {
  31709. this._positions = null;
  31710. };
  31711. Geometry.prototype._generatePointsArray = function () {
  31712. if (this._positions)
  31713. return true;
  31714. this._positions = [];
  31715. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31716. if (!data) {
  31717. return false;
  31718. }
  31719. for (var index = 0; index < data.length; index += 3) {
  31720. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  31721. }
  31722. return true;
  31723. };
  31724. Geometry.prototype.isDisposed = function () {
  31725. return this._isDisposed;
  31726. };
  31727. Geometry.prototype._disposeVertexArrayObjects = function () {
  31728. if (this._vertexArrayObjects) {
  31729. for (var kind in this._vertexArrayObjects) {
  31730. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  31731. }
  31732. this._vertexArrayObjects = {};
  31733. }
  31734. };
  31735. Geometry.prototype.dispose = function () {
  31736. var meshes = this._meshes;
  31737. var numOfMeshes = meshes.length;
  31738. var index;
  31739. for (index = 0; index < numOfMeshes; index++) {
  31740. this.releaseForMesh(meshes[index]);
  31741. }
  31742. this._meshes = [];
  31743. this._disposeVertexArrayObjects();
  31744. for (var kind in this._vertexBuffers) {
  31745. this._vertexBuffers[kind].dispose();
  31746. }
  31747. this._vertexBuffers = {};
  31748. this._totalVertices = 0;
  31749. if (this._indexBuffer) {
  31750. this._engine._releaseBuffer(this._indexBuffer);
  31751. }
  31752. this._indexBuffer = null;
  31753. this._indices = [];
  31754. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31755. this.delayLoadingFile = null;
  31756. this._delayLoadingFunction = null;
  31757. this._delayInfo = [];
  31758. this._boundingInfo = null;
  31759. this._scene.removeGeometry(this);
  31760. this._isDisposed = true;
  31761. };
  31762. Geometry.prototype.copy = function (id) {
  31763. var vertexData = new BABYLON.VertexData();
  31764. vertexData.indices = [];
  31765. var indices = this.getIndices();
  31766. if (indices) {
  31767. for (var index = 0; index < indices.length; index++) {
  31768. vertexData.indices.push(indices[index]);
  31769. }
  31770. }
  31771. var updatable = false;
  31772. var stopChecking = false;
  31773. var kind;
  31774. for (kind in this._vertexBuffers) {
  31775. // using slice() to make a copy of the array and not just reference it
  31776. var data = this.getVerticesData(kind);
  31777. if (data instanceof Float32Array) {
  31778. vertexData.set(new Float32Array(data), kind);
  31779. }
  31780. else {
  31781. vertexData.set(data.slice(0), kind);
  31782. }
  31783. if (!stopChecking) {
  31784. var vb = this.getVertexBuffer(kind);
  31785. if (vb) {
  31786. updatable = vb.isUpdatable();
  31787. stopChecking = !updatable;
  31788. }
  31789. }
  31790. }
  31791. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  31792. geometry.delayLoadState = this.delayLoadState;
  31793. geometry.delayLoadingFile = this.delayLoadingFile;
  31794. geometry._delayLoadingFunction = this._delayLoadingFunction;
  31795. for (kind in this._delayInfo) {
  31796. geometry._delayInfo = geometry._delayInfo || [];
  31797. geometry._delayInfo.push(kind);
  31798. }
  31799. // Bounding info
  31800. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31801. return geometry;
  31802. };
  31803. Geometry.prototype.serialize = function () {
  31804. var serializationObject = {};
  31805. serializationObject.id = this.id;
  31806. serializationObject.updatable = this._updatable;
  31807. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  31808. serializationObject.tags = BABYLON.Tags.GetTags(this);
  31809. }
  31810. return serializationObject;
  31811. };
  31812. Geometry.prototype.toNumberArray = function (origin) {
  31813. if (Array.isArray(origin)) {
  31814. return origin;
  31815. }
  31816. else {
  31817. return Array.prototype.slice.call(origin);
  31818. }
  31819. };
  31820. Geometry.prototype.serializeVerticeData = function () {
  31821. var serializationObject = this.serialize();
  31822. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31823. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  31824. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  31825. serializationObject.positions._updatable = true;
  31826. }
  31827. }
  31828. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31829. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  31830. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  31831. serializationObject.normals._updatable = true;
  31832. }
  31833. }
  31834. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31835. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  31836. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  31837. serializationObject.uvs._updatable = true;
  31838. }
  31839. }
  31840. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31841. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  31842. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  31843. serializationObject.uv2s._updatable = true;
  31844. }
  31845. }
  31846. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  31847. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  31848. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  31849. serializationObject.uv3s._updatable = true;
  31850. }
  31851. }
  31852. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  31853. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  31854. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  31855. serializationObject.uv4s._updatable = true;
  31856. }
  31857. }
  31858. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  31859. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  31860. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  31861. serializationObject.uv5s._updatable = true;
  31862. }
  31863. }
  31864. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  31865. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  31866. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  31867. serializationObject.uv6s._updatable = true;
  31868. }
  31869. }
  31870. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  31871. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  31872. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  31873. serializationObject.colors._updatable = true;
  31874. }
  31875. }
  31876. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31877. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  31878. serializationObject.matricesIndices._isExpanded = true;
  31879. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31880. serializationObject.matricesIndices._updatable = true;
  31881. }
  31882. }
  31883. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31884. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  31885. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31886. serializationObject.matricesWeights._updatable = true;
  31887. }
  31888. }
  31889. serializationObject.indices = this.toNumberArray(this.getIndices());
  31890. return serializationObject;
  31891. };
  31892. // Statics
  31893. Geometry.ExtractFromMesh = function (mesh, id) {
  31894. var geometry = mesh._geometry;
  31895. if (!geometry) {
  31896. return null;
  31897. }
  31898. return geometry.copy(id);
  31899. };
  31900. /**
  31901. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  31902. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  31903. * Be aware Math.random() could cause collisions, but:
  31904. * "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"
  31905. */
  31906. Geometry.RandomId = function () {
  31907. return BABYLON.Tools.RandomId();
  31908. };
  31909. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  31910. var scene = mesh.getScene();
  31911. // Geometry
  31912. var geometryId = parsedGeometry.geometryId;
  31913. if (geometryId) {
  31914. var geometry = scene.getGeometryByID(geometryId);
  31915. if (geometry) {
  31916. geometry.applyToMesh(mesh);
  31917. }
  31918. }
  31919. else if (parsedGeometry instanceof ArrayBuffer) {
  31920. var binaryInfo = mesh._binaryInfo;
  31921. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  31922. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  31923. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  31924. }
  31925. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  31926. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  31927. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  31928. }
  31929. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  31930. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  31931. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  31932. }
  31933. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  31934. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  31935. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  31936. }
  31937. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  31938. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  31939. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  31940. }
  31941. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  31942. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  31943. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  31944. }
  31945. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  31946. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  31947. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  31948. }
  31949. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  31950. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  31951. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  31952. }
  31953. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  31954. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  31955. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  31956. }
  31957. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  31958. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  31959. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  31960. }
  31961. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  31962. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  31963. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  31964. }
  31965. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  31966. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  31967. mesh.setIndices(indicesData, null);
  31968. }
  31969. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  31970. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  31971. mesh.subMeshes = [];
  31972. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  31973. var materialIndex = subMeshesData[(i * 5) + 0];
  31974. var verticesStart = subMeshesData[(i * 5) + 1];
  31975. var verticesCount = subMeshesData[(i * 5) + 2];
  31976. var indexStart = subMeshesData[(i * 5) + 3];
  31977. var indexCount = subMeshesData[(i * 5) + 4];
  31978. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  31979. }
  31980. }
  31981. }
  31982. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  31983. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  31984. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  31985. if (parsedGeometry.uvs) {
  31986. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  31987. }
  31988. if (parsedGeometry.uvs2) {
  31989. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  31990. }
  31991. if (parsedGeometry.uvs3) {
  31992. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  31993. }
  31994. if (parsedGeometry.uvs4) {
  31995. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  31996. }
  31997. if (parsedGeometry.uvs5) {
  31998. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  31999. }
  32000. if (parsedGeometry.uvs6) {
  32001. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  32002. }
  32003. if (parsedGeometry.colors) {
  32004. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  32005. }
  32006. if (parsedGeometry.matricesIndices) {
  32007. if (!parsedGeometry.matricesIndices._isExpanded) {
  32008. var floatIndices = [];
  32009. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  32010. var matricesIndex = parsedGeometry.matricesIndices[i];
  32011. floatIndices.push(matricesIndex & 0x000000FF);
  32012. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32013. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32014. floatIndices.push(matricesIndex >> 24);
  32015. }
  32016. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  32017. }
  32018. else {
  32019. delete parsedGeometry.matricesIndices._isExpanded;
  32020. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  32021. }
  32022. }
  32023. if (parsedGeometry.matricesIndicesExtra) {
  32024. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  32025. var floatIndices = [];
  32026. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  32027. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  32028. floatIndices.push(matricesIndex & 0x000000FF);
  32029. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32030. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32031. floatIndices.push(matricesIndex >> 24);
  32032. }
  32033. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  32034. }
  32035. else {
  32036. delete parsedGeometry.matricesIndices._isExpanded;
  32037. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  32038. }
  32039. }
  32040. if (parsedGeometry.matricesWeights) {
  32041. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  32042. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  32043. }
  32044. if (parsedGeometry.matricesWeightsExtra) {
  32045. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  32046. }
  32047. mesh.setIndices(parsedGeometry.indices, null);
  32048. }
  32049. // SubMeshes
  32050. if (parsedGeometry.subMeshes) {
  32051. mesh.subMeshes = [];
  32052. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  32053. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  32054. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  32055. }
  32056. }
  32057. // Flat shading
  32058. if (mesh._shouldGenerateFlatShading) {
  32059. mesh.convertToFlatShadedMesh();
  32060. delete mesh._shouldGenerateFlatShading;
  32061. }
  32062. // Update
  32063. mesh.computeWorldMatrix(true);
  32064. // Octree
  32065. var sceneOctree = scene.selectionOctree;
  32066. if (sceneOctree !== undefined && sceneOctree !== null) {
  32067. sceneOctree.addMesh(mesh);
  32068. }
  32069. };
  32070. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  32071. var epsilon = 1e-3;
  32072. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  32073. return;
  32074. }
  32075. var noInfluenceBoneIndex = 0.0;
  32076. if (parsedGeometry.skeletonId > -1) {
  32077. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  32078. if (!skeleton) {
  32079. return;
  32080. }
  32081. noInfluenceBoneIndex = skeleton.bones.length;
  32082. }
  32083. else {
  32084. return;
  32085. }
  32086. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32087. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32088. var matricesWeights = parsedGeometry.matricesWeights;
  32089. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  32090. var influencers = parsedGeometry.numBoneInfluencer;
  32091. var size = matricesWeights.length;
  32092. for (var i = 0; i < size; i += 4) {
  32093. var weight = 0.0;
  32094. var firstZeroWeight = -1;
  32095. for (var j = 0; j < 4; j++) {
  32096. var w = matricesWeights[i + j];
  32097. weight += w;
  32098. if (w < epsilon && firstZeroWeight < 0) {
  32099. firstZeroWeight = j;
  32100. }
  32101. }
  32102. if (matricesWeightsExtra) {
  32103. for (var j = 0; j < 4; j++) {
  32104. var w = matricesWeightsExtra[i + j];
  32105. weight += w;
  32106. if (w < epsilon && firstZeroWeight < 0) {
  32107. firstZeroWeight = j + 4;
  32108. }
  32109. }
  32110. }
  32111. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32112. firstZeroWeight = influencers - 1;
  32113. }
  32114. if (weight > epsilon) {
  32115. var mweight = 1.0 / weight;
  32116. for (var j = 0; j < 4; j++) {
  32117. matricesWeights[i + j] *= mweight;
  32118. }
  32119. if (matricesWeightsExtra) {
  32120. for (var j = 0; j < 4; j++) {
  32121. matricesWeightsExtra[i + j] *= mweight;
  32122. }
  32123. }
  32124. }
  32125. else {
  32126. if (firstZeroWeight >= 4) {
  32127. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32128. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32129. }
  32130. else {
  32131. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32132. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32133. }
  32134. }
  32135. }
  32136. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32137. if (parsedGeometry.matricesWeightsExtra) {
  32138. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32139. }
  32140. };
  32141. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  32142. if (scene.getGeometryByID(parsedVertexData.id)) {
  32143. return null; // null since geometry could be something else than a box...
  32144. }
  32145. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  32146. if (BABYLON.Tags) {
  32147. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  32148. }
  32149. if (parsedVertexData.delayLoadingFile) {
  32150. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32151. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  32152. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  32153. geometry._delayInfo = [];
  32154. if (parsedVertexData.hasUVs) {
  32155. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32156. }
  32157. if (parsedVertexData.hasUVs2) {
  32158. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32159. }
  32160. if (parsedVertexData.hasUVs3) {
  32161. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32162. }
  32163. if (parsedVertexData.hasUVs4) {
  32164. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32165. }
  32166. if (parsedVertexData.hasUVs5) {
  32167. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32168. }
  32169. if (parsedVertexData.hasUVs6) {
  32170. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32171. }
  32172. if (parsedVertexData.hasColors) {
  32173. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32174. }
  32175. if (parsedVertexData.hasMatricesIndices) {
  32176. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32177. }
  32178. if (parsedVertexData.hasMatricesWeights) {
  32179. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32180. }
  32181. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  32182. }
  32183. else {
  32184. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  32185. }
  32186. scene.pushGeometry(geometry, true);
  32187. return geometry;
  32188. };
  32189. return Geometry;
  32190. }());
  32191. BABYLON.Geometry = Geometry;
  32192. /////// Primitives //////////////////////////////////////////////
  32193. //export module Geometry.Primitives {
  32194. /// Abstract class
  32195. var _PrimitiveGeometry = /** @class */ (function (_super) {
  32196. __extends(_PrimitiveGeometry, _super);
  32197. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  32198. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  32199. if (mesh === void 0) { mesh = null; }
  32200. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  32201. _this._canBeRegenerated = _canBeRegenerated;
  32202. _this._beingRegenerated = true;
  32203. _this.regenerate();
  32204. _this._beingRegenerated = false;
  32205. return _this;
  32206. }
  32207. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  32208. return this._canBeRegenerated;
  32209. };
  32210. _PrimitiveGeometry.prototype.regenerate = function () {
  32211. if (!this._canBeRegenerated) {
  32212. return;
  32213. }
  32214. this._beingRegenerated = true;
  32215. this.setAllVerticesData(this._regenerateVertexData(), false);
  32216. this._beingRegenerated = false;
  32217. };
  32218. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  32219. return _super.prototype.copy.call(this, id);
  32220. };
  32221. // overrides
  32222. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  32223. if (!this._beingRegenerated) {
  32224. return;
  32225. }
  32226. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  32227. };
  32228. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  32229. if (!this._beingRegenerated) {
  32230. return;
  32231. }
  32232. _super.prototype.setVerticesData.call(this, kind, data, false);
  32233. };
  32234. // to override
  32235. // protected
  32236. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  32237. throw new Error("Abstract method");
  32238. };
  32239. _PrimitiveGeometry.prototype.copy = function (id) {
  32240. throw new Error("Must be overriden in sub-classes.");
  32241. };
  32242. _PrimitiveGeometry.prototype.serialize = function () {
  32243. var serializationObject = _super.prototype.serialize.call(this);
  32244. serializationObject.canBeRegenerated = this.canBeRegenerated();
  32245. return serializationObject;
  32246. };
  32247. return _PrimitiveGeometry;
  32248. }(Geometry));
  32249. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  32250. var RibbonGeometry = /** @class */ (function (_super) {
  32251. __extends(RibbonGeometry, _super);
  32252. // Members
  32253. function RibbonGeometry(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  32254. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32255. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32256. _this.pathArray = pathArray;
  32257. _this.closeArray = closeArray;
  32258. _this.closePath = closePath;
  32259. _this.offset = offset;
  32260. _this.side = side;
  32261. return _this;
  32262. }
  32263. RibbonGeometry.prototype._regenerateVertexData = function () {
  32264. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  32265. };
  32266. RibbonGeometry.prototype.copy = function (id) {
  32267. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  32268. };
  32269. return RibbonGeometry;
  32270. }(_PrimitiveGeometry));
  32271. BABYLON.RibbonGeometry = RibbonGeometry;
  32272. var BoxGeometry = /** @class */ (function (_super) {
  32273. __extends(BoxGeometry, _super);
  32274. // Members
  32275. function BoxGeometry(id, scene, size, canBeRegenerated, mesh, side) {
  32276. if (mesh === void 0) { mesh = null; }
  32277. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32278. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32279. _this.size = size;
  32280. _this.side = side;
  32281. return _this;
  32282. }
  32283. BoxGeometry.prototype._regenerateVertexData = function () {
  32284. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  32285. };
  32286. BoxGeometry.prototype.copy = function (id) {
  32287. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  32288. };
  32289. BoxGeometry.prototype.serialize = function () {
  32290. var serializationObject = _super.prototype.serialize.call(this);
  32291. serializationObject.size = this.size;
  32292. return serializationObject;
  32293. };
  32294. BoxGeometry.Parse = function (parsedBox, scene) {
  32295. if (scene.getGeometryByID(parsedBox.id)) {
  32296. return null; // null since geometry could be something else than a box...
  32297. }
  32298. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  32299. if (BABYLON.Tags) {
  32300. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  32301. }
  32302. scene.pushGeometry(box, true);
  32303. return box;
  32304. };
  32305. return BoxGeometry;
  32306. }(_PrimitiveGeometry));
  32307. BABYLON.BoxGeometry = BoxGeometry;
  32308. var SphereGeometry = /** @class */ (function (_super) {
  32309. __extends(SphereGeometry, _super);
  32310. function SphereGeometry(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  32311. if (mesh === void 0) { mesh = null; }
  32312. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32313. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32314. _this.segments = segments;
  32315. _this.diameter = diameter;
  32316. _this.side = side;
  32317. return _this;
  32318. }
  32319. SphereGeometry.prototype._regenerateVertexData = function () {
  32320. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  32321. };
  32322. SphereGeometry.prototype.copy = function (id) {
  32323. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  32324. };
  32325. SphereGeometry.prototype.serialize = function () {
  32326. var serializationObject = _super.prototype.serialize.call(this);
  32327. serializationObject.segments = this.segments;
  32328. serializationObject.diameter = this.diameter;
  32329. return serializationObject;
  32330. };
  32331. SphereGeometry.Parse = function (parsedSphere, scene) {
  32332. if (scene.getGeometryByID(parsedSphere.id)) {
  32333. return null; // null since geometry could be something else than a sphere...
  32334. }
  32335. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  32336. if (BABYLON.Tags) {
  32337. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  32338. }
  32339. scene.pushGeometry(sphere, true);
  32340. return sphere;
  32341. };
  32342. return SphereGeometry;
  32343. }(_PrimitiveGeometry));
  32344. BABYLON.SphereGeometry = SphereGeometry;
  32345. var DiscGeometry = /** @class */ (function (_super) {
  32346. __extends(DiscGeometry, _super);
  32347. // Members
  32348. function DiscGeometry(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  32349. if (mesh === void 0) { mesh = null; }
  32350. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32351. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32352. _this.radius = radius;
  32353. _this.tessellation = tessellation;
  32354. _this.side = side;
  32355. return _this;
  32356. }
  32357. DiscGeometry.prototype._regenerateVertexData = function () {
  32358. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  32359. };
  32360. DiscGeometry.prototype.copy = function (id) {
  32361. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  32362. };
  32363. return DiscGeometry;
  32364. }(_PrimitiveGeometry));
  32365. BABYLON.DiscGeometry = DiscGeometry;
  32366. var CylinderGeometry = /** @class */ (function (_super) {
  32367. __extends(CylinderGeometry, _super);
  32368. function CylinderGeometry(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  32369. if (subdivisions === void 0) { subdivisions = 1; }
  32370. if (mesh === void 0) { mesh = null; }
  32371. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32372. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32373. _this.height = height;
  32374. _this.diameterTop = diameterTop;
  32375. _this.diameterBottom = diameterBottom;
  32376. _this.tessellation = tessellation;
  32377. _this.subdivisions = subdivisions;
  32378. _this.side = side;
  32379. return _this;
  32380. }
  32381. CylinderGeometry.prototype._regenerateVertexData = function () {
  32382. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  32383. };
  32384. CylinderGeometry.prototype.copy = function (id) {
  32385. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  32386. };
  32387. CylinderGeometry.prototype.serialize = function () {
  32388. var serializationObject = _super.prototype.serialize.call(this);
  32389. serializationObject.height = this.height;
  32390. serializationObject.diameterTop = this.diameterTop;
  32391. serializationObject.diameterBottom = this.diameterBottom;
  32392. serializationObject.tessellation = this.tessellation;
  32393. return serializationObject;
  32394. };
  32395. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  32396. if (scene.getGeometryByID(parsedCylinder.id)) {
  32397. return null; // null since geometry could be something else than a cylinder...
  32398. }
  32399. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  32400. if (BABYLON.Tags) {
  32401. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  32402. }
  32403. scene.pushGeometry(cylinder, true);
  32404. return cylinder;
  32405. };
  32406. return CylinderGeometry;
  32407. }(_PrimitiveGeometry));
  32408. BABYLON.CylinderGeometry = CylinderGeometry;
  32409. var TorusGeometry = /** @class */ (function (_super) {
  32410. __extends(TorusGeometry, _super);
  32411. function TorusGeometry(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  32412. if (mesh === void 0) { mesh = null; }
  32413. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32414. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32415. _this.diameter = diameter;
  32416. _this.thickness = thickness;
  32417. _this.tessellation = tessellation;
  32418. _this.side = side;
  32419. return _this;
  32420. }
  32421. TorusGeometry.prototype._regenerateVertexData = function () {
  32422. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  32423. };
  32424. TorusGeometry.prototype.copy = function (id) {
  32425. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  32426. };
  32427. TorusGeometry.prototype.serialize = function () {
  32428. var serializationObject = _super.prototype.serialize.call(this);
  32429. serializationObject.diameter = this.diameter;
  32430. serializationObject.thickness = this.thickness;
  32431. serializationObject.tessellation = this.tessellation;
  32432. return serializationObject;
  32433. };
  32434. TorusGeometry.Parse = function (parsedTorus, scene) {
  32435. if (scene.getGeometryByID(parsedTorus.id)) {
  32436. return null; // null since geometry could be something else than a torus...
  32437. }
  32438. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  32439. if (BABYLON.Tags) {
  32440. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  32441. }
  32442. scene.pushGeometry(torus, true);
  32443. return torus;
  32444. };
  32445. return TorusGeometry;
  32446. }(_PrimitiveGeometry));
  32447. BABYLON.TorusGeometry = TorusGeometry;
  32448. var GroundGeometry = /** @class */ (function (_super) {
  32449. __extends(GroundGeometry, _super);
  32450. function GroundGeometry(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  32451. if (mesh === void 0) { mesh = null; }
  32452. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32453. _this.width = width;
  32454. _this.height = height;
  32455. _this.subdivisions = subdivisions;
  32456. return _this;
  32457. }
  32458. GroundGeometry.prototype._regenerateVertexData = function () {
  32459. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  32460. };
  32461. GroundGeometry.prototype.copy = function (id) {
  32462. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  32463. };
  32464. GroundGeometry.prototype.serialize = function () {
  32465. var serializationObject = _super.prototype.serialize.call(this);
  32466. serializationObject.width = this.width;
  32467. serializationObject.height = this.height;
  32468. serializationObject.subdivisions = this.subdivisions;
  32469. return serializationObject;
  32470. };
  32471. GroundGeometry.Parse = function (parsedGround, scene) {
  32472. if (scene.getGeometryByID(parsedGround.id)) {
  32473. return null; // null since geometry could be something else than a ground...
  32474. }
  32475. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  32476. if (BABYLON.Tags) {
  32477. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  32478. }
  32479. scene.pushGeometry(ground, true);
  32480. return ground;
  32481. };
  32482. return GroundGeometry;
  32483. }(_PrimitiveGeometry));
  32484. BABYLON.GroundGeometry = GroundGeometry;
  32485. var TiledGroundGeometry = /** @class */ (function (_super) {
  32486. __extends(TiledGroundGeometry, _super);
  32487. function TiledGroundGeometry(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  32488. if (mesh === void 0) { mesh = null; }
  32489. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32490. _this.xmin = xmin;
  32491. _this.zmin = zmin;
  32492. _this.xmax = xmax;
  32493. _this.zmax = zmax;
  32494. _this.subdivisions = subdivisions;
  32495. _this.precision = precision;
  32496. return _this;
  32497. }
  32498. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  32499. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  32500. };
  32501. TiledGroundGeometry.prototype.copy = function (id) {
  32502. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  32503. };
  32504. return TiledGroundGeometry;
  32505. }(_PrimitiveGeometry));
  32506. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  32507. var PlaneGeometry = /** @class */ (function (_super) {
  32508. __extends(PlaneGeometry, _super);
  32509. function PlaneGeometry(id, scene, size, canBeRegenerated, mesh, side) {
  32510. if (mesh === void 0) { mesh = null; }
  32511. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32512. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32513. _this.size = size;
  32514. _this.side = side;
  32515. return _this;
  32516. }
  32517. PlaneGeometry.prototype._regenerateVertexData = function () {
  32518. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  32519. };
  32520. PlaneGeometry.prototype.copy = function (id) {
  32521. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  32522. };
  32523. PlaneGeometry.prototype.serialize = function () {
  32524. var serializationObject = _super.prototype.serialize.call(this);
  32525. serializationObject.size = this.size;
  32526. return serializationObject;
  32527. };
  32528. PlaneGeometry.Parse = function (parsedPlane, scene) {
  32529. if (scene.getGeometryByID(parsedPlane.id)) {
  32530. return null; // null since geometry could be something else than a ground...
  32531. }
  32532. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  32533. if (BABYLON.Tags) {
  32534. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  32535. }
  32536. scene.pushGeometry(plane, true);
  32537. return plane;
  32538. };
  32539. return PlaneGeometry;
  32540. }(_PrimitiveGeometry));
  32541. BABYLON.PlaneGeometry = PlaneGeometry;
  32542. var TorusKnotGeometry = /** @class */ (function (_super) {
  32543. __extends(TorusKnotGeometry, _super);
  32544. function TorusKnotGeometry(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  32545. if (mesh === void 0) { mesh = null; }
  32546. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32547. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32548. _this.radius = radius;
  32549. _this.tube = tube;
  32550. _this.radialSegments = radialSegments;
  32551. _this.tubularSegments = tubularSegments;
  32552. _this.p = p;
  32553. _this.q = q;
  32554. _this.side = side;
  32555. return _this;
  32556. }
  32557. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  32558. 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 });
  32559. };
  32560. TorusKnotGeometry.prototype.copy = function (id) {
  32561. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  32562. };
  32563. TorusKnotGeometry.prototype.serialize = function () {
  32564. var serializationObject = _super.prototype.serialize.call(this);
  32565. serializationObject.radius = this.radius;
  32566. serializationObject.tube = this.tube;
  32567. serializationObject.radialSegments = this.radialSegments;
  32568. serializationObject.tubularSegments = this.tubularSegments;
  32569. serializationObject.p = this.p;
  32570. serializationObject.q = this.q;
  32571. return serializationObject;
  32572. };
  32573. ;
  32574. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  32575. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  32576. return null; // null since geometry could be something else than a ground...
  32577. }
  32578. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  32579. if (BABYLON.Tags) {
  32580. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  32581. }
  32582. scene.pushGeometry(torusKnot, true);
  32583. return torusKnot;
  32584. };
  32585. return TorusKnotGeometry;
  32586. }(_PrimitiveGeometry));
  32587. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  32588. //}
  32589. })(BABYLON || (BABYLON = {}));
  32590. //# sourceMappingURL=babylon.geometry.js.map
  32591. var BABYLON;
  32592. (function (BABYLON) {
  32593. var PostProcessManager = /** @class */ (function () {
  32594. function PostProcessManager(scene) {
  32595. this._vertexBuffers = {};
  32596. this._scene = scene;
  32597. }
  32598. PostProcessManager.prototype._prepareBuffers = function () {
  32599. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  32600. return;
  32601. }
  32602. // VBO
  32603. var vertices = [];
  32604. vertices.push(1, 1);
  32605. vertices.push(-1, 1);
  32606. vertices.push(-1, -1);
  32607. vertices.push(1, -1);
  32608. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  32609. this._buildIndexBuffer();
  32610. };
  32611. PostProcessManager.prototype._buildIndexBuffer = function () {
  32612. // Indices
  32613. var indices = [];
  32614. indices.push(0);
  32615. indices.push(1);
  32616. indices.push(2);
  32617. indices.push(0);
  32618. indices.push(2);
  32619. indices.push(3);
  32620. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  32621. };
  32622. PostProcessManager.prototype._rebuild = function () {
  32623. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32624. if (!vb) {
  32625. return;
  32626. }
  32627. vb._rebuild();
  32628. this._buildIndexBuffer();
  32629. };
  32630. // Methods
  32631. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  32632. if (sourceTexture === void 0) { sourceTexture = null; }
  32633. if (postProcesses === void 0) { postProcesses = null; }
  32634. var camera = this._scene.activeCamera;
  32635. if (!camera) {
  32636. return false;
  32637. }
  32638. var postProcesses = postProcesses || camera._postProcesses;
  32639. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32640. return false;
  32641. }
  32642. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  32643. return true;
  32644. };
  32645. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  32646. if (targetTexture === void 0) { targetTexture = null; }
  32647. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  32648. var engine = this._scene.getEngine();
  32649. for (var index = 0; index < postProcesses.length; index++) {
  32650. if (index < postProcesses.length - 1) {
  32651. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  32652. }
  32653. else {
  32654. if (targetTexture) {
  32655. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  32656. }
  32657. else {
  32658. engine.restoreDefaultFramebuffer();
  32659. }
  32660. }
  32661. var pp = postProcesses[index];
  32662. var effect = pp.apply();
  32663. if (effect) {
  32664. pp.onBeforeRenderObservable.notifyObservers(effect);
  32665. // VBOs
  32666. this._prepareBuffers();
  32667. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32668. // Draw order
  32669. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  32670. pp.onAfterRenderObservable.notifyObservers(effect);
  32671. }
  32672. }
  32673. // Restore depth buffer
  32674. engine.setDepthBuffer(true);
  32675. engine.setDepthWrite(true);
  32676. };
  32677. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  32678. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  32679. var camera = this._scene.activeCamera;
  32680. if (!camera) {
  32681. return;
  32682. }
  32683. postProcesses = postProcesses || camera._postProcesses;
  32684. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32685. return;
  32686. }
  32687. var engine = this._scene.getEngine();
  32688. for (var index = 0, len = postProcesses.length; index < len; index++) {
  32689. if (index < len - 1) {
  32690. postProcesses[index + 1].activate(camera, targetTexture);
  32691. }
  32692. else {
  32693. if (targetTexture) {
  32694. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  32695. }
  32696. else {
  32697. engine.restoreDefaultFramebuffer();
  32698. }
  32699. }
  32700. if (doNotPresent) {
  32701. break;
  32702. }
  32703. var pp = postProcesses[index];
  32704. var effect = pp.apply();
  32705. if (effect) {
  32706. pp.onBeforeRenderObservable.notifyObservers(effect);
  32707. // VBOs
  32708. this._prepareBuffers();
  32709. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32710. // Draw order
  32711. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  32712. pp.onAfterRenderObservable.notifyObservers(effect);
  32713. }
  32714. }
  32715. // Restore states
  32716. engine.setDepthBuffer(true);
  32717. engine.setDepthWrite(true);
  32718. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32719. };
  32720. PostProcessManager.prototype.dispose = function () {
  32721. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32722. if (buffer) {
  32723. buffer.dispose();
  32724. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  32725. }
  32726. if (this._indexBuffer) {
  32727. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32728. this._indexBuffer = null;
  32729. }
  32730. };
  32731. return PostProcessManager;
  32732. }());
  32733. BABYLON.PostProcessManager = PostProcessManager;
  32734. })(BABYLON || (BABYLON = {}));
  32735. //# sourceMappingURL=babylon.postProcessManager.js.map
  32736. BABYLON.Effect.IncludesShadersStore['depthPrePass'] = "#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif";
  32737. 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";
  32738. 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";
  32739. BABYLON.Effect.IncludesShadersStore['pointCloudVertexDeclaration'] = "#ifdef POINTSIZE\nuniform float pointSize;\n#endif";
  32740. BABYLON.Effect.IncludesShadersStore['bumpVertexDeclaration'] = "#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n";
  32741. BABYLON.Effect.IncludesShadersStore['clipPlaneVertexDeclaration'] = "#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif";
  32742. BABYLON.Effect.IncludesShadersStore['fogVertexDeclaration'] = "#ifdef FOG\nvarying vec3 vFogDistance;\n#endif";
  32743. BABYLON.Effect.IncludesShadersStore['morphTargetsVertexGlobalDeclaration'] = "#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif";
  32744. 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";
  32745. BABYLON.Effect.IncludesShadersStore['logDepthDeclaration'] = "#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif";
  32746. 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";
  32747. BABYLON.Effect.IncludesShadersStore['instancesVertex'] = "#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif";
  32748. 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";
  32749. 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";
  32750. BABYLON.Effect.IncludesShadersStore['clipPlaneVertex'] = "#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif";
  32751. BABYLON.Effect.IncludesShadersStore['fogVertex'] = "#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif";
  32752. 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";
  32753. BABYLON.Effect.IncludesShadersStore['pointCloudVertex'] = "#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif";
  32754. BABYLON.Effect.IncludesShadersStore['logDepthVertex'] = "#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif";
  32755. 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}";
  32756. 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";
  32757. 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";
  32758. 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";
  32759. 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";
  32760. 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";
  32761. 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};";
  32762. 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";
  32763. 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";
  32764. 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}";
  32765. 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";
  32766. 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}";
  32767. 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";
  32768. BABYLON.Effect.IncludesShadersStore['clipPlaneFragmentDeclaration'] = "#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif";
  32769. 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";
  32770. BABYLON.Effect.IncludesShadersStore['clipPlaneFragment'] = "#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif";
  32771. 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";
  32772. 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";
  32773. BABYLON.Effect.IncludesShadersStore['logDepthFragment'] = "#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif";
  32774. BABYLON.Effect.IncludesShadersStore['fogFragment'] = "#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif";
  32775. var BABYLON;
  32776. (function (BABYLON) {
  32777. /**
  32778. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  32779. */
  32780. var PerformanceMonitor = /** @class */ (function () {
  32781. /**
  32782. * constructor
  32783. * @param frameSampleSize The number of samples required to saturate the sliding window
  32784. */
  32785. function PerformanceMonitor(frameSampleSize) {
  32786. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  32787. this._enabled = true;
  32788. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  32789. }
  32790. /**
  32791. * Samples current frame
  32792. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  32793. */
  32794. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  32795. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  32796. if (!this._enabled)
  32797. return;
  32798. if (this._lastFrameTimeMs != null) {
  32799. var dt = timeMs - this._lastFrameTimeMs;
  32800. this._rollingFrameTime.add(dt);
  32801. }
  32802. this._lastFrameTimeMs = timeMs;
  32803. };
  32804. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  32805. /**
  32806. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  32807. * @return Average frame time in milliseconds
  32808. */
  32809. get: function () {
  32810. return this._rollingFrameTime.average;
  32811. },
  32812. enumerable: true,
  32813. configurable: true
  32814. });
  32815. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  32816. /**
  32817. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  32818. * @return Frame time variance in milliseconds squared
  32819. */
  32820. get: function () {
  32821. return this._rollingFrameTime.variance;
  32822. },
  32823. enumerable: true,
  32824. configurable: true
  32825. });
  32826. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  32827. /**
  32828. * Returns the frame time of the most recent frame
  32829. * @return Frame time in milliseconds
  32830. */
  32831. get: function () {
  32832. return this._rollingFrameTime.history(0);
  32833. },
  32834. enumerable: true,
  32835. configurable: true
  32836. });
  32837. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  32838. /**
  32839. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  32840. * @return Framerate in frames per second
  32841. */
  32842. get: function () {
  32843. return 1000.0 / this._rollingFrameTime.average;
  32844. },
  32845. enumerable: true,
  32846. configurable: true
  32847. });
  32848. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  32849. /**
  32850. * Returns the average framerate in frames per second using the most recent frame time
  32851. * @return Framerate in frames per second
  32852. */
  32853. get: function () {
  32854. var history = this._rollingFrameTime.history(0);
  32855. if (history === 0) {
  32856. return 0;
  32857. }
  32858. return 1000.0 / history;
  32859. },
  32860. enumerable: true,
  32861. configurable: true
  32862. });
  32863. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  32864. /**
  32865. * Returns true if enough samples have been taken to completely fill the sliding window
  32866. * @return true if saturated
  32867. */
  32868. get: function () {
  32869. return this._rollingFrameTime.isSaturated();
  32870. },
  32871. enumerable: true,
  32872. configurable: true
  32873. });
  32874. /**
  32875. * Enables contributions to the sliding window sample set
  32876. */
  32877. PerformanceMonitor.prototype.enable = function () {
  32878. this._enabled = true;
  32879. };
  32880. /**
  32881. * Disables contributions to the sliding window sample set
  32882. * Samples will not be interpolated over the disabled period
  32883. */
  32884. PerformanceMonitor.prototype.disable = function () {
  32885. this._enabled = false;
  32886. //clear last sample to avoid interpolating over the disabled period when next enabled
  32887. this._lastFrameTimeMs = null;
  32888. };
  32889. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  32890. /**
  32891. * Returns true if sampling is enabled
  32892. * @return true if enabled
  32893. */
  32894. get: function () {
  32895. return this._enabled;
  32896. },
  32897. enumerable: true,
  32898. configurable: true
  32899. });
  32900. /**
  32901. * Resets performance monitor
  32902. */
  32903. PerformanceMonitor.prototype.reset = function () {
  32904. //clear last sample to avoid interpolating over the disabled period when next enabled
  32905. this._lastFrameTimeMs = null;
  32906. //wipe record
  32907. this._rollingFrameTime.reset();
  32908. };
  32909. return PerformanceMonitor;
  32910. }());
  32911. BABYLON.PerformanceMonitor = PerformanceMonitor;
  32912. /**
  32913. * RollingAverage
  32914. *
  32915. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  32916. */
  32917. var RollingAverage = /** @class */ (function () {
  32918. /**
  32919. * constructor
  32920. * @param length The number of samples required to saturate the sliding window
  32921. */
  32922. function RollingAverage(length) {
  32923. this._samples = new Array(length);
  32924. this.reset();
  32925. }
  32926. /**
  32927. * Adds a sample to the sample set
  32928. * @param v The sample value
  32929. */
  32930. RollingAverage.prototype.add = function (v) {
  32931. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  32932. var delta;
  32933. //we need to check if we've already wrapped round
  32934. if (this.isSaturated()) {
  32935. //remove bottom of stack from mean
  32936. var bottomValue = this._samples[this._pos];
  32937. delta = bottomValue - this.average;
  32938. this.average -= delta / (this._sampleCount - 1);
  32939. this._m2 -= delta * (bottomValue - this.average);
  32940. }
  32941. else {
  32942. this._sampleCount++;
  32943. }
  32944. //add new value to mean
  32945. delta = v - this.average;
  32946. this.average += delta / (this._sampleCount);
  32947. this._m2 += delta * (v - this.average);
  32948. //set the new variance
  32949. this.variance = this._m2 / (this._sampleCount - 1);
  32950. this._samples[this._pos] = v;
  32951. this._pos++;
  32952. this._pos %= this._samples.length; //positive wrap around
  32953. };
  32954. /**
  32955. * Returns previously added values or null if outside of history or outside the sliding window domain
  32956. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  32957. * @return Value previously recorded with add() or null if outside of range
  32958. */
  32959. RollingAverage.prototype.history = function (i) {
  32960. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  32961. return 0;
  32962. }
  32963. var i0 = this._wrapPosition(this._pos - 1.0);
  32964. return this._samples[this._wrapPosition(i0 - i)];
  32965. };
  32966. /**
  32967. * Returns true if enough samples have been taken to completely fill the sliding window
  32968. * @return true if sample-set saturated
  32969. */
  32970. RollingAverage.prototype.isSaturated = function () {
  32971. return this._sampleCount >= this._samples.length;
  32972. };
  32973. /**
  32974. * Resets the rolling average (equivalent to 0 samples taken so far)
  32975. */
  32976. RollingAverage.prototype.reset = function () {
  32977. this.average = 0;
  32978. this.variance = 0;
  32979. this._sampleCount = 0;
  32980. this._pos = 0;
  32981. this._m2 = 0;
  32982. };
  32983. /**
  32984. * Wraps a value around the sample range boundaries
  32985. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  32986. * @return Wrapped position in sample range
  32987. */
  32988. RollingAverage.prototype._wrapPosition = function (i) {
  32989. var max = this._samples.length;
  32990. return ((i % max) + max) % max;
  32991. };
  32992. return RollingAverage;
  32993. }());
  32994. BABYLON.RollingAverage = RollingAverage;
  32995. })(BABYLON || (BABYLON = {}));
  32996. //# sourceMappingURL=babylon.performanceMonitor.js.map
  32997. var BABYLON;
  32998. (function (BABYLON) {
  32999. /**
  33000. * This groups together the common properties used for image processing either in direct forward pass
  33001. * or through post processing effect depending on the use of the image processing pipeline in your scene
  33002. * or not.
  33003. */
  33004. var ImageProcessingConfiguration = /** @class */ (function () {
  33005. function ImageProcessingConfiguration() {
  33006. /**
  33007. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  33008. */
  33009. this.colorCurves = new BABYLON.ColorCurves();
  33010. this._colorCurvesEnabled = false;
  33011. this._colorGradingEnabled = false;
  33012. this._colorGradingWithGreenDepth = true;
  33013. this._colorGradingBGR = true;
  33014. this._exposure = 1.0;
  33015. this._toneMappingEnabled = false;
  33016. this._contrast = 1.0;
  33017. /**
  33018. * Vignette stretch size.
  33019. */
  33020. this.vignetteStretch = 0;
  33021. /**
  33022. * Vignette centre X Offset.
  33023. */
  33024. this.vignetteCentreX = 0;
  33025. /**
  33026. * Vignette centre Y Offset.
  33027. */
  33028. this.vignetteCentreY = 0;
  33029. /**
  33030. * Vignette weight or intensity of the vignette effect.
  33031. */
  33032. this.vignetteWeight = 1.5;
  33033. /**
  33034. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  33035. * if vignetteEnabled is set to true.
  33036. */
  33037. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  33038. /**
  33039. * Camera field of view used by the Vignette effect.
  33040. */
  33041. this.vignetteCameraFov = 0.5;
  33042. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  33043. this._vignetteEnabled = false;
  33044. this._applyByPostProcess = false;
  33045. this._isEnabled = true;
  33046. /**
  33047. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  33048. * @type {BABYLON.Observable}
  33049. */
  33050. this.onUpdateParameters = new BABYLON.Observable();
  33051. }
  33052. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  33053. /**
  33054. * Gets wether the color curves effect is enabled.
  33055. */
  33056. get: function () {
  33057. return this._colorCurvesEnabled;
  33058. },
  33059. /**
  33060. * Sets wether the color curves effect is enabled.
  33061. */
  33062. set: function (value) {
  33063. if (this._colorCurvesEnabled === value) {
  33064. return;
  33065. }
  33066. this._colorCurvesEnabled = value;
  33067. this._updateParameters();
  33068. },
  33069. enumerable: true,
  33070. configurable: true
  33071. });
  33072. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  33073. /**
  33074. * Gets wether the color grading effect is enabled.
  33075. */
  33076. get: function () {
  33077. return this._colorGradingEnabled;
  33078. },
  33079. /**
  33080. * Sets wether the color grading effect is enabled.
  33081. */
  33082. set: function (value) {
  33083. if (this._colorGradingEnabled === value) {
  33084. return;
  33085. }
  33086. this._colorGradingEnabled = value;
  33087. this._updateParameters();
  33088. },
  33089. enumerable: true,
  33090. configurable: true
  33091. });
  33092. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  33093. /**
  33094. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  33095. */
  33096. get: function () {
  33097. return this._colorGradingWithGreenDepth;
  33098. },
  33099. /**
  33100. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  33101. */
  33102. set: function (value) {
  33103. if (this._colorGradingWithGreenDepth === value) {
  33104. return;
  33105. }
  33106. this._colorGradingWithGreenDepth = value;
  33107. this._updateParameters();
  33108. },
  33109. enumerable: true,
  33110. configurable: true
  33111. });
  33112. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  33113. /**
  33114. * Gets wether the color grading texture contains BGR values.
  33115. */
  33116. get: function () {
  33117. return this._colorGradingBGR;
  33118. },
  33119. /**
  33120. * Sets wether the color grading texture contains BGR values.
  33121. */
  33122. set: function (value) {
  33123. if (this._colorGradingBGR === value) {
  33124. return;
  33125. }
  33126. this._colorGradingBGR = value;
  33127. this._updateParameters();
  33128. },
  33129. enumerable: true,
  33130. configurable: true
  33131. });
  33132. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  33133. /**
  33134. * Gets the Exposure used in the effect.
  33135. */
  33136. get: function () {
  33137. return this._exposure;
  33138. },
  33139. /**
  33140. * Sets the Exposure used in the effect.
  33141. */
  33142. set: function (value) {
  33143. if (this._exposure === value) {
  33144. return;
  33145. }
  33146. this._exposure = value;
  33147. this._updateParameters();
  33148. },
  33149. enumerable: true,
  33150. configurable: true
  33151. });
  33152. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  33153. /**
  33154. * Gets wether the tone mapping effect is enabled.
  33155. */
  33156. get: function () {
  33157. return this._toneMappingEnabled;
  33158. },
  33159. /**
  33160. * Sets wether the tone mapping effect is enabled.
  33161. */
  33162. set: function (value) {
  33163. if (this._toneMappingEnabled === value) {
  33164. return;
  33165. }
  33166. this._toneMappingEnabled = value;
  33167. this._updateParameters();
  33168. },
  33169. enumerable: true,
  33170. configurable: true
  33171. });
  33172. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  33173. /**
  33174. * Gets the contrast used in the effect.
  33175. */
  33176. get: function () {
  33177. return this._contrast;
  33178. },
  33179. /**
  33180. * Sets the contrast used in the effect.
  33181. */
  33182. set: function (value) {
  33183. if (this._contrast === value) {
  33184. return;
  33185. }
  33186. this._contrast = value;
  33187. this._updateParameters();
  33188. },
  33189. enumerable: true,
  33190. configurable: true
  33191. });
  33192. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  33193. /**
  33194. * Gets the vignette blend mode allowing different kind of effect.
  33195. */
  33196. get: function () {
  33197. return this._vignetteBlendMode;
  33198. },
  33199. /**
  33200. * Sets the vignette blend mode allowing different kind of effect.
  33201. */
  33202. set: function (value) {
  33203. if (this._vignetteBlendMode === value) {
  33204. return;
  33205. }
  33206. this._vignetteBlendMode = value;
  33207. this._updateParameters();
  33208. },
  33209. enumerable: true,
  33210. configurable: true
  33211. });
  33212. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  33213. /**
  33214. * Gets wether the vignette effect is enabled.
  33215. */
  33216. get: function () {
  33217. return this._vignetteEnabled;
  33218. },
  33219. /**
  33220. * Sets wether the vignette effect is enabled.
  33221. */
  33222. set: function (value) {
  33223. if (this._vignetteEnabled === value) {
  33224. return;
  33225. }
  33226. this._vignetteEnabled = value;
  33227. this._updateParameters();
  33228. },
  33229. enumerable: true,
  33230. configurable: true
  33231. });
  33232. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  33233. /**
  33234. * Gets wether the image processing is applied through a post process or not.
  33235. */
  33236. get: function () {
  33237. return this._applyByPostProcess;
  33238. },
  33239. /**
  33240. * Sets wether the image processing is applied through a post process or not.
  33241. */
  33242. set: function (value) {
  33243. if (this._applyByPostProcess === value) {
  33244. return;
  33245. }
  33246. this._applyByPostProcess = value;
  33247. this._updateParameters();
  33248. },
  33249. enumerable: true,
  33250. configurable: true
  33251. });
  33252. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  33253. /**
  33254. * Gets wether the image processing is enabled or not.
  33255. */
  33256. get: function () {
  33257. return this._isEnabled;
  33258. },
  33259. /**
  33260. * Sets wether the image processing is enabled or not.
  33261. */
  33262. set: function (value) {
  33263. if (this._isEnabled === value) {
  33264. return;
  33265. }
  33266. this._isEnabled = value;
  33267. this._updateParameters();
  33268. },
  33269. enumerable: true,
  33270. configurable: true
  33271. });
  33272. /**
  33273. * Method called each time the image processing information changes requires to recompile the effect.
  33274. */
  33275. ImageProcessingConfiguration.prototype._updateParameters = function () {
  33276. this.onUpdateParameters.notifyObservers(this);
  33277. };
  33278. ImageProcessingConfiguration.prototype.getClassName = function () {
  33279. return "ImageProcessingConfiguration";
  33280. };
  33281. /**
  33282. * Prepare the list of uniforms associated with the Image Processing effects.
  33283. * @param uniformsList The list of uniforms used in the effect
  33284. * @param defines the list of defines currently in use
  33285. */
  33286. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  33287. if (defines.EXPOSURE) {
  33288. uniforms.push("exposureLinear");
  33289. }
  33290. if (defines.CONTRAST) {
  33291. uniforms.push("contrast");
  33292. }
  33293. if (defines.COLORGRADING) {
  33294. uniforms.push("colorTransformSettings");
  33295. }
  33296. if (defines.VIGNETTE) {
  33297. uniforms.push("vInverseScreenSize");
  33298. uniforms.push("vignetteSettings1");
  33299. uniforms.push("vignetteSettings2");
  33300. }
  33301. if (defines.COLORCURVES) {
  33302. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  33303. }
  33304. };
  33305. /**
  33306. * Prepare the list of samplers associated with the Image Processing effects.
  33307. * @param uniformsList The list of uniforms used in the effect
  33308. * @param defines the list of defines currently in use
  33309. */
  33310. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  33311. if (defines.COLORGRADING) {
  33312. samplersList.push("txColorTransform");
  33313. }
  33314. };
  33315. /**
  33316. * Prepare the list of defines associated to the shader.
  33317. * @param defines the list of defines to complete
  33318. */
  33319. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  33320. if (forPostProcess === void 0) { forPostProcess = false; }
  33321. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  33322. defines.VIGNETTE = false;
  33323. defines.TONEMAPPING = false;
  33324. defines.CONTRAST = false;
  33325. defines.EXPOSURE = false;
  33326. defines.COLORCURVES = false;
  33327. defines.COLORGRADING = false;
  33328. defines.COLORGRADING3D = false;
  33329. defines.IMAGEPROCESSING = false;
  33330. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  33331. return;
  33332. }
  33333. defines.VIGNETTE = this.vignetteEnabled;
  33334. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  33335. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  33336. defines.TONEMAPPING = this.toneMappingEnabled;
  33337. defines.CONTRAST = (this.contrast !== 1.0);
  33338. defines.EXPOSURE = (this.exposure !== 1.0);
  33339. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  33340. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  33341. if (defines.COLORGRADING) {
  33342. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  33343. }
  33344. else {
  33345. defines.COLORGRADING3D = false;
  33346. }
  33347. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  33348. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  33349. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  33350. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  33351. };
  33352. /**
  33353. * Returns true if all the image processing information are ready.
  33354. */
  33355. ImageProcessingConfiguration.prototype.isReady = function () {
  33356. // Color Grading texure can not be none blocking.
  33357. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  33358. };
  33359. /**
  33360. * Binds the image processing to the shader.
  33361. * @param effect The effect to bind to
  33362. */
  33363. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  33364. if (aspectRatio === void 0) { aspectRatio = 1; }
  33365. // Color Curves
  33366. if (this._colorCurvesEnabled && this.colorCurves) {
  33367. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  33368. }
  33369. // Vignette
  33370. if (this._vignetteEnabled) {
  33371. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  33372. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  33373. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  33374. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  33375. var vignetteScaleX = vignetteScaleY * aspectRatio;
  33376. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  33377. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  33378. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  33379. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  33380. var vignettePower = -2.0 * this.vignetteWeight;
  33381. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  33382. }
  33383. // Exposure
  33384. effect.setFloat("exposureLinear", this.exposure);
  33385. // Contrast
  33386. effect.setFloat("contrast", this.contrast);
  33387. // Color transform settings
  33388. if (this.colorGradingTexture) {
  33389. effect.setTexture("txColorTransform", this.colorGradingTexture);
  33390. var textureSize = this.colorGradingTexture.getSize().height;
  33391. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  33392. 0.5 / textureSize, // textureOffset
  33393. textureSize, // textureSize
  33394. this.colorGradingTexture.level // weight
  33395. );
  33396. }
  33397. };
  33398. /**
  33399. * Clones the current image processing instance.
  33400. * @return The cloned image processing
  33401. */
  33402. ImageProcessingConfiguration.prototype.clone = function () {
  33403. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  33404. };
  33405. /**
  33406. * Serializes the current image processing instance to a json representation.
  33407. * @return a JSON representation
  33408. */
  33409. ImageProcessingConfiguration.prototype.serialize = function () {
  33410. return BABYLON.SerializationHelper.Serialize(this);
  33411. };
  33412. /**
  33413. * Parses the image processing from a json representation.
  33414. * @param source the JSON source to parse
  33415. * @return The parsed image processing
  33416. */
  33417. ImageProcessingConfiguration.Parse = function (source) {
  33418. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  33419. };
  33420. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  33421. /**
  33422. * Used to apply the vignette as a mix with the pixel color.
  33423. */
  33424. get: function () {
  33425. return this._VIGNETTEMODE_MULTIPLY;
  33426. },
  33427. enumerable: true,
  33428. configurable: true
  33429. });
  33430. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  33431. /**
  33432. * Used to apply the vignette as a replacement of the pixel color.
  33433. */
  33434. get: function () {
  33435. return this._VIGNETTEMODE_OPAQUE;
  33436. },
  33437. enumerable: true,
  33438. configurable: true
  33439. });
  33440. // Static constants associated to the image processing.
  33441. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  33442. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  33443. __decorate([
  33444. BABYLON.serializeAsColorCurves()
  33445. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  33446. __decorate([
  33447. BABYLON.serialize()
  33448. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  33449. __decorate([
  33450. BABYLON.serializeAsTexture()
  33451. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  33452. __decorate([
  33453. BABYLON.serialize()
  33454. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  33455. __decorate([
  33456. BABYLON.serialize()
  33457. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  33458. __decorate([
  33459. BABYLON.serialize()
  33460. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  33461. __decorate([
  33462. BABYLON.serialize()
  33463. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  33464. __decorate([
  33465. BABYLON.serialize()
  33466. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  33467. __decorate([
  33468. BABYLON.serialize()
  33469. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  33470. __decorate([
  33471. BABYLON.serialize()
  33472. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  33473. __decorate([
  33474. BABYLON.serialize()
  33475. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  33476. __decorate([
  33477. BABYLON.serialize()
  33478. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  33479. __decorate([
  33480. BABYLON.serialize()
  33481. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  33482. __decorate([
  33483. BABYLON.serializeAsColor4()
  33484. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  33485. __decorate([
  33486. BABYLON.serialize()
  33487. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  33488. __decorate([
  33489. BABYLON.serialize()
  33490. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  33491. __decorate([
  33492. BABYLON.serialize()
  33493. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  33494. __decorate([
  33495. BABYLON.serialize()
  33496. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  33497. __decorate([
  33498. BABYLON.serialize()
  33499. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  33500. return ImageProcessingConfiguration;
  33501. }());
  33502. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  33503. })(BABYLON || (BABYLON = {}));
  33504. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  33505. var BABYLON;
  33506. (function (BABYLON) {
  33507. /**
  33508. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  33509. * It can help converting any input color in a desired output one. This can then be used to create effects
  33510. * from sepia, black and white to sixties or futuristic rendering...
  33511. *
  33512. * The only supported format is currently 3dl.
  33513. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  33514. */
  33515. var ColorGradingTexture = /** @class */ (function (_super) {
  33516. __extends(ColorGradingTexture, _super);
  33517. /**
  33518. * Instantiates a ColorGradingTexture from the following parameters.
  33519. *
  33520. * @param url The location of the color gradind data (currently only supporting 3dl)
  33521. * @param scene The scene the texture will be used in
  33522. */
  33523. function ColorGradingTexture(url, scene) {
  33524. var _this = _super.call(this, scene) || this;
  33525. if (!url) {
  33526. return _this;
  33527. }
  33528. _this._engine = scene.getEngine();
  33529. _this._textureMatrix = BABYLON.Matrix.Identity();
  33530. _this.name = url;
  33531. _this.url = url;
  33532. _this.hasAlpha = false;
  33533. _this.isCube = false;
  33534. _this.is3D = _this._engine.webGLVersion > 1;
  33535. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33536. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33537. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33538. _this.anisotropicFilteringLevel = 1;
  33539. _this._texture = _this._getFromCache(url, true);
  33540. if (!_this._texture) {
  33541. if (!scene.useDelayedTextureLoading) {
  33542. _this.loadTexture();
  33543. }
  33544. else {
  33545. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33546. }
  33547. }
  33548. return _this;
  33549. }
  33550. /**
  33551. * Returns the texture matrix used in most of the material.
  33552. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  33553. */
  33554. ColorGradingTexture.prototype.getTextureMatrix = function () {
  33555. return this._textureMatrix;
  33556. };
  33557. /**
  33558. * Occurs when the file being loaded is a .3dl LUT file.
  33559. */
  33560. ColorGradingTexture.prototype.load3dlTexture = function () {
  33561. var engine = this._engine;
  33562. var texture;
  33563. if (engine.webGLVersion === 1) {
  33564. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33565. }
  33566. else {
  33567. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33568. }
  33569. this._texture = texture;
  33570. var callback = function (text) {
  33571. if (typeof text !== "string") {
  33572. return;
  33573. }
  33574. var data = null;
  33575. var tempData = null;
  33576. var line;
  33577. var lines = text.split('\n');
  33578. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  33579. var maxColor = 0;
  33580. for (var i = 0; i < lines.length; i++) {
  33581. line = lines[i];
  33582. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  33583. continue;
  33584. if (line.indexOf('#') === 0)
  33585. continue;
  33586. var words = line.split(" ");
  33587. if (size === 0) {
  33588. // Number of space + one
  33589. size = words.length;
  33590. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  33591. tempData = new Float32Array(size * size * size * 4);
  33592. continue;
  33593. }
  33594. if (size != 0) {
  33595. var r = Math.max(parseInt(words[0]), 0);
  33596. var g = Math.max(parseInt(words[1]), 0);
  33597. var b = Math.max(parseInt(words[2]), 0);
  33598. maxColor = Math.max(r, maxColor);
  33599. maxColor = Math.max(g, maxColor);
  33600. maxColor = Math.max(b, maxColor);
  33601. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  33602. if (tempData) {
  33603. tempData[pixelStorageIndex + 0] = r;
  33604. tempData[pixelStorageIndex + 1] = g;
  33605. tempData[pixelStorageIndex + 2] = b;
  33606. }
  33607. pixelIndexSlice++;
  33608. if (pixelIndexSlice % size == 0) {
  33609. pixelIndexH++;
  33610. pixelIndexSlice = 0;
  33611. if (pixelIndexH % size == 0) {
  33612. pixelIndexW++;
  33613. pixelIndexH = 0;
  33614. }
  33615. }
  33616. }
  33617. }
  33618. if (tempData && data) {
  33619. for (var i = 0; i < tempData.length; i++) {
  33620. if (i > 0 && (i + 1) % 4 === 0) {
  33621. data[i] = 255;
  33622. }
  33623. else {
  33624. var value = tempData[i];
  33625. data[i] = (value / maxColor * 255);
  33626. }
  33627. }
  33628. }
  33629. if (texture.is3D) {
  33630. texture.updateSize(size, size, size);
  33631. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33632. }
  33633. else {
  33634. texture.updateSize(size * size, size);
  33635. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33636. }
  33637. };
  33638. var scene = this.getScene();
  33639. if (scene) {
  33640. scene._loadFile(this.url, callback);
  33641. }
  33642. else {
  33643. this._engine._loadFile(this.url, callback);
  33644. }
  33645. return this._texture;
  33646. };
  33647. /**
  33648. * Starts the loading process of the texture.
  33649. */
  33650. ColorGradingTexture.prototype.loadTexture = function () {
  33651. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  33652. this.load3dlTexture();
  33653. }
  33654. };
  33655. /**
  33656. * Clones the color gradind texture.
  33657. */
  33658. ColorGradingTexture.prototype.clone = function () {
  33659. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  33660. // Base texture
  33661. newTexture.level = this.level;
  33662. return newTexture;
  33663. };
  33664. /**
  33665. * Called during delayed load for textures.
  33666. */
  33667. ColorGradingTexture.prototype.delayLoad = function () {
  33668. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33669. return;
  33670. }
  33671. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33672. this._texture = this._getFromCache(this.url, true);
  33673. if (!this._texture) {
  33674. this.loadTexture();
  33675. }
  33676. };
  33677. /**
  33678. * Parses a color grading texture serialized by Babylon.
  33679. * @param parsedTexture The texture information being parsedTexture
  33680. * @param scene The scene to load the texture in
  33681. * @param rootUrl The root url of the data assets to load
  33682. * @return A color gradind texture
  33683. */
  33684. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  33685. var texture = null;
  33686. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  33687. texture = new ColorGradingTexture(parsedTexture.name, scene);
  33688. texture.name = parsedTexture.name;
  33689. texture.level = parsedTexture.level;
  33690. }
  33691. return texture;
  33692. };
  33693. /**
  33694. * Serializes the LUT texture to json format.
  33695. */
  33696. ColorGradingTexture.prototype.serialize = function () {
  33697. if (!this.name) {
  33698. return null;
  33699. }
  33700. var serializationObject = {};
  33701. serializationObject.name = this.name;
  33702. serializationObject.level = this.level;
  33703. serializationObject.customType = "BABYLON.ColorGradingTexture";
  33704. return serializationObject;
  33705. };
  33706. /**
  33707. * Empty line regex stored for GC.
  33708. */
  33709. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  33710. return ColorGradingTexture;
  33711. }(BABYLON.BaseTexture));
  33712. BABYLON.ColorGradingTexture = ColorGradingTexture;
  33713. })(BABYLON || (BABYLON = {}));
  33714. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  33715. var BABYLON;
  33716. (function (BABYLON) {
  33717. /**
  33718. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33719. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33720. * 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;
  33721. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33722. */
  33723. var ColorCurves = /** @class */ (function () {
  33724. function ColorCurves() {
  33725. this._dirty = true;
  33726. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  33727. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  33728. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  33729. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  33730. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  33731. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  33732. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  33733. this._globalHue = 30;
  33734. this._globalDensity = 0;
  33735. this._globalSaturation = 0;
  33736. this._globalExposure = 0;
  33737. this._highlightsHue = 30;
  33738. this._highlightsDensity = 0;
  33739. this._highlightsSaturation = 0;
  33740. this._highlightsExposure = 0;
  33741. this._midtonesHue = 30;
  33742. this._midtonesDensity = 0;
  33743. this._midtonesSaturation = 0;
  33744. this._midtonesExposure = 0;
  33745. this._shadowsHue = 30;
  33746. this._shadowsDensity = 0;
  33747. this._shadowsSaturation = 0;
  33748. this._shadowsExposure = 0;
  33749. }
  33750. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  33751. /**
  33752. * Gets the global Hue value.
  33753. * 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).
  33754. */
  33755. get: function () {
  33756. return this._globalHue;
  33757. },
  33758. /**
  33759. * Sets the global Hue value.
  33760. * 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).
  33761. */
  33762. set: function (value) {
  33763. this._globalHue = value;
  33764. this._dirty = true;
  33765. },
  33766. enumerable: true,
  33767. configurable: true
  33768. });
  33769. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  33770. /**
  33771. * Gets the global Density value.
  33772. * 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.
  33773. * Values less than zero provide a filter of opposite hue.
  33774. */
  33775. get: function () {
  33776. return this._globalDensity;
  33777. },
  33778. /**
  33779. * Sets the global Density value.
  33780. * 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.
  33781. * Values less than zero provide a filter of opposite hue.
  33782. */
  33783. set: function (value) {
  33784. this._globalDensity = value;
  33785. this._dirty = true;
  33786. },
  33787. enumerable: true,
  33788. configurable: true
  33789. });
  33790. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  33791. /**
  33792. * Gets the global Saturation value.
  33793. * 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.
  33794. */
  33795. get: function () {
  33796. return this._globalSaturation;
  33797. },
  33798. /**
  33799. * Sets the global Saturation value.
  33800. * 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.
  33801. */
  33802. set: function (value) {
  33803. this._globalSaturation = value;
  33804. this._dirty = true;
  33805. },
  33806. enumerable: true,
  33807. configurable: true
  33808. });
  33809. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  33810. /**
  33811. * Gets the highlights Hue value.
  33812. * 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).
  33813. */
  33814. get: function () {
  33815. return this._highlightsHue;
  33816. },
  33817. /**
  33818. * Sets the highlights Hue value.
  33819. * 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).
  33820. */
  33821. set: function (value) {
  33822. this._highlightsHue = value;
  33823. this._dirty = true;
  33824. },
  33825. enumerable: true,
  33826. configurable: true
  33827. });
  33828. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  33829. /**
  33830. * Gets the highlights Density value.
  33831. * 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.
  33832. * Values less than zero provide a filter of opposite hue.
  33833. */
  33834. get: function () {
  33835. return this._highlightsDensity;
  33836. },
  33837. /**
  33838. * Sets the highlights Density value.
  33839. * 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.
  33840. * Values less than zero provide a filter of opposite hue.
  33841. */
  33842. set: function (value) {
  33843. this._highlightsDensity = value;
  33844. this._dirty = true;
  33845. },
  33846. enumerable: true,
  33847. configurable: true
  33848. });
  33849. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  33850. /**
  33851. * Gets the highlights Saturation value.
  33852. * 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.
  33853. */
  33854. get: function () {
  33855. return this._highlightsSaturation;
  33856. },
  33857. /**
  33858. * Sets the highlights Saturation value.
  33859. * 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.
  33860. */
  33861. set: function (value) {
  33862. this._highlightsSaturation = value;
  33863. this._dirty = true;
  33864. },
  33865. enumerable: true,
  33866. configurable: true
  33867. });
  33868. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  33869. /**
  33870. * Gets the highlights Exposure value.
  33871. * 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.
  33872. */
  33873. get: function () {
  33874. return this._highlightsExposure;
  33875. },
  33876. /**
  33877. * Sets the highlights Exposure value.
  33878. * 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.
  33879. */
  33880. set: function (value) {
  33881. this._highlightsExposure = value;
  33882. this._dirty = true;
  33883. },
  33884. enumerable: true,
  33885. configurable: true
  33886. });
  33887. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  33888. /**
  33889. * Gets the midtones Hue value.
  33890. * 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).
  33891. */
  33892. get: function () {
  33893. return this._midtonesHue;
  33894. },
  33895. /**
  33896. * Sets the midtones Hue value.
  33897. * 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).
  33898. */
  33899. set: function (value) {
  33900. this._midtonesHue = value;
  33901. this._dirty = true;
  33902. },
  33903. enumerable: true,
  33904. configurable: true
  33905. });
  33906. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  33907. /**
  33908. * Gets the midtones Density value.
  33909. * 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.
  33910. * Values less than zero provide a filter of opposite hue.
  33911. */
  33912. get: function () {
  33913. return this._midtonesDensity;
  33914. },
  33915. /**
  33916. * Sets the midtones Density value.
  33917. * 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.
  33918. * Values less than zero provide a filter of opposite hue.
  33919. */
  33920. set: function (value) {
  33921. this._midtonesDensity = value;
  33922. this._dirty = true;
  33923. },
  33924. enumerable: true,
  33925. configurable: true
  33926. });
  33927. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  33928. /**
  33929. * Gets the midtones Saturation value.
  33930. * 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.
  33931. */
  33932. get: function () {
  33933. return this._midtonesSaturation;
  33934. },
  33935. /**
  33936. * Sets the midtones Saturation value.
  33937. * 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.
  33938. */
  33939. set: function (value) {
  33940. this._midtonesSaturation = value;
  33941. this._dirty = true;
  33942. },
  33943. enumerable: true,
  33944. configurable: true
  33945. });
  33946. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  33947. /**
  33948. * Gets the midtones Exposure value.
  33949. * 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.
  33950. */
  33951. get: function () {
  33952. return this._midtonesExposure;
  33953. },
  33954. /**
  33955. * Sets the midtones Exposure value.
  33956. * 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.
  33957. */
  33958. set: function (value) {
  33959. this._midtonesExposure = value;
  33960. this._dirty = true;
  33961. },
  33962. enumerable: true,
  33963. configurable: true
  33964. });
  33965. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  33966. /**
  33967. * Gets the shadows Hue value.
  33968. * 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).
  33969. */
  33970. get: function () {
  33971. return this._shadowsHue;
  33972. },
  33973. /**
  33974. * Sets the shadows Hue value.
  33975. * 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).
  33976. */
  33977. set: function (value) {
  33978. this._shadowsHue = value;
  33979. this._dirty = true;
  33980. },
  33981. enumerable: true,
  33982. configurable: true
  33983. });
  33984. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  33985. /**
  33986. * Gets the shadows Density value.
  33987. * 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.
  33988. * Values less than zero provide a filter of opposite hue.
  33989. */
  33990. get: function () {
  33991. return this._shadowsDensity;
  33992. },
  33993. /**
  33994. * Sets the shadows Density value.
  33995. * 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.
  33996. * Values less than zero provide a filter of opposite hue.
  33997. */
  33998. set: function (value) {
  33999. this._shadowsDensity = value;
  34000. this._dirty = true;
  34001. },
  34002. enumerable: true,
  34003. configurable: true
  34004. });
  34005. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  34006. /**
  34007. * Gets the shadows Saturation value.
  34008. * 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.
  34009. */
  34010. get: function () {
  34011. return this._shadowsSaturation;
  34012. },
  34013. /**
  34014. * Sets the shadows Saturation value.
  34015. * 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.
  34016. */
  34017. set: function (value) {
  34018. this._shadowsSaturation = value;
  34019. this._dirty = true;
  34020. },
  34021. enumerable: true,
  34022. configurable: true
  34023. });
  34024. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  34025. /**
  34026. * Gets the shadows Exposure value.
  34027. * 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.
  34028. */
  34029. get: function () {
  34030. return this._shadowsExposure;
  34031. },
  34032. /**
  34033. * Sets the shadows Exposure value.
  34034. * 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.
  34035. */
  34036. set: function (value) {
  34037. this._shadowsExposure = value;
  34038. this._dirty = true;
  34039. },
  34040. enumerable: true,
  34041. configurable: true
  34042. });
  34043. ColorCurves.prototype.getClassName = function () {
  34044. return "ColorCurves";
  34045. };
  34046. /**
  34047. * Binds the color curves to the shader.
  34048. * @param colorCurves The color curve to bind
  34049. * @param effect The effect to bind to
  34050. */
  34051. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  34052. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  34053. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  34054. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  34055. if (colorCurves._dirty) {
  34056. colorCurves._dirty = false;
  34057. // Fill in global info.
  34058. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  34059. // Compute highlights info.
  34060. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  34061. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  34062. // Compute midtones info.
  34063. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  34064. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  34065. // Compute shadows info.
  34066. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  34067. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  34068. // Compute deltas (neutral is midtones).
  34069. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  34070. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  34071. }
  34072. if (effect) {
  34073. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  34074. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  34075. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  34076. }
  34077. };
  34078. /**
  34079. * Prepare the list of uniforms associated with the ColorCurves effects.
  34080. * @param uniformsList The list of uniforms used in the effect
  34081. */
  34082. ColorCurves.PrepareUniforms = function (uniformsList) {
  34083. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  34084. };
  34085. /**
  34086. * Returns color grading data based on a hue, density, saturation and exposure value.
  34087. * @param filterHue The hue of the color filter.
  34088. * @param filterDensity The density of the color filter.
  34089. * @param saturation The saturation.
  34090. * @param exposure The exposure.
  34091. * @param result The result data container.
  34092. */
  34093. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  34094. if (hue == null) {
  34095. return;
  34096. }
  34097. hue = ColorCurves.clamp(hue, 0, 360);
  34098. density = ColorCurves.clamp(density, -100, 100);
  34099. saturation = ColorCurves.clamp(saturation, -100, 100);
  34100. exposure = ColorCurves.clamp(exposure, -100, 100);
  34101. // Remap the slider/config filter density with non-linear mapping and also scale by half
  34102. // so that the maximum filter density is only 50% control. This provides fine control
  34103. // for small values and reasonable range.
  34104. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  34105. density *= 0.5;
  34106. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  34107. if (density < 0) {
  34108. density *= -1;
  34109. hue = (hue + 180) % 360;
  34110. }
  34111. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  34112. result.scaleToRef(2, result);
  34113. result.a = 1 + 0.01 * saturation;
  34114. };
  34115. /**
  34116. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  34117. * @param value The input slider value in range [-100,100].
  34118. * @returns Adjusted value.
  34119. */
  34120. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  34121. value /= 100;
  34122. var x = Math.abs(value);
  34123. x = Math.pow(x, 2);
  34124. if (value < 0) {
  34125. x *= -1;
  34126. }
  34127. x *= 100;
  34128. return x;
  34129. };
  34130. /**
  34131. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  34132. * @param hue The hue (H) input.
  34133. * @param saturation The saturation (S) input.
  34134. * @param brightness The brightness (B) input.
  34135. * @result An RGBA color represented as Vector4.
  34136. */
  34137. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  34138. var h = ColorCurves.clamp(hue, 0, 360);
  34139. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  34140. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  34141. if (s === 0) {
  34142. result.r = v;
  34143. result.g = v;
  34144. result.b = v;
  34145. }
  34146. else {
  34147. // sector 0 to 5
  34148. h /= 60;
  34149. var i = Math.floor(h);
  34150. // fractional part of h
  34151. var f = h - i;
  34152. var p = v * (1 - s);
  34153. var q = v * (1 - s * f);
  34154. var t = v * (1 - s * (1 - f));
  34155. switch (i) {
  34156. case 0:
  34157. result.r = v;
  34158. result.g = t;
  34159. result.b = p;
  34160. break;
  34161. case 1:
  34162. result.r = q;
  34163. result.g = v;
  34164. result.b = p;
  34165. break;
  34166. case 2:
  34167. result.r = p;
  34168. result.g = v;
  34169. result.b = t;
  34170. break;
  34171. case 3:
  34172. result.r = p;
  34173. result.g = q;
  34174. result.b = v;
  34175. break;
  34176. case 4:
  34177. result.r = t;
  34178. result.g = p;
  34179. result.b = v;
  34180. break;
  34181. default:// case 5:
  34182. result.r = v;
  34183. result.g = p;
  34184. result.b = q;
  34185. break;
  34186. }
  34187. }
  34188. result.a = 1;
  34189. };
  34190. /**
  34191. * Returns a value clamped between min and max
  34192. * @param value The value to clamp
  34193. * @param min The minimum of value
  34194. * @param max The maximum of value
  34195. * @returns The clamped value.
  34196. */
  34197. ColorCurves.clamp = function (value, min, max) {
  34198. return Math.min(Math.max(value, min), max);
  34199. };
  34200. /**
  34201. * Clones the current color curve instance.
  34202. * @return The cloned curves
  34203. */
  34204. ColorCurves.prototype.clone = function () {
  34205. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  34206. };
  34207. /**
  34208. * Serializes the current color curve instance to a json representation.
  34209. * @return a JSON representation
  34210. */
  34211. ColorCurves.prototype.serialize = function () {
  34212. return BABYLON.SerializationHelper.Serialize(this);
  34213. };
  34214. /**
  34215. * Parses the color curve from a json representation.
  34216. * @param source the JSON source to parse
  34217. * @return The parsed curves
  34218. */
  34219. ColorCurves.Parse = function (source) {
  34220. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  34221. };
  34222. __decorate([
  34223. BABYLON.serialize()
  34224. ], ColorCurves.prototype, "_globalHue", void 0);
  34225. __decorate([
  34226. BABYLON.serialize()
  34227. ], ColorCurves.prototype, "_globalDensity", void 0);
  34228. __decorate([
  34229. BABYLON.serialize()
  34230. ], ColorCurves.prototype, "_globalSaturation", void 0);
  34231. __decorate([
  34232. BABYLON.serialize()
  34233. ], ColorCurves.prototype, "_globalExposure", void 0);
  34234. __decorate([
  34235. BABYLON.serialize()
  34236. ], ColorCurves.prototype, "_highlightsHue", void 0);
  34237. __decorate([
  34238. BABYLON.serialize()
  34239. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  34240. __decorate([
  34241. BABYLON.serialize()
  34242. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  34243. __decorate([
  34244. BABYLON.serialize()
  34245. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  34246. __decorate([
  34247. BABYLON.serialize()
  34248. ], ColorCurves.prototype, "_midtonesHue", void 0);
  34249. __decorate([
  34250. BABYLON.serialize()
  34251. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  34252. __decorate([
  34253. BABYLON.serialize()
  34254. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  34255. __decorate([
  34256. BABYLON.serialize()
  34257. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  34258. return ColorCurves;
  34259. }());
  34260. BABYLON.ColorCurves = ColorCurves;
  34261. })(BABYLON || (BABYLON = {}));
  34262. //# sourceMappingURL=babylon.colorCurves.js.map
  34263. //# sourceMappingURL=babylon.behavior.js.map
  34264. var BABYLON;
  34265. (function (BABYLON) {
  34266. var MaterialHelper = /** @class */ (function () {
  34267. function MaterialHelper() {
  34268. }
  34269. MaterialHelper.BindEyePosition = function (effect, scene) {
  34270. if (scene._forcedViewPosition) {
  34271. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  34272. return;
  34273. }
  34274. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  34275. };
  34276. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  34277. defines._needUVs = true;
  34278. defines[key] = true;
  34279. if (texture.getTextureMatrix().isIdentity(true)) {
  34280. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  34281. if (texture.coordinatesIndex === 0) {
  34282. defines["MAINUV1"] = true;
  34283. }
  34284. else {
  34285. defines["MAINUV2"] = true;
  34286. }
  34287. }
  34288. else {
  34289. defines[key + "DIRECTUV"] = 0;
  34290. }
  34291. };
  34292. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  34293. var matrix = texture.getTextureMatrix();
  34294. if (!matrix.isIdentity(true)) {
  34295. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  34296. }
  34297. };
  34298. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  34299. if (defines._areMiscDirty) {
  34300. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  34301. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  34302. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  34303. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  34304. }
  34305. };
  34306. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  34307. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  34308. var changed = false;
  34309. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  34310. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  34311. changed = true;
  34312. }
  34313. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  34314. defines["ALPHATEST"] = !defines["ALPHATEST"];
  34315. changed = true;
  34316. }
  34317. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  34318. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  34319. changed = true;
  34320. }
  34321. if (defines["INSTANCES"] !== useInstances) {
  34322. defines["INSTANCES"] = useInstances;
  34323. changed = true;
  34324. }
  34325. if (changed) {
  34326. defines.markAsUnprocessed();
  34327. }
  34328. };
  34329. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  34330. if (useMorphTargets === void 0) { useMorphTargets = false; }
  34331. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  34332. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  34333. return false;
  34334. }
  34335. defines._normals = defines._needNormals;
  34336. defines._uvs = defines._needUVs;
  34337. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  34338. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  34339. defines["TANGENT"] = true;
  34340. }
  34341. if (defines._needUVs) {
  34342. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  34343. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  34344. }
  34345. else {
  34346. defines["UV1"] = false;
  34347. defines["UV2"] = false;
  34348. }
  34349. if (useVertexColor) {
  34350. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  34351. defines["VERTEXCOLOR"] = hasVertexColors;
  34352. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  34353. }
  34354. if (useBones) {
  34355. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  34356. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  34357. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  34358. }
  34359. else {
  34360. defines["NUM_BONE_INFLUENCERS"] = 0;
  34361. defines["BonesPerMesh"] = 0;
  34362. }
  34363. }
  34364. if (useMorphTargets) {
  34365. var manager = mesh.morphTargetManager;
  34366. if (manager) {
  34367. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  34368. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  34369. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  34370. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  34371. }
  34372. else {
  34373. defines["MORPHTARGETS_TANGENT"] = false;
  34374. defines["MORPHTARGETS_NORMAL"] = false;
  34375. defines["MORPHTARGETS"] = false;
  34376. defines["NUM_MORPH_INFLUENCERS"] = 0;
  34377. }
  34378. }
  34379. return true;
  34380. };
  34381. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  34382. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34383. if (disableLighting === void 0) { disableLighting = false; }
  34384. if (!defines._areLightsDirty) {
  34385. return defines._needNormals;
  34386. }
  34387. var lightIndex = 0;
  34388. var needNormals = false;
  34389. var needRebuild = false;
  34390. var lightmapMode = false;
  34391. var shadowEnabled = false;
  34392. var specularEnabled = false;
  34393. if (scene.lightsEnabled && !disableLighting) {
  34394. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  34395. var light = _a[_i];
  34396. needNormals = true;
  34397. if (defines["LIGHT" + lightIndex] === undefined) {
  34398. needRebuild = true;
  34399. }
  34400. defines["LIGHT" + lightIndex] = true;
  34401. defines["SPOTLIGHT" + lightIndex] = false;
  34402. defines["HEMILIGHT" + lightIndex] = false;
  34403. defines["POINTLIGHT" + lightIndex] = false;
  34404. defines["DIRLIGHT" + lightIndex] = false;
  34405. var type;
  34406. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  34407. type = "SPOTLIGHT" + lightIndex;
  34408. }
  34409. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  34410. type = "HEMILIGHT" + lightIndex;
  34411. }
  34412. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  34413. type = "POINTLIGHT" + lightIndex;
  34414. }
  34415. else {
  34416. type = "DIRLIGHT" + lightIndex;
  34417. }
  34418. defines[type] = true;
  34419. // Specular
  34420. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  34421. specularEnabled = true;
  34422. }
  34423. // Shadows
  34424. defines["SHADOW" + lightIndex] = false;
  34425. defines["SHADOWPCF" + lightIndex] = false;
  34426. defines["SHADOWESM" + lightIndex] = false;
  34427. defines["SHADOWCUBE" + lightIndex] = false;
  34428. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  34429. var shadowGenerator = light.getShadowGenerator();
  34430. if (shadowGenerator) {
  34431. shadowEnabled = true;
  34432. shadowGenerator.prepareDefines(defines, lightIndex);
  34433. }
  34434. }
  34435. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  34436. lightmapMode = true;
  34437. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  34438. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  34439. }
  34440. else {
  34441. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  34442. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  34443. }
  34444. lightIndex++;
  34445. if (lightIndex === maxSimultaneousLights)
  34446. break;
  34447. }
  34448. }
  34449. defines["SPECULARTERM"] = specularEnabled;
  34450. defines["SHADOWS"] = shadowEnabled;
  34451. // Resetting all other lights if any
  34452. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  34453. if (defines["LIGHT" + index] !== undefined) {
  34454. defines["LIGHT" + index] = false;
  34455. defines["HEMILIGHT" + lightIndex] = false;
  34456. defines["POINTLIGHT" + lightIndex] = false;
  34457. defines["DIRLIGHT" + lightIndex] = false;
  34458. defines["SPOTLIGHT" + lightIndex] = false;
  34459. defines["SHADOW" + lightIndex] = false;
  34460. }
  34461. }
  34462. var caps = scene.getEngine().getCaps();
  34463. if (defines["SHADOWFLOAT"] === undefined) {
  34464. needRebuild = true;
  34465. }
  34466. defines["SHADOWFLOAT"] = shadowEnabled &&
  34467. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  34468. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  34469. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  34470. if (needRebuild) {
  34471. defines.rebuild();
  34472. }
  34473. return needNormals;
  34474. };
  34475. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  34476. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34477. var uniformsList;
  34478. var uniformBuffersList = null;
  34479. if (uniformsListOrOptions.uniformsNames) {
  34480. var options = uniformsListOrOptions;
  34481. uniformsList = options.uniformsNames;
  34482. uniformBuffersList = options.uniformBuffersNames;
  34483. samplersList = options.samplers;
  34484. defines = options.defines;
  34485. maxSimultaneousLights = options.maxSimultaneousLights;
  34486. }
  34487. else {
  34488. uniformsList = uniformsListOrOptions;
  34489. if (!samplersList) {
  34490. samplersList = [];
  34491. }
  34492. }
  34493. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  34494. if (!defines["LIGHT" + lightIndex]) {
  34495. break;
  34496. }
  34497. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  34498. if (uniformBuffersList) {
  34499. uniformBuffersList.push("Light" + lightIndex);
  34500. }
  34501. samplersList.push("shadowSampler" + lightIndex);
  34502. }
  34503. if (defines["NUM_MORPH_INFLUENCERS"]) {
  34504. uniformsList.push("morphTargetInfluences");
  34505. }
  34506. };
  34507. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  34508. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34509. if (rank === void 0) { rank = 0; }
  34510. var lightFallbackRank = 0;
  34511. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  34512. if (!defines["LIGHT" + lightIndex]) {
  34513. break;
  34514. }
  34515. if (lightIndex > 0) {
  34516. lightFallbackRank = rank + lightIndex;
  34517. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  34518. }
  34519. if (!defines["SHADOWS"]) {
  34520. if (defines["SHADOW" + lightIndex]) {
  34521. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  34522. }
  34523. if (defines["SHADOWPCF" + lightIndex]) {
  34524. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  34525. }
  34526. if (defines["SHADOWESM" + lightIndex]) {
  34527. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  34528. }
  34529. }
  34530. }
  34531. return lightFallbackRank++;
  34532. };
  34533. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  34534. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  34535. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  34536. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  34537. var manager = mesh.morphTargetManager;
  34538. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  34539. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  34540. for (var index = 0; index < influencers; index++) {
  34541. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  34542. if (normal) {
  34543. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  34544. }
  34545. if (tangent) {
  34546. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  34547. }
  34548. if (attribs.length > maxAttributesCount) {
  34549. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  34550. }
  34551. }
  34552. }
  34553. };
  34554. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  34555. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  34556. fallbacks.addCPUSkinningFallback(0, mesh);
  34557. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34558. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34559. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  34560. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34561. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  34562. }
  34563. }
  34564. };
  34565. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  34566. if (defines["INSTANCES"]) {
  34567. attribs.push("world0");
  34568. attribs.push("world1");
  34569. attribs.push("world2");
  34570. attribs.push("world3");
  34571. }
  34572. };
  34573. // Bindings
  34574. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  34575. if (light.shadowEnabled && mesh.receiveShadows) {
  34576. var shadowGenerator = light.getShadowGenerator();
  34577. if (shadowGenerator) {
  34578. shadowGenerator.bindShadowLight(lightIndex, effect);
  34579. }
  34580. }
  34581. };
  34582. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  34583. light.transferToEffect(effect, lightIndex + "");
  34584. };
  34585. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  34586. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34587. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  34588. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  34589. for (var i = 0; i < len; i++) {
  34590. var light = mesh._lightSources[i];
  34591. var iAsString = i.toString();
  34592. var scaledIntensity = light.getScaledIntensity();
  34593. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  34594. MaterialHelper.BindLightProperties(light, effect, i);
  34595. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  34596. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  34597. if (defines["SPECULARTERM"]) {
  34598. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  34599. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  34600. }
  34601. // Shadows
  34602. if (scene.shadowsEnabled) {
  34603. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  34604. }
  34605. light._uniformBuffer.update();
  34606. }
  34607. };
  34608. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  34609. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  34610. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  34611. effect.setColor3("vFogColor", scene.fogColor);
  34612. }
  34613. };
  34614. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  34615. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  34616. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  34617. if (matrices && effect) {
  34618. effect.setMatrices("mBones", matrices);
  34619. }
  34620. }
  34621. };
  34622. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  34623. var manager = abstractMesh.morphTargetManager;
  34624. if (!abstractMesh || !manager) {
  34625. return;
  34626. }
  34627. effect.setFloatArray("morphTargetInfluences", manager.influences);
  34628. };
  34629. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  34630. if (defines["LOGARITHMICDEPTH"]) {
  34631. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  34632. }
  34633. };
  34634. MaterialHelper.BindClipPlane = function (effect, scene) {
  34635. if (scene.clipPlane) {
  34636. var clipPlane = scene.clipPlane;
  34637. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  34638. }
  34639. };
  34640. return MaterialHelper;
  34641. }());
  34642. BABYLON.MaterialHelper = MaterialHelper;
  34643. })(BABYLON || (BABYLON = {}));
  34644. //# sourceMappingURL=babylon.materialHelper.js.map
  34645. var BABYLON;
  34646. (function (BABYLON) {
  34647. var PushMaterial = /** @class */ (function (_super) {
  34648. __extends(PushMaterial, _super);
  34649. function PushMaterial(name, scene) {
  34650. var _this = _super.call(this, name, scene) || this;
  34651. _this.storeEffectOnSubMeshes = true;
  34652. return _this;
  34653. }
  34654. PushMaterial.prototype.getEffect = function () {
  34655. return this._activeEffect;
  34656. };
  34657. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  34658. if (!mesh) {
  34659. return false;
  34660. }
  34661. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  34662. return true;
  34663. }
  34664. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  34665. };
  34666. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  34667. this._activeEffect.setMatrix("world", world);
  34668. };
  34669. PushMaterial.prototype.bind = function (world, mesh) {
  34670. if (!mesh) {
  34671. return;
  34672. }
  34673. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  34674. };
  34675. PushMaterial.prototype._afterBind = function (mesh, effect) {
  34676. if (effect === void 0) { effect = null; }
  34677. _super.prototype._afterBind.call(this, mesh);
  34678. this.getScene()._cachedEffect = effect;
  34679. };
  34680. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  34681. if (visibility === void 0) { visibility = 1; }
  34682. return scene.isCachedMaterialInvalid(this, effect, visibility);
  34683. };
  34684. return PushMaterial;
  34685. }(BABYLON.Material));
  34686. BABYLON.PushMaterial = PushMaterial;
  34687. })(BABYLON || (BABYLON = {}));
  34688. //# sourceMappingURL=babylon.pushMaterial.js.map
  34689. var BABYLON;
  34690. (function (BABYLON) {
  34691. var StandardMaterialDefines = /** @class */ (function (_super) {
  34692. __extends(StandardMaterialDefines, _super);
  34693. function StandardMaterialDefines() {
  34694. var _this = _super.call(this) || this;
  34695. _this.MAINUV1 = false;
  34696. _this.MAINUV2 = false;
  34697. _this.DIFFUSE = false;
  34698. _this.DIFFUSEDIRECTUV = 0;
  34699. _this.AMBIENT = false;
  34700. _this.AMBIENTDIRECTUV = 0;
  34701. _this.OPACITY = false;
  34702. _this.OPACITYDIRECTUV = 0;
  34703. _this.OPACITYRGB = false;
  34704. _this.REFLECTION = false;
  34705. _this.EMISSIVE = false;
  34706. _this.EMISSIVEDIRECTUV = 0;
  34707. _this.SPECULAR = false;
  34708. _this.SPECULARDIRECTUV = 0;
  34709. _this.BUMP = false;
  34710. _this.BUMPDIRECTUV = 0;
  34711. _this.PARALLAX = false;
  34712. _this.PARALLAXOCCLUSION = false;
  34713. _this.SPECULAROVERALPHA = false;
  34714. _this.CLIPPLANE = false;
  34715. _this.ALPHATEST = false;
  34716. _this.DEPTHPREPASS = false;
  34717. _this.ALPHAFROMDIFFUSE = false;
  34718. _this.POINTSIZE = false;
  34719. _this.FOG = false;
  34720. _this.SPECULARTERM = false;
  34721. _this.DIFFUSEFRESNEL = false;
  34722. _this.OPACITYFRESNEL = false;
  34723. _this.REFLECTIONFRESNEL = false;
  34724. _this.REFRACTIONFRESNEL = false;
  34725. _this.EMISSIVEFRESNEL = false;
  34726. _this.FRESNEL = false;
  34727. _this.NORMAL = false;
  34728. _this.UV1 = false;
  34729. _this.UV2 = false;
  34730. _this.VERTEXCOLOR = false;
  34731. _this.VERTEXALPHA = false;
  34732. _this.NUM_BONE_INFLUENCERS = 0;
  34733. _this.BonesPerMesh = 0;
  34734. _this.INSTANCES = false;
  34735. _this.GLOSSINESS = false;
  34736. _this.ROUGHNESS = false;
  34737. _this.EMISSIVEASILLUMINATION = false;
  34738. _this.LINKEMISSIVEWITHDIFFUSE = false;
  34739. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  34740. _this.LIGHTMAP = false;
  34741. _this.LIGHTMAPDIRECTUV = 0;
  34742. _this.USELIGHTMAPASSHADOWMAP = false;
  34743. _this.REFLECTIONMAP_3D = false;
  34744. _this.REFLECTIONMAP_SPHERICAL = false;
  34745. _this.REFLECTIONMAP_PLANAR = false;
  34746. _this.REFLECTIONMAP_CUBIC = false;
  34747. _this.REFLECTIONMAP_PROJECTION = false;
  34748. _this.REFLECTIONMAP_SKYBOX = false;
  34749. _this.REFLECTIONMAP_EXPLICIT = false;
  34750. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34751. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34752. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34753. _this.INVERTCUBICMAP = false;
  34754. _this.LOGARITHMICDEPTH = false;
  34755. _this.REFRACTION = false;
  34756. _this.REFRACTIONMAP_3D = false;
  34757. _this.REFLECTIONOVERALPHA = false;
  34758. _this.TWOSIDEDLIGHTING = false;
  34759. _this.SHADOWFLOAT = false;
  34760. _this.MORPHTARGETS = false;
  34761. _this.MORPHTARGETS_NORMAL = false;
  34762. _this.MORPHTARGETS_TANGENT = false;
  34763. _this.NUM_MORPH_INFLUENCERS = 0;
  34764. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  34765. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  34766. _this.IMAGEPROCESSING = false;
  34767. _this.VIGNETTE = false;
  34768. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  34769. _this.VIGNETTEBLENDMODEOPAQUE = false;
  34770. _this.TONEMAPPING = false;
  34771. _this.CONTRAST = false;
  34772. _this.COLORCURVES = false;
  34773. _this.COLORGRADING = false;
  34774. _this.COLORGRADING3D = false;
  34775. _this.SAMPLER3DGREENDEPTH = false;
  34776. _this.SAMPLER3DBGRMAP = false;
  34777. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  34778. _this.EXPOSURE = false;
  34779. _this.rebuild();
  34780. return _this;
  34781. }
  34782. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  34783. var modes = [
  34784. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  34785. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  34786. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  34787. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  34788. ];
  34789. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  34790. var mode = modes_1[_i];
  34791. this[mode] = (mode === modeToEnable);
  34792. }
  34793. };
  34794. return StandardMaterialDefines;
  34795. }(BABYLON.MaterialDefines));
  34796. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  34797. var StandardMaterial = /** @class */ (function (_super) {
  34798. __extends(StandardMaterial, _super);
  34799. function StandardMaterial(name, scene) {
  34800. var _this = _super.call(this, name, scene) || this;
  34801. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  34802. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  34803. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  34804. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  34805. _this.specularPower = 64;
  34806. _this._useAlphaFromDiffuseTexture = false;
  34807. _this._useEmissiveAsIllumination = false;
  34808. _this._linkEmissiveWithDiffuse = false;
  34809. _this._useSpecularOverAlpha = false;
  34810. _this._useReflectionOverAlpha = false;
  34811. _this._disableLighting = false;
  34812. _this._useParallax = false;
  34813. _this._useParallaxOcclusion = false;
  34814. _this.parallaxScaleBias = 0.05;
  34815. _this._roughness = 0;
  34816. _this.indexOfRefraction = 0.98;
  34817. _this.invertRefractionY = true;
  34818. _this._useLightmapAsShadowmap = false;
  34819. _this._useReflectionFresnelFromSpecular = false;
  34820. _this._useGlossinessFromSpecularMapAlpha = false;
  34821. _this._maxSimultaneousLights = 4;
  34822. /**
  34823. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  34824. */
  34825. _this._invertNormalMapX = false;
  34826. /**
  34827. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  34828. */
  34829. _this._invertNormalMapY = false;
  34830. /**
  34831. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34832. */
  34833. _this._twoSidedLighting = false;
  34834. _this._renderTargets = new BABYLON.SmartArray(16);
  34835. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  34836. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34837. // Setup the default processing configuration to the scene.
  34838. _this._attachImageProcessingConfiguration(null);
  34839. _this.getRenderTargetTextures = function () {
  34840. _this._renderTargets.reset();
  34841. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  34842. _this._renderTargets.push(_this._reflectionTexture);
  34843. }
  34844. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  34845. _this._renderTargets.push(_this._refractionTexture);
  34846. }
  34847. return _this._renderTargets;
  34848. };
  34849. return _this;
  34850. }
  34851. ;
  34852. ;
  34853. ;
  34854. ;
  34855. ;
  34856. ;
  34857. ;
  34858. ;
  34859. ;
  34860. ;
  34861. ;
  34862. ;
  34863. ;
  34864. ;
  34865. ;
  34866. ;
  34867. ;
  34868. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  34869. /**
  34870. * Gets the image processing configuration used either in this material.
  34871. */
  34872. get: function () {
  34873. return this._imageProcessingConfiguration;
  34874. },
  34875. /**
  34876. * Sets the Default image processing configuration used either in the this material.
  34877. *
  34878. * If sets to null, the scene one is in use.
  34879. */
  34880. set: function (value) {
  34881. this._attachImageProcessingConfiguration(value);
  34882. // Ensure the effect will be rebuilt.
  34883. this._markAllSubMeshesAsTexturesDirty();
  34884. },
  34885. enumerable: true,
  34886. configurable: true
  34887. });
  34888. /**
  34889. * Attaches a new image processing configuration to the Standard Material.
  34890. * @param configuration
  34891. */
  34892. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  34893. var _this = this;
  34894. if (configuration === this._imageProcessingConfiguration) {
  34895. return;
  34896. }
  34897. // Detaches observer.
  34898. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34899. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34900. }
  34901. // Pick the scene configuration if needed.
  34902. if (!configuration) {
  34903. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  34904. }
  34905. else {
  34906. this._imageProcessingConfiguration = configuration;
  34907. }
  34908. // Attaches observer.
  34909. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  34910. _this._markAllSubMeshesAsImageProcessingDirty();
  34911. });
  34912. };
  34913. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  34914. /**
  34915. * Gets wether the color curves effect is enabled.
  34916. */
  34917. get: function () {
  34918. return this.imageProcessingConfiguration.colorCurvesEnabled;
  34919. },
  34920. /**
  34921. * Sets wether the color curves effect is enabled.
  34922. */
  34923. set: function (value) {
  34924. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  34925. },
  34926. enumerable: true,
  34927. configurable: true
  34928. });
  34929. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  34930. /**
  34931. * Gets wether the color grading effect is enabled.
  34932. */
  34933. get: function () {
  34934. return this.imageProcessingConfiguration.colorGradingEnabled;
  34935. },
  34936. /**
  34937. * Gets wether the color grading effect is enabled.
  34938. */
  34939. set: function (value) {
  34940. this.imageProcessingConfiguration.colorGradingEnabled = value;
  34941. },
  34942. enumerable: true,
  34943. configurable: true
  34944. });
  34945. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  34946. /**
  34947. * Gets wether tonemapping is enabled or not.
  34948. */
  34949. get: function () {
  34950. return this._imageProcessingConfiguration.toneMappingEnabled;
  34951. },
  34952. /**
  34953. * Sets wether tonemapping is enabled or not
  34954. */
  34955. set: function (value) {
  34956. this._imageProcessingConfiguration.toneMappingEnabled = value;
  34957. },
  34958. enumerable: true,
  34959. configurable: true
  34960. });
  34961. ;
  34962. ;
  34963. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  34964. /**
  34965. * The camera exposure used on this material.
  34966. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  34967. * This corresponds to a photographic exposure.
  34968. */
  34969. get: function () {
  34970. return this._imageProcessingConfiguration.exposure;
  34971. },
  34972. /**
  34973. * The camera exposure used on this material.
  34974. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  34975. * This corresponds to a photographic exposure.
  34976. */
  34977. set: function (value) {
  34978. this._imageProcessingConfiguration.exposure = value;
  34979. },
  34980. enumerable: true,
  34981. configurable: true
  34982. });
  34983. ;
  34984. ;
  34985. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  34986. /**
  34987. * Gets The camera contrast used on this material.
  34988. */
  34989. get: function () {
  34990. return this._imageProcessingConfiguration.contrast;
  34991. },
  34992. /**
  34993. * Sets The camera contrast used on this material.
  34994. */
  34995. set: function (value) {
  34996. this._imageProcessingConfiguration.contrast = value;
  34997. },
  34998. enumerable: true,
  34999. configurable: true
  35000. });
  35001. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  35002. /**
  35003. * Gets the Color Grading 2D Lookup Texture.
  35004. */
  35005. get: function () {
  35006. return this._imageProcessingConfiguration.colorGradingTexture;
  35007. },
  35008. /**
  35009. * Sets the Color Grading 2D Lookup Texture.
  35010. */
  35011. set: function (value) {
  35012. this._imageProcessingConfiguration.colorGradingTexture = value;
  35013. },
  35014. enumerable: true,
  35015. configurable: true
  35016. });
  35017. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  35018. /**
  35019. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35020. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35021. * 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;
  35022. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35023. */
  35024. get: function () {
  35025. return this._imageProcessingConfiguration.colorCurves;
  35026. },
  35027. /**
  35028. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35029. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35030. * 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;
  35031. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35032. */
  35033. set: function (value) {
  35034. this._imageProcessingConfiguration.colorCurves = value;
  35035. },
  35036. enumerable: true,
  35037. configurable: true
  35038. });
  35039. StandardMaterial.prototype.getClassName = function () {
  35040. return "StandardMaterial";
  35041. };
  35042. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  35043. get: function () {
  35044. return this._useLogarithmicDepth;
  35045. },
  35046. set: function (value) {
  35047. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  35048. this._markAllSubMeshesAsMiscDirty();
  35049. },
  35050. enumerable: true,
  35051. configurable: true
  35052. });
  35053. StandardMaterial.prototype.needAlphaBlending = function () {
  35054. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  35055. };
  35056. StandardMaterial.prototype.needAlphaTesting = function () {
  35057. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  35058. };
  35059. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  35060. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  35061. };
  35062. StandardMaterial.prototype.getAlphaTestTexture = function () {
  35063. return this._diffuseTexture;
  35064. };
  35065. /**
  35066. * Child classes can use it to update shaders
  35067. */
  35068. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35069. if (useInstances === void 0) { useInstances = false; }
  35070. if (subMesh.effect && this.isFrozen) {
  35071. if (this._wasPreviouslyReady && subMesh.effect) {
  35072. return true;
  35073. }
  35074. }
  35075. if (!subMesh._materialDefines) {
  35076. subMesh._materialDefines = new StandardMaterialDefines();
  35077. }
  35078. var scene = this.getScene();
  35079. var defines = subMesh._materialDefines;
  35080. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  35081. if (defines._renderId === scene.getRenderId()) {
  35082. return true;
  35083. }
  35084. }
  35085. var engine = scene.getEngine();
  35086. // Lights
  35087. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  35088. // Textures
  35089. if (defines._areTexturesDirty) {
  35090. defines._needUVs = false;
  35091. defines.MAINUV1 = false;
  35092. defines.MAINUV2 = false;
  35093. if (scene.texturesEnabled) {
  35094. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35095. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  35096. return false;
  35097. }
  35098. else {
  35099. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  35100. }
  35101. }
  35102. else {
  35103. defines.DIFFUSE = false;
  35104. }
  35105. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35106. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  35107. return false;
  35108. }
  35109. else {
  35110. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  35111. }
  35112. }
  35113. else {
  35114. defines.AMBIENT = false;
  35115. }
  35116. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35117. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  35118. return false;
  35119. }
  35120. else {
  35121. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  35122. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  35123. }
  35124. }
  35125. else {
  35126. defines.OPACITY = false;
  35127. }
  35128. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35129. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  35130. return false;
  35131. }
  35132. else {
  35133. defines._needNormals = true;
  35134. defines.REFLECTION = true;
  35135. defines.ROUGHNESS = (this._roughness > 0);
  35136. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  35137. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  35138. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  35139. switch (this._reflectionTexture.coordinatesMode) {
  35140. case BABYLON.Texture.CUBIC_MODE:
  35141. case BABYLON.Texture.INVCUBIC_MODE:
  35142. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  35143. break;
  35144. case BABYLON.Texture.EXPLICIT_MODE:
  35145. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  35146. break;
  35147. case BABYLON.Texture.PLANAR_MODE:
  35148. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  35149. break;
  35150. case BABYLON.Texture.PROJECTION_MODE:
  35151. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  35152. break;
  35153. case BABYLON.Texture.SKYBOX_MODE:
  35154. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  35155. break;
  35156. case BABYLON.Texture.SPHERICAL_MODE:
  35157. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  35158. break;
  35159. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  35160. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  35161. break;
  35162. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  35163. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  35164. break;
  35165. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  35166. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  35167. break;
  35168. }
  35169. }
  35170. }
  35171. else {
  35172. defines.REFLECTION = false;
  35173. }
  35174. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35175. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  35176. return false;
  35177. }
  35178. else {
  35179. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  35180. }
  35181. }
  35182. else {
  35183. defines.EMISSIVE = false;
  35184. }
  35185. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35186. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  35187. return false;
  35188. }
  35189. else {
  35190. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  35191. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  35192. }
  35193. }
  35194. else {
  35195. defines.LIGHTMAP = false;
  35196. }
  35197. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35198. if (!this._specularTexture.isReadyOrNotBlocking()) {
  35199. return false;
  35200. }
  35201. else {
  35202. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  35203. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  35204. }
  35205. }
  35206. else {
  35207. defines.SPECULAR = false;
  35208. }
  35209. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  35210. // Bump texure can not be not blocking.
  35211. if (!this._bumpTexture.isReady()) {
  35212. return false;
  35213. }
  35214. else {
  35215. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  35216. defines.PARALLAX = this._useParallax;
  35217. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  35218. }
  35219. }
  35220. else {
  35221. defines.BUMP = false;
  35222. }
  35223. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35224. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  35225. return false;
  35226. }
  35227. else {
  35228. defines._needUVs = true;
  35229. defines.REFRACTION = true;
  35230. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  35231. }
  35232. }
  35233. else {
  35234. defines.REFRACTION = false;
  35235. }
  35236. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  35237. }
  35238. else {
  35239. defines.DIFFUSE = false;
  35240. defines.AMBIENT = false;
  35241. defines.OPACITY = false;
  35242. defines.REFLECTION = false;
  35243. defines.EMISSIVE = false;
  35244. defines.LIGHTMAP = false;
  35245. defines.BUMP = false;
  35246. defines.REFRACTION = false;
  35247. }
  35248. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  35249. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  35250. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  35251. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  35252. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  35253. }
  35254. if (defines._areImageProcessingDirty) {
  35255. if (!this._imageProcessingConfiguration.isReady()) {
  35256. return false;
  35257. }
  35258. this._imageProcessingConfiguration.prepareDefines(defines);
  35259. }
  35260. if (defines._areFresnelDirty) {
  35261. if (StandardMaterial.FresnelEnabled) {
  35262. // Fresnel
  35263. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  35264. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  35265. this._reflectionFresnelParameters) {
  35266. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  35267. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  35268. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  35269. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  35270. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  35271. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  35272. defines._needNormals = true;
  35273. defines.FRESNEL = true;
  35274. }
  35275. }
  35276. else {
  35277. defines.FRESNEL = false;
  35278. }
  35279. }
  35280. // Misc.
  35281. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  35282. // Attribs
  35283. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  35284. // Values that need to be evaluated on every frame
  35285. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  35286. // Get correct effect
  35287. if (defines.isDirty) {
  35288. defines.markAsProcessed();
  35289. scene.resetCachedMaterial();
  35290. // Fallbacks
  35291. var fallbacks = new BABYLON.EffectFallbacks();
  35292. if (defines.REFLECTION) {
  35293. fallbacks.addFallback(0, "REFLECTION");
  35294. }
  35295. if (defines.SPECULAR) {
  35296. fallbacks.addFallback(0, "SPECULAR");
  35297. }
  35298. if (defines.BUMP) {
  35299. fallbacks.addFallback(0, "BUMP");
  35300. }
  35301. if (defines.PARALLAX) {
  35302. fallbacks.addFallback(1, "PARALLAX");
  35303. }
  35304. if (defines.PARALLAXOCCLUSION) {
  35305. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  35306. }
  35307. if (defines.SPECULAROVERALPHA) {
  35308. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  35309. }
  35310. if (defines.FOG) {
  35311. fallbacks.addFallback(1, "FOG");
  35312. }
  35313. if (defines.POINTSIZE) {
  35314. fallbacks.addFallback(0, "POINTSIZE");
  35315. }
  35316. if (defines.LOGARITHMICDEPTH) {
  35317. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  35318. }
  35319. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  35320. if (defines.SPECULARTERM) {
  35321. fallbacks.addFallback(0, "SPECULARTERM");
  35322. }
  35323. if (defines.DIFFUSEFRESNEL) {
  35324. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  35325. }
  35326. if (defines.OPACITYFRESNEL) {
  35327. fallbacks.addFallback(2, "OPACITYFRESNEL");
  35328. }
  35329. if (defines.REFLECTIONFRESNEL) {
  35330. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  35331. }
  35332. if (defines.EMISSIVEFRESNEL) {
  35333. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  35334. }
  35335. if (defines.FRESNEL) {
  35336. fallbacks.addFallback(4, "FRESNEL");
  35337. }
  35338. //Attributes
  35339. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35340. if (defines.NORMAL) {
  35341. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35342. }
  35343. if (defines.UV1) {
  35344. attribs.push(BABYLON.VertexBuffer.UVKind);
  35345. }
  35346. if (defines.UV2) {
  35347. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35348. }
  35349. if (defines.VERTEXCOLOR) {
  35350. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35351. }
  35352. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  35353. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  35354. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  35355. var shaderName = "default";
  35356. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  35357. "vFogInfos", "vFogColor", "pointSize",
  35358. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  35359. "mBones",
  35360. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  35361. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  35362. "logarithmicDepthConstant", "vTangentSpaceParams"
  35363. ];
  35364. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  35365. var uniformBuffers = ["Material", "Scene"];
  35366. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  35367. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  35368. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35369. uniformsNames: uniforms,
  35370. uniformBuffersNames: uniformBuffers,
  35371. samplers: samplers,
  35372. defines: defines,
  35373. maxSimultaneousLights: this._maxSimultaneousLights
  35374. });
  35375. if (this.customShaderNameResolve) {
  35376. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  35377. }
  35378. var join = defines.toString();
  35379. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  35380. attributes: attribs,
  35381. uniformsNames: uniforms,
  35382. uniformBuffersNames: uniformBuffers,
  35383. samplers: samplers,
  35384. defines: join,
  35385. fallbacks: fallbacks,
  35386. onCompiled: this.onCompiled,
  35387. onError: this.onError,
  35388. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35389. }, engine), defines);
  35390. this.buildUniformLayout();
  35391. }
  35392. if (!subMesh.effect || !subMesh.effect.isReady()) {
  35393. return false;
  35394. }
  35395. defines._renderId = scene.getRenderId();
  35396. this._wasPreviouslyReady = true;
  35397. return true;
  35398. };
  35399. StandardMaterial.prototype.buildUniformLayout = function () {
  35400. // Order is important !
  35401. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  35402. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  35403. this._uniformBuffer.addUniform("opacityParts", 4);
  35404. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  35405. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  35406. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  35407. this._uniformBuffer.addUniform("refractionRightColor", 4);
  35408. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  35409. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  35410. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  35411. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  35412. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35413. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35414. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35415. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35416. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  35417. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35418. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  35419. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35420. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35421. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35422. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35423. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35424. this._uniformBuffer.addUniform("specularMatrix", 16);
  35425. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35426. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  35427. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35428. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35429. this._uniformBuffer.addUniform("vSpecularColor", 4);
  35430. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35431. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  35432. this._uniformBuffer.addUniform("pointSize", 1);
  35433. this._uniformBuffer.create();
  35434. };
  35435. StandardMaterial.prototype.unbind = function () {
  35436. if (this._activeEffect) {
  35437. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35438. this._activeEffect.setTexture("reflection2DSampler", null);
  35439. }
  35440. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35441. this._activeEffect.setTexture("refraction2DSampler", null);
  35442. }
  35443. }
  35444. _super.prototype.unbind.call(this);
  35445. };
  35446. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35447. var scene = this.getScene();
  35448. var defines = subMesh._materialDefines;
  35449. if (!defines) {
  35450. return;
  35451. }
  35452. var effect = subMesh.effect;
  35453. if (!effect) {
  35454. return;
  35455. }
  35456. this._activeEffect = effect;
  35457. // Matrices
  35458. this.bindOnlyWorldMatrix(world);
  35459. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  35460. // Bones
  35461. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  35462. if (mustRebind) {
  35463. this._uniformBuffer.bindToEffect(effect, "Material");
  35464. this.bindViewProjection(effect);
  35465. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35466. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  35467. // Fresnel
  35468. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  35469. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  35470. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  35471. }
  35472. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  35473. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  35474. }
  35475. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  35476. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  35477. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  35478. }
  35479. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  35480. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  35481. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  35482. }
  35483. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  35484. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  35485. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  35486. }
  35487. }
  35488. // Textures
  35489. if (scene.texturesEnabled) {
  35490. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35491. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  35492. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  35493. }
  35494. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35495. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  35496. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  35497. }
  35498. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35499. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35500. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  35501. }
  35502. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35503. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  35504. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  35505. }
  35506. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35507. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35508. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  35509. }
  35510. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35511. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35512. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  35513. }
  35514. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35515. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  35516. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  35517. }
  35518. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35519. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  35520. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  35521. if (scene._mirroredCameraPosition) {
  35522. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  35523. }
  35524. else {
  35525. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  35526. }
  35527. }
  35528. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35529. var depth = 1.0;
  35530. if (!this._refractionTexture.isCube) {
  35531. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  35532. if (this._refractionTexture.depth) {
  35533. depth = this._refractionTexture.depth;
  35534. }
  35535. }
  35536. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  35537. }
  35538. }
  35539. // Point size
  35540. if (this.pointsCloud) {
  35541. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35542. }
  35543. if (defines.SPECULARTERM) {
  35544. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  35545. }
  35546. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  35547. // Diffuse
  35548. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  35549. }
  35550. // Textures
  35551. if (scene.texturesEnabled) {
  35552. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35553. effect.setTexture("diffuseSampler", this._diffuseTexture);
  35554. }
  35555. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35556. effect.setTexture("ambientSampler", this._ambientTexture);
  35557. }
  35558. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35559. effect.setTexture("opacitySampler", this._opacityTexture);
  35560. }
  35561. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35562. if (this._reflectionTexture.isCube) {
  35563. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  35564. }
  35565. else {
  35566. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  35567. }
  35568. }
  35569. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35570. effect.setTexture("emissiveSampler", this._emissiveTexture);
  35571. }
  35572. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35573. effect.setTexture("lightmapSampler", this._lightmapTexture);
  35574. }
  35575. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35576. effect.setTexture("specularSampler", this._specularTexture);
  35577. }
  35578. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35579. effect.setTexture("bumpSampler", this._bumpTexture);
  35580. }
  35581. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35582. var depth = 1.0;
  35583. if (this._refractionTexture.isCube) {
  35584. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  35585. }
  35586. else {
  35587. effect.setTexture("refraction2DSampler", this._refractionTexture);
  35588. }
  35589. }
  35590. }
  35591. // Clip plane
  35592. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  35593. // Colors
  35594. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  35595. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  35596. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35597. }
  35598. if (mustRebind || !this.isFrozen) {
  35599. // Lights
  35600. if (scene.lightsEnabled && !this._disableLighting) {
  35601. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  35602. }
  35603. // View
  35604. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  35605. this.bindView(effect);
  35606. }
  35607. // Fog
  35608. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  35609. // Morph targets
  35610. if (defines.NUM_MORPH_INFLUENCERS) {
  35611. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  35612. }
  35613. // Log. depth
  35614. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  35615. // image processing
  35616. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  35617. this._imageProcessingConfiguration.bind(this._activeEffect);
  35618. }
  35619. }
  35620. this._uniformBuffer.update();
  35621. this._afterBind(mesh, this._activeEffect);
  35622. };
  35623. StandardMaterial.prototype.getAnimatables = function () {
  35624. var results = [];
  35625. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  35626. results.push(this._diffuseTexture);
  35627. }
  35628. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35629. results.push(this._ambientTexture);
  35630. }
  35631. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35632. results.push(this._opacityTexture);
  35633. }
  35634. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35635. results.push(this._reflectionTexture);
  35636. }
  35637. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35638. results.push(this._emissiveTexture);
  35639. }
  35640. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  35641. results.push(this._specularTexture);
  35642. }
  35643. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35644. results.push(this._bumpTexture);
  35645. }
  35646. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35647. results.push(this._lightmapTexture);
  35648. }
  35649. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35650. results.push(this._refractionTexture);
  35651. }
  35652. return results;
  35653. };
  35654. StandardMaterial.prototype.getActiveTextures = function () {
  35655. var activeTextures = _super.prototype.getActiveTextures.call(this);
  35656. if (this._diffuseTexture) {
  35657. activeTextures.push(this._diffuseTexture);
  35658. }
  35659. if (this._ambientTexture) {
  35660. activeTextures.push(this._ambientTexture);
  35661. }
  35662. if (this._opacityTexture) {
  35663. activeTextures.push(this._opacityTexture);
  35664. }
  35665. if (this._reflectionTexture) {
  35666. activeTextures.push(this._reflectionTexture);
  35667. }
  35668. if (this._emissiveTexture) {
  35669. activeTextures.push(this._emissiveTexture);
  35670. }
  35671. if (this._specularTexture) {
  35672. activeTextures.push(this._specularTexture);
  35673. }
  35674. if (this._bumpTexture) {
  35675. activeTextures.push(this._bumpTexture);
  35676. }
  35677. if (this._lightmapTexture) {
  35678. activeTextures.push(this._lightmapTexture);
  35679. }
  35680. if (this._refractionTexture) {
  35681. activeTextures.push(this._refractionTexture);
  35682. }
  35683. return activeTextures;
  35684. };
  35685. StandardMaterial.prototype.hasTexture = function (texture) {
  35686. if (_super.prototype.hasTexture.call(this, texture)) {
  35687. return true;
  35688. }
  35689. if (this._diffuseTexture === texture) {
  35690. return true;
  35691. }
  35692. if (this._ambientTexture === texture) {
  35693. return true;
  35694. }
  35695. if (this._opacityTexture === texture) {
  35696. return true;
  35697. }
  35698. if (this._reflectionTexture === texture) {
  35699. return true;
  35700. }
  35701. if (this._emissiveTexture === texture) {
  35702. return true;
  35703. }
  35704. if (this._specularTexture === texture) {
  35705. return true;
  35706. }
  35707. if (this._bumpTexture === texture) {
  35708. return true;
  35709. }
  35710. if (this._lightmapTexture === texture) {
  35711. return true;
  35712. }
  35713. if (this._refractionTexture === texture) {
  35714. return true;
  35715. }
  35716. return false;
  35717. };
  35718. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35719. if (forceDisposeTextures) {
  35720. if (this._diffuseTexture) {
  35721. this._diffuseTexture.dispose();
  35722. }
  35723. if (this._ambientTexture) {
  35724. this._ambientTexture.dispose();
  35725. }
  35726. if (this._opacityTexture) {
  35727. this._opacityTexture.dispose();
  35728. }
  35729. if (this._reflectionTexture) {
  35730. this._reflectionTexture.dispose();
  35731. }
  35732. if (this._emissiveTexture) {
  35733. this._emissiveTexture.dispose();
  35734. }
  35735. if (this._specularTexture) {
  35736. this._specularTexture.dispose();
  35737. }
  35738. if (this._bumpTexture) {
  35739. this._bumpTexture.dispose();
  35740. }
  35741. if (this._lightmapTexture) {
  35742. this._lightmapTexture.dispose();
  35743. }
  35744. if (this._refractionTexture) {
  35745. this._refractionTexture.dispose();
  35746. }
  35747. }
  35748. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35749. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35750. }
  35751. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35752. };
  35753. StandardMaterial.prototype.clone = function (name) {
  35754. var _this = this;
  35755. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  35756. result.name = name;
  35757. result.id = name;
  35758. return result;
  35759. };
  35760. StandardMaterial.prototype.serialize = function () {
  35761. return BABYLON.SerializationHelper.Serialize(this);
  35762. };
  35763. // Statics
  35764. StandardMaterial.Parse = function (source, scene, rootUrl) {
  35765. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  35766. };
  35767. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  35768. get: function () {
  35769. return StandardMaterial._DiffuseTextureEnabled;
  35770. },
  35771. set: function (value) {
  35772. if (StandardMaterial._DiffuseTextureEnabled === value) {
  35773. return;
  35774. }
  35775. StandardMaterial._DiffuseTextureEnabled = value;
  35776. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35777. },
  35778. enumerable: true,
  35779. configurable: true
  35780. });
  35781. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  35782. get: function () {
  35783. return StandardMaterial._AmbientTextureEnabled;
  35784. },
  35785. set: function (value) {
  35786. if (StandardMaterial._AmbientTextureEnabled === value) {
  35787. return;
  35788. }
  35789. StandardMaterial._AmbientTextureEnabled = value;
  35790. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35791. },
  35792. enumerable: true,
  35793. configurable: true
  35794. });
  35795. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  35796. get: function () {
  35797. return StandardMaterial._OpacityTextureEnabled;
  35798. },
  35799. set: function (value) {
  35800. if (StandardMaterial._OpacityTextureEnabled === value) {
  35801. return;
  35802. }
  35803. StandardMaterial._OpacityTextureEnabled = value;
  35804. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35805. },
  35806. enumerable: true,
  35807. configurable: true
  35808. });
  35809. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  35810. get: function () {
  35811. return StandardMaterial._ReflectionTextureEnabled;
  35812. },
  35813. set: function (value) {
  35814. if (StandardMaterial._ReflectionTextureEnabled === value) {
  35815. return;
  35816. }
  35817. StandardMaterial._ReflectionTextureEnabled = value;
  35818. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35819. },
  35820. enumerable: true,
  35821. configurable: true
  35822. });
  35823. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  35824. get: function () {
  35825. return StandardMaterial._EmissiveTextureEnabled;
  35826. },
  35827. set: function (value) {
  35828. if (StandardMaterial._EmissiveTextureEnabled === value) {
  35829. return;
  35830. }
  35831. StandardMaterial._EmissiveTextureEnabled = value;
  35832. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35833. },
  35834. enumerable: true,
  35835. configurable: true
  35836. });
  35837. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  35838. get: function () {
  35839. return StandardMaterial._SpecularTextureEnabled;
  35840. },
  35841. set: function (value) {
  35842. if (StandardMaterial._SpecularTextureEnabled === value) {
  35843. return;
  35844. }
  35845. StandardMaterial._SpecularTextureEnabled = value;
  35846. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35847. },
  35848. enumerable: true,
  35849. configurable: true
  35850. });
  35851. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  35852. get: function () {
  35853. return StandardMaterial._BumpTextureEnabled;
  35854. },
  35855. set: function (value) {
  35856. if (StandardMaterial._BumpTextureEnabled === value) {
  35857. return;
  35858. }
  35859. StandardMaterial._BumpTextureEnabled = value;
  35860. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35861. },
  35862. enumerable: true,
  35863. configurable: true
  35864. });
  35865. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  35866. get: function () {
  35867. return StandardMaterial._LightmapTextureEnabled;
  35868. },
  35869. set: function (value) {
  35870. if (StandardMaterial._LightmapTextureEnabled === value) {
  35871. return;
  35872. }
  35873. StandardMaterial._LightmapTextureEnabled = value;
  35874. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35875. },
  35876. enumerable: true,
  35877. configurable: true
  35878. });
  35879. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  35880. get: function () {
  35881. return StandardMaterial._RefractionTextureEnabled;
  35882. },
  35883. set: function (value) {
  35884. if (StandardMaterial._RefractionTextureEnabled === value) {
  35885. return;
  35886. }
  35887. StandardMaterial._RefractionTextureEnabled = value;
  35888. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35889. },
  35890. enumerable: true,
  35891. configurable: true
  35892. });
  35893. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  35894. get: function () {
  35895. return StandardMaterial._ColorGradingTextureEnabled;
  35896. },
  35897. set: function (value) {
  35898. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  35899. return;
  35900. }
  35901. StandardMaterial._ColorGradingTextureEnabled = value;
  35902. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35903. },
  35904. enumerable: true,
  35905. configurable: true
  35906. });
  35907. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  35908. get: function () {
  35909. return StandardMaterial._FresnelEnabled;
  35910. },
  35911. set: function (value) {
  35912. if (StandardMaterial._FresnelEnabled === value) {
  35913. return;
  35914. }
  35915. StandardMaterial._FresnelEnabled = value;
  35916. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  35917. },
  35918. enumerable: true,
  35919. configurable: true
  35920. });
  35921. // Flags used to enable or disable a type of texture for all Standard Materials
  35922. StandardMaterial._DiffuseTextureEnabled = true;
  35923. StandardMaterial._AmbientTextureEnabled = true;
  35924. StandardMaterial._OpacityTextureEnabled = true;
  35925. StandardMaterial._ReflectionTextureEnabled = true;
  35926. StandardMaterial._EmissiveTextureEnabled = true;
  35927. StandardMaterial._SpecularTextureEnabled = true;
  35928. StandardMaterial._BumpTextureEnabled = true;
  35929. StandardMaterial._LightmapTextureEnabled = true;
  35930. StandardMaterial._RefractionTextureEnabled = true;
  35931. StandardMaterial._ColorGradingTextureEnabled = true;
  35932. StandardMaterial._FresnelEnabled = true;
  35933. __decorate([
  35934. BABYLON.serializeAsTexture("diffuseTexture")
  35935. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  35936. __decorate([
  35937. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35938. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  35939. __decorate([
  35940. BABYLON.serializeAsTexture("ambientTexture")
  35941. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  35942. __decorate([
  35943. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35944. ], StandardMaterial.prototype, "ambientTexture", void 0);
  35945. __decorate([
  35946. BABYLON.serializeAsTexture("opacityTexture")
  35947. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  35948. __decorate([
  35949. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35950. ], StandardMaterial.prototype, "opacityTexture", void 0);
  35951. __decorate([
  35952. BABYLON.serializeAsTexture("reflectionTexture")
  35953. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  35954. __decorate([
  35955. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35956. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  35957. __decorate([
  35958. BABYLON.serializeAsTexture("emissiveTexture")
  35959. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  35960. __decorate([
  35961. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35962. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  35963. __decorate([
  35964. BABYLON.serializeAsTexture("specularTexture")
  35965. ], StandardMaterial.prototype, "_specularTexture", void 0);
  35966. __decorate([
  35967. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35968. ], StandardMaterial.prototype, "specularTexture", void 0);
  35969. __decorate([
  35970. BABYLON.serializeAsTexture("bumpTexture")
  35971. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  35972. __decorate([
  35973. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35974. ], StandardMaterial.prototype, "bumpTexture", void 0);
  35975. __decorate([
  35976. BABYLON.serializeAsTexture("lightmapTexture")
  35977. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  35978. __decorate([
  35979. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35980. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  35981. __decorate([
  35982. BABYLON.serializeAsTexture("refractionTexture")
  35983. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  35984. __decorate([
  35985. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35986. ], StandardMaterial.prototype, "refractionTexture", void 0);
  35987. __decorate([
  35988. BABYLON.serializeAsColor3("ambient")
  35989. ], StandardMaterial.prototype, "ambientColor", void 0);
  35990. __decorate([
  35991. BABYLON.serializeAsColor3("diffuse")
  35992. ], StandardMaterial.prototype, "diffuseColor", void 0);
  35993. __decorate([
  35994. BABYLON.serializeAsColor3("specular")
  35995. ], StandardMaterial.prototype, "specularColor", void 0);
  35996. __decorate([
  35997. BABYLON.serializeAsColor3("emissive")
  35998. ], StandardMaterial.prototype, "emissiveColor", void 0);
  35999. __decorate([
  36000. BABYLON.serialize()
  36001. ], StandardMaterial.prototype, "specularPower", void 0);
  36002. __decorate([
  36003. BABYLON.serialize("useAlphaFromDiffuseTexture")
  36004. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  36005. __decorate([
  36006. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36007. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  36008. __decorate([
  36009. BABYLON.serialize("useEmissiveAsIllumination")
  36010. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  36011. __decorate([
  36012. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36013. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  36014. __decorate([
  36015. BABYLON.serialize("linkEmissiveWithDiffuse")
  36016. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  36017. __decorate([
  36018. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36019. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  36020. __decorate([
  36021. BABYLON.serialize("useSpecularOverAlpha")
  36022. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  36023. __decorate([
  36024. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36025. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  36026. __decorate([
  36027. BABYLON.serialize("useReflectionOverAlpha")
  36028. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  36029. __decorate([
  36030. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36031. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  36032. __decorate([
  36033. BABYLON.serialize("disableLighting")
  36034. ], StandardMaterial.prototype, "_disableLighting", void 0);
  36035. __decorate([
  36036. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36037. ], StandardMaterial.prototype, "disableLighting", void 0);
  36038. __decorate([
  36039. BABYLON.serialize("useParallax")
  36040. ], StandardMaterial.prototype, "_useParallax", void 0);
  36041. __decorate([
  36042. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36043. ], StandardMaterial.prototype, "useParallax", void 0);
  36044. __decorate([
  36045. BABYLON.serialize("useParallaxOcclusion")
  36046. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  36047. __decorate([
  36048. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36049. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  36050. __decorate([
  36051. BABYLON.serialize()
  36052. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  36053. __decorate([
  36054. BABYLON.serialize("roughness")
  36055. ], StandardMaterial.prototype, "_roughness", void 0);
  36056. __decorate([
  36057. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36058. ], StandardMaterial.prototype, "roughness", void 0);
  36059. __decorate([
  36060. BABYLON.serialize()
  36061. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  36062. __decorate([
  36063. BABYLON.serialize()
  36064. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  36065. __decorate([
  36066. BABYLON.serialize("useLightmapAsShadowmap")
  36067. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  36068. __decorate([
  36069. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36070. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  36071. __decorate([
  36072. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  36073. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  36074. __decorate([
  36075. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36076. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  36077. __decorate([
  36078. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  36079. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  36080. __decorate([
  36081. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36082. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  36083. __decorate([
  36084. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  36085. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  36086. __decorate([
  36087. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36088. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  36089. __decorate([
  36090. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  36091. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  36092. __decorate([
  36093. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36094. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  36095. __decorate([
  36096. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  36097. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  36098. __decorate([
  36099. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36100. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  36101. __decorate([
  36102. BABYLON.serialize("useReflectionFresnelFromSpecular")
  36103. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  36104. __decorate([
  36105. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36106. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  36107. __decorate([
  36108. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  36109. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  36110. __decorate([
  36111. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36112. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  36113. __decorate([
  36114. BABYLON.serialize("maxSimultaneousLights")
  36115. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  36116. __decorate([
  36117. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36118. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  36119. __decorate([
  36120. BABYLON.serialize("invertNormalMapX")
  36121. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  36122. __decorate([
  36123. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36124. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  36125. __decorate([
  36126. BABYLON.serialize("invertNormalMapY")
  36127. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  36128. __decorate([
  36129. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36130. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  36131. __decorate([
  36132. BABYLON.serialize("twoSidedLighting")
  36133. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  36134. __decorate([
  36135. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36136. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  36137. __decorate([
  36138. BABYLON.serialize()
  36139. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  36140. return StandardMaterial;
  36141. }(BABYLON.PushMaterial));
  36142. BABYLON.StandardMaterial = StandardMaterial;
  36143. })(BABYLON || (BABYLON = {}));
  36144. //# sourceMappingURL=babylon.standardMaterial.js.map
  36145. (function() {
  36146. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  36147. globalObject["BABYLON"] = BABYLON;
  36148. })();;
  36149. var EffectFallbacks = BABYLON.EffectFallbacks;
  36150. var EffectCreationOptions = BABYLON.EffectCreationOptions;
  36151. var Effect = BABYLON.Effect;
  36152. var KeyboardEventTypes = BABYLON.KeyboardEventTypes;
  36153. var KeyboardInfo = BABYLON.KeyboardInfo;
  36154. var KeyboardInfoPre = BABYLON.KeyboardInfoPre;
  36155. var PointerEventTypes = BABYLON.PointerEventTypes;
  36156. var PointerInfoBase = BABYLON.PointerInfoBase;
  36157. var PointerInfoPre = BABYLON.PointerInfoPre;
  36158. var PointerInfo = BABYLON.PointerInfo;
  36159. var ToGammaSpace = BABYLON.ToGammaSpace;
  36160. var ToLinearSpace = BABYLON.ToLinearSpace;
  36161. var Epsilon = BABYLON.Epsilon;
  36162. var Color3 = BABYLON.Color3;
  36163. var Color4 = BABYLON.Color4;
  36164. var Vector2 = BABYLON.Vector2;
  36165. var Vector3 = BABYLON.Vector3;
  36166. var Vector4 = BABYLON.Vector4;
  36167. var Size = BABYLON.Size;
  36168. var Quaternion = BABYLON.Quaternion;
  36169. var Matrix = BABYLON.Matrix;
  36170. var Plane = BABYLON.Plane;
  36171. var Viewport = BABYLON.Viewport;
  36172. var Frustum = BABYLON.Frustum;
  36173. var Space = BABYLON.Space;
  36174. var Axis = BABYLON.Axis;
  36175. var BezierCurve = BABYLON.BezierCurve;
  36176. var Orientation = BABYLON.Orientation;
  36177. var Angle = BABYLON.Angle;
  36178. var Arc2 = BABYLON.Arc2;
  36179. var Path2 = BABYLON.Path2;
  36180. var Path3D = BABYLON.Path3D;
  36181. var Curve3 = BABYLON.Curve3;
  36182. var PositionNormalVertex = BABYLON.PositionNormalVertex;
  36183. var PositionNormalTextureVertex = BABYLON.PositionNormalTextureVertex;
  36184. var Tmp = BABYLON.Tmp;
  36185. var Scalar = BABYLON.Scalar;
  36186. var expandToProperty = BABYLON.expandToProperty;
  36187. var serialize = BABYLON.serialize;
  36188. var serializeAsTexture = BABYLON.serializeAsTexture;
  36189. var serializeAsColor3 = BABYLON.serializeAsColor3;
  36190. var serializeAsFresnelParameters = BABYLON.serializeAsFresnelParameters;
  36191. var serializeAsVector2 = BABYLON.serializeAsVector2;
  36192. var serializeAsVector3 = BABYLON.serializeAsVector3;
  36193. var serializeAsMeshReference = BABYLON.serializeAsMeshReference;
  36194. var serializeAsColorCurves = BABYLON.serializeAsColorCurves;
  36195. var serializeAsColor4 = BABYLON.serializeAsColor4;
  36196. var serializeAsImageProcessingConfiguration = BABYLON.serializeAsImageProcessingConfiguration;
  36197. var serializeAsQuaternion = BABYLON.serializeAsQuaternion;
  36198. var SerializationHelper = BABYLON.SerializationHelper;
  36199. var EventState = BABYLON.EventState;
  36200. var Observer = BABYLON.Observer;
  36201. var MultiObserver = BABYLON.MultiObserver;
  36202. var Observable = BABYLON.Observable;
  36203. var SmartArray = BABYLON.SmartArray;
  36204. var SmartArrayNoDuplicate = BABYLON.SmartArrayNoDuplicate;
  36205. var LoadFileError = BABYLON.LoadFileError;
  36206. var RetryStrategy = BABYLON.RetryStrategy;
  36207. var Tools = BABYLON.Tools;
  36208. var PerfCounter = BABYLON.PerfCounter;
  36209. var className = BABYLON.className;
  36210. var AsyncLoop = BABYLON.AsyncLoop;
  36211. var _AlphaState = BABYLON._AlphaState;
  36212. var _DepthCullingState = BABYLON._DepthCullingState;
  36213. var _StencilState = BABYLON._StencilState;
  36214. var InstancingAttributeInfo = BABYLON.InstancingAttributeInfo;
  36215. var RenderTargetCreationOptions = BABYLON.RenderTargetCreationOptions;
  36216. var EngineCapabilities = BABYLON.EngineCapabilities;
  36217. var Engine = BABYLON.Engine;
  36218. var Node = BABYLON.Node;
  36219. var BoundingSphere = BABYLON.BoundingSphere;
  36220. var BoundingBox = BABYLON.BoundingBox;
  36221. var BoundingInfo = BABYLON.BoundingInfo;
  36222. var TransformNode = BABYLON.TransformNode;
  36223. var AbstractMesh = BABYLON.AbstractMesh;
  36224. var Light = BABYLON.Light;
  36225. var Camera = BABYLON.Camera;
  36226. var RenderingManager = BABYLON.RenderingManager;
  36227. var RenderingGroup = BABYLON.RenderingGroup;
  36228. var RenderingGroupInfo = BABYLON.RenderingGroupInfo;
  36229. var Scene = BABYLON.Scene;
  36230. var Buffer = BABYLON.Buffer;
  36231. var VertexBuffer = BABYLON.VertexBuffer;
  36232. var InternalTexture = BABYLON.InternalTexture;
  36233. var BaseTexture = BABYLON.BaseTexture;
  36234. var Texture = BABYLON.Texture;
  36235. var _InstancesBatch = BABYLON._InstancesBatch;
  36236. var Mesh = BABYLON.Mesh;
  36237. var BaseSubMesh = BABYLON.BaseSubMesh;
  36238. var SubMesh = BABYLON.SubMesh;
  36239. var MaterialDefines = BABYLON.MaterialDefines;
  36240. var Material = BABYLON.Material;
  36241. var UniformBuffer = BABYLON.UniformBuffer;
  36242. var VertexData = BABYLON.VertexData;
  36243. var Geometry = BABYLON.Geometry;
  36244. var _PrimitiveGeometry = BABYLON._PrimitiveGeometry;
  36245. var RibbonGeometry = BABYLON.RibbonGeometry;
  36246. var BoxGeometry = BABYLON.BoxGeometry;
  36247. var SphereGeometry = BABYLON.SphereGeometry;
  36248. var DiscGeometry = BABYLON.DiscGeometry;
  36249. var CylinderGeometry = BABYLON.CylinderGeometry;
  36250. var TorusGeometry = BABYLON.TorusGeometry;
  36251. var GroundGeometry = BABYLON.GroundGeometry;
  36252. var TiledGroundGeometry = BABYLON.TiledGroundGeometry;
  36253. var PlaneGeometry = BABYLON.PlaneGeometry;
  36254. var TorusKnotGeometry = BABYLON.TorusKnotGeometry;
  36255. var PostProcessManager = BABYLON.PostProcessManager;
  36256. var PerformanceMonitor = BABYLON.PerformanceMonitor;
  36257. var RollingAverage = BABYLON.RollingAverage;
  36258. var ImageProcessingConfiguration = BABYLON.ImageProcessingConfiguration;
  36259. var ColorGradingTexture = BABYLON.ColorGradingTexture;
  36260. var ColorCurves = BABYLON.ColorCurves;
  36261. var MaterialHelper = BABYLON.MaterialHelper;
  36262. var PushMaterial = BABYLON.PushMaterial;
  36263. var StandardMaterialDefines = BABYLON.StandardMaterialDefines;
  36264. var StandardMaterial = BABYLON.StandardMaterial;
  36265. 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 };