babylon.scene.ts 253 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265
  1. module BABYLON {
  2. /**
  3. * Define an interface for all classes that will hold resources
  4. */
  5. export interface IDisposable {
  6. /**
  7. * Releases all held resources
  8. */
  9. dispose(): void;
  10. }
  11. /**
  12. * Interface used to let developers provide their own mesh selection mechanism
  13. */
  14. export interface IActiveMeshCandidateProvider {
  15. /**
  16. * Return the list of active meshes
  17. * @param scene defines the current scene
  18. * @returns the list of active meshes
  19. */
  20. getMeshes(scene: Scene): AbstractMesh[];
  21. /**
  22. * Indicates if the meshes have been checked to make sure they are isEnabled()
  23. */
  24. readonly checksIsEnabled: boolean;
  25. }
  26. /** @hidden */
  27. class ClickInfo {
  28. private _singleClick = false;
  29. private _doubleClick = false;
  30. private _hasSwiped = false;
  31. private _ignore = false;
  32. public get singleClick(): boolean {
  33. return this._singleClick;
  34. }
  35. public get doubleClick(): boolean {
  36. return this._doubleClick;
  37. }
  38. public get hasSwiped(): boolean {
  39. return this._hasSwiped;
  40. }
  41. public get ignore(): boolean {
  42. return this._ignore;
  43. }
  44. public set singleClick(b: boolean) {
  45. this._singleClick = b;
  46. }
  47. public set doubleClick(b: boolean) {
  48. this._doubleClick = b;
  49. }
  50. public set hasSwiped(b: boolean) {
  51. this._hasSwiped = b;
  52. }
  53. public set ignore(b: boolean) {
  54. this._ignore = b;
  55. }
  56. }
  57. /**
  58. * This class is used by the onRenderingGroupObservable
  59. */
  60. export class RenderingGroupInfo {
  61. /**
  62. * The Scene that being rendered
  63. */
  64. scene: Scene;
  65. /**
  66. * The camera currently used for the rendering pass
  67. */
  68. camera: Nullable<Camera>;
  69. /**
  70. * The ID of the renderingGroup being processed
  71. */
  72. renderingGroupId: number;
  73. /**
  74. * The rendering stage, can be either STAGE_PRECLEAR, STAGE_PREOPAQUE, STAGE_PRETRANSPARENT, STAGE_POSTTRANSPARENT
  75. */
  76. renderStage: number;
  77. /**
  78. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  79. * This stage will be fired no matter what
  80. */
  81. static STAGE_PRECLEAR = 1;
  82. /**
  83. * Called before opaque object are rendered.
  84. * This stage will be fired only if there's 3D Opaque content to render
  85. */
  86. static STAGE_PREOPAQUE = 2;
  87. /**
  88. * Called after the opaque objects are rendered and before the transparent ones
  89. * This stage will be fired only if there's 3D transparent content to render
  90. */
  91. static STAGE_PRETRANSPARENT = 3;
  92. /**
  93. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  94. * This stage will be fired no matter what
  95. */
  96. static STAGE_POSTTRANSPARENT = 4;
  97. }
  98. /**
  99. * Represents a scene to be rendered by the engine.
  100. * @see http://doc.babylonjs.com/features/scene
  101. */
  102. export class Scene implements IAnimatable {
  103. // Statics
  104. private static _FOGMODE_NONE = 0;
  105. private static _FOGMODE_EXP = 1;
  106. private static _FOGMODE_EXP2 = 2;
  107. private static _FOGMODE_LINEAR = 3;
  108. private static _uniqueIdCounter = 0;
  109. /**
  110. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  111. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  112. */
  113. public static MinDeltaTime = 1.0;
  114. /**
  115. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  116. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  117. */
  118. public static MaxDeltaTime = 1000.0;
  119. /** The fog is deactivated */
  120. public static get FOGMODE_NONE(): number {
  121. return Scene._FOGMODE_NONE;
  122. }
  123. /** The fog density is following an exponential function */
  124. public static get FOGMODE_EXP(): number {
  125. return Scene._FOGMODE_EXP;
  126. }
  127. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  128. public static get FOGMODE_EXP2(): number {
  129. return Scene._FOGMODE_EXP2;
  130. }
  131. /** The fog density is following a linear function. */
  132. public static get FOGMODE_LINEAR(): number {
  133. return Scene._FOGMODE_LINEAR;
  134. }
  135. // Members
  136. /**
  137. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  138. */
  139. public autoClear = true;
  140. /**
  141. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  142. */
  143. public autoClearDepthAndStencil = true;
  144. /**
  145. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  146. */
  147. public clearColor: Color4 = new Color4(0.2, 0.2, 0.3, 1.0);
  148. /**
  149. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  150. */
  151. public ambientColor = new Color3(0, 0, 0);
  152. /** @hidden */
  153. public _environmentBRDFTexture: BaseTexture;
  154. /** @hidden */
  155. protected _environmentTexture: BaseTexture;
  156. /**
  157. * Texture used in all pbr material as the reflection texture.
  158. * As in the majority of the scene they are the same (exception for multi room and so on),
  159. * this is easier to reference from here than from all the materials.
  160. */
  161. public get environmentTexture(): BaseTexture {
  162. return this._environmentTexture;
  163. }
  164. /**
  165. * Texture used in all pbr material as the reflection texture.
  166. * As in the majority of the scene they are the same (exception for multi room and so on),
  167. * this is easier to set here than in all the materials.
  168. */
  169. public set environmentTexture(value: BaseTexture) {
  170. if (this._environmentTexture === value) {
  171. return;
  172. }
  173. this._environmentTexture = value;
  174. this.markAllMaterialsAsDirty(Material.TextureDirtyFlag);
  175. }
  176. /** @hidden */
  177. protected _imageProcessingConfiguration: ImageProcessingConfiguration;
  178. /**
  179. * Default image processing configuration used either in the rendering
  180. * Forward main pass or through the imageProcessingPostProcess if present.
  181. * As in the majority of the scene they are the same (exception for multi camera),
  182. * this is easier to reference from here than from all the materials and post process.
  183. *
  184. * No setter as we it is a shared configuration, you can set the values instead.
  185. */
  186. public get imageProcessingConfiguration(): ImageProcessingConfiguration {
  187. return this._imageProcessingConfiguration;
  188. }
  189. private _forceWireframe = false;
  190. /**
  191. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  192. */
  193. public set forceWireframe(value: boolean) {
  194. if (this._forceWireframe === value) {
  195. return;
  196. }
  197. this._forceWireframe = value;
  198. this.markAllMaterialsAsDirty(Material.MiscDirtyFlag);
  199. }
  200. public get forceWireframe(): boolean {
  201. return this._forceWireframe;
  202. }
  203. private _forcePointsCloud = false;
  204. /**
  205. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  206. */
  207. public set forcePointsCloud(value: boolean) {
  208. if (this._forcePointsCloud === value) {
  209. return;
  210. }
  211. this._forcePointsCloud = value;
  212. this.markAllMaterialsAsDirty(Material.MiscDirtyFlag);
  213. }
  214. public get forcePointsCloud(): boolean {
  215. return this._forcePointsCloud;
  216. }
  217. /**
  218. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  219. */
  220. public forceShowBoundingBoxes = false;
  221. /**
  222. * Gets or sets the active clipplane
  223. */
  224. public clipPlane: Nullable<Plane>;
  225. /**
  226. * Gets or sets a boolean indicating if animations are enabled
  227. */
  228. public animationsEnabled = true;
  229. private _animationPropertiesOverride: Nullable<AnimationPropertiesOverride> = null;
  230. /**
  231. * Gets or sets the animation properties override
  232. */
  233. public get animationPropertiesOverride(): Nullable<AnimationPropertiesOverride> {
  234. return this._animationPropertiesOverride;
  235. }
  236. public set animationPropertiesOverride(value: Nullable<AnimationPropertiesOverride>) {
  237. this._animationPropertiesOverride = value;
  238. }
  239. /**
  240. * Gets or sets a boolean indicating if a constant deltatime has to be used
  241. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  242. */
  243. public useConstantAnimationDeltaTime = false;
  244. /**
  245. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  246. * Please note that it requires to run a ray cast through the scene on every frame
  247. */
  248. public constantlyUpdateMeshUnderPointer = false;
  249. /**
  250. * Defines the HTML cursor to use when hovering over interactive elements
  251. */
  252. public hoverCursor = "pointer";
  253. /**
  254. * Defines the HTML default cursor to use (empty by default)
  255. */
  256. public defaultCursor: string = "";
  257. /**
  258. * This is used to call preventDefault() on pointer down
  259. * in order to block unwanted artifacts like system double clicks
  260. */
  261. public preventDefaultOnPointerDown = true;
  262. // Metadata
  263. /**
  264. * Gets or sets user defined metadata
  265. */
  266. public metadata: any = null;
  267. /**
  268. * Gets the name of the plugin used to load this scene (null by default)
  269. */
  270. public loadingPluginName: string;
  271. /**
  272. * Use this array to add regular expressions used to disable offline support for specific urls
  273. */
  274. public disableOfflineSupportExceptionRules = new Array<RegExp>();
  275. // Events
  276. private _spritePredicate: (sprite: Sprite) => boolean;
  277. /**
  278. * An event triggered when the scene is disposed.
  279. */
  280. public onDisposeObservable = new Observable<Scene>();
  281. private _onDisposeObserver: Nullable<Observer<Scene>> = null;
  282. /** Sets a function to be executed when this scene is disposed. */
  283. public set onDispose(callback: () => void) {
  284. if (this._onDisposeObserver) {
  285. this.onDisposeObservable.remove(this._onDisposeObserver);
  286. }
  287. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  288. }
  289. /**
  290. * An event triggered before rendering the scene (right after animations and physics)
  291. */
  292. public onBeforeRenderObservable = new Observable<Scene>();
  293. private _onBeforeRenderObserver: Nullable<Observer<Scene>> = null;
  294. /** Sets a function to be executed before rendering this scene */
  295. public set beforeRender(callback: Nullable<() => void>) {
  296. if (this._onBeforeRenderObserver) {
  297. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  298. }
  299. if (callback) {
  300. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  301. }
  302. }
  303. /**
  304. * An event triggered after rendering the scene
  305. */
  306. public onAfterRenderObservable = new Observable<Scene>();
  307. private _onAfterRenderObserver: Nullable<Observer<Scene>> = null;
  308. /** Sets a function to be executed after rendering this scene */
  309. public set afterRender(callback: Nullable<() => void>) {
  310. if (this._onAfterRenderObserver) {
  311. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  312. }
  313. if (callback) {
  314. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  315. }
  316. }
  317. /**
  318. * An event triggered before animating the scene
  319. */
  320. public onBeforeAnimationsObservable = new Observable<Scene>();
  321. /**
  322. * An event triggered after animations processing
  323. */
  324. public onAfterAnimationsObservable = new Observable<Scene>();
  325. /**
  326. * An event triggered before draw calls are ready to be sent
  327. */
  328. public onBeforeDrawPhaseObservable = new Observable<Scene>();
  329. /**
  330. * An event triggered after draw calls have been sent
  331. */
  332. public onAfterDrawPhaseObservable = new Observable<Scene>();
  333. /**
  334. * An event triggered when physic simulation is about to be run
  335. */
  336. public onBeforePhysicsObservable = new Observable<Scene>();
  337. /**
  338. * An event triggered when physic simulation has been done
  339. */
  340. public onAfterPhysicsObservable = new Observable<Scene>();
  341. /**
  342. * An event triggered when the scene is ready
  343. */
  344. public onReadyObservable = new Observable<Scene>();
  345. /**
  346. * An event triggered before rendering a camera
  347. */
  348. public onBeforeCameraRenderObservable = new Observable<Camera>();
  349. private _onBeforeCameraRenderObserver: Nullable<Observer<Camera>> = null;
  350. /** Sets a function to be executed before rendering a camera*/
  351. public set beforeCameraRender(callback: () => void) {
  352. if (this._onBeforeCameraRenderObserver) {
  353. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  354. }
  355. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  356. }
  357. /**
  358. * An event triggered after rendering a camera
  359. */
  360. public onAfterCameraRenderObservable = new Observable<Camera>();
  361. private _onAfterCameraRenderObserver: Nullable<Observer<Camera>> = null;
  362. /** Sets a function to be executed after rendering a camera*/
  363. public set afterCameraRender(callback: () => void) {
  364. if (this._onAfterCameraRenderObserver) {
  365. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  366. }
  367. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  368. }
  369. /**
  370. * An event triggered when active meshes evaluation is about to start
  371. */
  372. public onBeforeActiveMeshesEvaluationObservable = new Observable<Scene>();
  373. /**
  374. * An event triggered when active meshes evaluation is done
  375. */
  376. public onAfterActiveMeshesEvaluationObservable = new Observable<Scene>();
  377. /**
  378. * An event triggered when particles rendering is about to start
  379. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  380. */
  381. public onBeforeParticlesRenderingObservable = new Observable<Scene>();
  382. /**
  383. * An event triggered when particles rendering is done
  384. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  385. */
  386. public onAfterParticlesRenderingObservable = new Observable<Scene>();
  387. /**
  388. * An event triggered when sprites rendering is about to start
  389. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  390. */
  391. public onBeforeSpritesRenderingObservable = new Observable<Scene>();
  392. /**
  393. * An event triggered when sprites rendering is done
  394. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  395. */
  396. public onAfterSpritesRenderingObservable = new Observable<Scene>();
  397. /**
  398. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  399. */
  400. public onDataLoadedObservable = new Observable<Scene>();
  401. /**
  402. * An event triggered when a camera is created
  403. */
  404. public onNewCameraAddedObservable = new Observable<Camera>();
  405. /**
  406. * An event triggered when a camera is removed
  407. */
  408. public onCameraRemovedObservable = new Observable<Camera>();
  409. /**
  410. * An event triggered when a light is created
  411. */
  412. public onNewLightAddedObservable = new Observable<Light>();
  413. /**
  414. * An event triggered when a light is removed
  415. */
  416. public onLightRemovedObservable = new Observable<Light>();
  417. /**
  418. * An event triggered when a geometry is created
  419. */
  420. public onNewGeometryAddedObservable = new Observable<Geometry>();
  421. /**
  422. * An event triggered when a geometry is removed
  423. */
  424. public onGeometryRemovedObservable = new Observable<Geometry>();
  425. /**
  426. * An event triggered when a transform node is created
  427. */
  428. public onNewTransformNodeAddedObservable = new Observable<TransformNode>();
  429. /**
  430. * An event triggered when a transform node is removed
  431. */
  432. public onTransformNodeRemovedObservable = new Observable<TransformNode>();
  433. /**
  434. * An event triggered when a mesh is created
  435. */
  436. public onNewMeshAddedObservable = new Observable<AbstractMesh>();
  437. /**
  438. * An event triggered when a mesh is removed
  439. */
  440. public onMeshRemovedObservable = new Observable<AbstractMesh>();
  441. /**
  442. * An event triggered when render targets are about to be rendered
  443. * Can happen multiple times per frame.
  444. */
  445. public onBeforeRenderTargetsRenderObservable = new Observable<Scene>();
  446. /**
  447. * An event triggered when render targets were rendered.
  448. * Can happen multiple times per frame.
  449. */
  450. public onAfterRenderTargetsRenderObservable = new Observable<Scene>();
  451. /**
  452. * An event triggered before calculating deterministic simulation step
  453. */
  454. public onBeforeStepObservable = new Observable<Scene>();
  455. /**
  456. * An event triggered after calculating deterministic simulation step
  457. */
  458. public onAfterStepObservable = new Observable<Scene>();
  459. /**
  460. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  461. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  462. * 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)
  463. */
  464. public onRenderingGroupObservable = new Observable<RenderingGroupInfo>();
  465. // Animations
  466. /**
  467. * Gets a list of Animations associated with the scene
  468. */
  469. public animations: Animation[] = [];
  470. private _registeredForLateAnimationBindings = new SmartArrayNoDuplicate<any>(256);
  471. // Pointers
  472. /**
  473. * Gets or sets a predicate used to select candidate meshes for a pointer down event
  474. */
  475. public pointerDownPredicate: (Mesh: AbstractMesh) => boolean;
  476. /**
  477. * Gets or sets a predicate used to select candidate meshes for a pointer up event
  478. */
  479. public pointerUpPredicate: (Mesh: AbstractMesh) => boolean;
  480. /**
  481. * Gets or sets a predicate used to select candidate meshes for a pointer move event
  482. */
  483. public pointerMovePredicate: (Mesh: AbstractMesh) => boolean;
  484. private _onPointerMove: (evt: PointerEvent) => void;
  485. private _onPointerDown: (evt: PointerEvent) => void;
  486. private _onPointerUp: (evt: PointerEvent) => void;
  487. /** Deprecated. Use onPointerObservable instead */
  488. public onPointerMove: (evt: PointerEvent, pickInfo: PickingInfo, type: PointerEventTypes) => void;
  489. /** Deprecated. Use onPointerObservable instead */
  490. public onPointerDown: (evt: PointerEvent, pickInfo: PickingInfo, type: PointerEventTypes) => void;
  491. /** Deprecated. Use onPointerObservable instead */
  492. public onPointerUp: (evt: PointerEvent, pickInfo: Nullable<PickingInfo>, type: PointerEventTypes) => void;
  493. /** Deprecated. Use onPointerObservable instead */
  494. public onPointerPick: (evt: PointerEvent, pickInfo: PickingInfo) => void;
  495. // Gamepads
  496. private _gamepadManager: Nullable<GamepadManager>;
  497. /**
  498. * Gets the gamepad manager associated with the scene
  499. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  500. */
  501. public get gamepadManager(): GamepadManager {
  502. if (!this._gamepadManager) {
  503. this._gamepadManager = new GamepadManager(this);
  504. }
  505. return this._gamepadManager;
  506. }
  507. /**
  508. * 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).
  509. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  510. */
  511. public onPrePointerObservable = new Observable<PointerInfoPre>();
  512. /**
  513. * Observable event triggered each time an input event is received from the rendering canvas
  514. */
  515. public onPointerObservable = new Observable<PointerInfo>();
  516. /**
  517. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  518. */
  519. public get unTranslatedPointer(): Vector2 {
  520. return new Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  521. }
  522. /** The distance in pixel that you have to move to prevent some events */
  523. public static DragMovementThreshold = 10; // in pixels
  524. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  525. public static LongPressDelay = 500; // in milliseconds
  526. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  527. public static DoubleClickDelay = 300; // in milliseconds
  528. /** If you need to check double click without raising a single click at first click, enable this flag */
  529. public static ExclusiveDoubleClickMode = false;
  530. private _initClickEvent: (obs1: Observable<PointerInfoPre>, obs2: Observable<PointerInfo>, evt: PointerEvent, cb: (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => void) => void;
  531. private _initActionManager: (act: Nullable<ActionManager>, clickInfo: ClickInfo) => Nullable<ActionManager>;
  532. private _delayedSimpleClick: (btn: number, clickInfo: ClickInfo, cb: (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => void) => void;
  533. private _delayedSimpleClickTimeout: number;
  534. private _previousDelayedSimpleClickTimeout: number;
  535. private _meshPickProceed = false;
  536. private _previousButtonPressed: number;
  537. private _currentPickResult: Nullable<PickingInfo> = null;
  538. private _previousPickResult: Nullable<PickingInfo> = null;
  539. private _totalPointersPressed = 0;
  540. private _doubleClickOccured = false;
  541. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  542. public cameraToUseForPointers: Nullable<Camera> = null;
  543. private _pointerX: number;
  544. private _pointerY: number;
  545. private _unTranslatedPointerX: number;
  546. private _unTranslatedPointerY: number;
  547. private _startingPointerPosition = new Vector2(0, 0);
  548. private _previousStartingPointerPosition = new Vector2(0, 0);
  549. private _startingPointerTime = 0;
  550. private _previousStartingPointerTime = 0;
  551. private _pointerCaptures: {[pointerId:number]: boolean} = {};
  552. // Deterministic lockstep
  553. private _timeAccumulator: number = 0;
  554. private _currentStepId: number = 0;
  555. private _currentInternalStep: number = 0;
  556. // Mirror
  557. /** @hidden */
  558. public _mirroredCameraPosition: Nullable<Vector3>;
  559. // Keyboard
  560. /**
  561. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  562. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  563. */
  564. public onPreKeyboardObservable = new Observable<KeyboardInfoPre>();
  565. /**
  566. * Observable event triggered each time an keyboard event is received from the hosting window
  567. */
  568. public onKeyboardObservable = new Observable<KeyboardInfo>();
  569. private _onKeyDown: (evt: KeyboardEvent) => void;
  570. private _onKeyUp: (evt: KeyboardEvent) => void;
  571. private _onCanvasFocusObserver: Nullable<Observer<Engine>>;
  572. private _onCanvasBlurObserver: Nullable<Observer<Engine>>;
  573. // Coordinates system
  574. private _useRightHandedSystem = false;
  575. /**
  576. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  577. */
  578. public set useRightHandedSystem(value: boolean) {
  579. if (this._useRightHandedSystem === value) {
  580. return;
  581. }
  582. this._useRightHandedSystem = value;
  583. this.markAllMaterialsAsDirty(Material.MiscDirtyFlag);
  584. }
  585. public get useRightHandedSystem(): boolean {
  586. return this._useRightHandedSystem;
  587. }
  588. /**
  589. * Sets the step Id used by deterministic lock step
  590. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  591. * @param newStepId defines the step Id
  592. */
  593. public setStepId(newStepId: number): void {
  594. this._currentStepId = newStepId;
  595. };
  596. /**
  597. * Gets the step Id used by deterministic lock step
  598. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  599. * @returns the step Id
  600. */
  601. public getStepId(): number {
  602. return this._currentStepId;
  603. };
  604. /**
  605. * Gets the internal step used by deterministic lock step
  606. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  607. * @returns the internal step
  608. */
  609. public getInternalStep(): number {
  610. return this._currentInternalStep;
  611. };
  612. // Fog
  613. private _fogEnabled = true;
  614. /**
  615. * Gets or sets a boolean indicating if fog is enabled on this scene
  616. * @see http://doc.babylonjs.com/babylon101/environment#fog
  617. */
  618. public set fogEnabled(value: boolean) {
  619. if (this._fogEnabled === value) {
  620. return;
  621. }
  622. this._fogEnabled = value;
  623. this.markAllMaterialsAsDirty(Material.MiscDirtyFlag);
  624. }
  625. public get fogEnabled(): boolean {
  626. return this._fogEnabled;
  627. }
  628. private _fogMode = Scene.FOGMODE_NONE;
  629. /**
  630. * Gets or sets the fog mode to use
  631. * @see http://doc.babylonjs.com/babylon101/environment#fog
  632. */
  633. public set fogMode(value: number) {
  634. if (this._fogMode === value) {
  635. return;
  636. }
  637. this._fogMode = value;
  638. this.markAllMaterialsAsDirty(Material.MiscDirtyFlag);
  639. }
  640. public get fogMode(): number {
  641. return this._fogMode;
  642. }
  643. /**
  644. * Gets or sets the fog color to use
  645. * @see http://doc.babylonjs.com/babylon101/environment#fog
  646. */
  647. public fogColor = new Color3(0.2, 0.2, 0.3);
  648. /**
  649. * Gets or sets the fog density to use
  650. * @see http://doc.babylonjs.com/babylon101/environment#fog
  651. */
  652. public fogDensity = 0.1;
  653. /**
  654. * Gets or sets the fog start distance to use
  655. * @see http://doc.babylonjs.com/babylon101/environment#fog
  656. */
  657. public fogStart = 0;
  658. /**
  659. * Gets or sets the fog end distance to use
  660. * @see http://doc.babylonjs.com/babylon101/environment#fog
  661. */
  662. public fogEnd = 1000.0;
  663. // Lights
  664. private _shadowsEnabled = true;
  665. /**
  666. * Gets or sets a boolean indicating if shadows are enabled on this scene
  667. */
  668. public set shadowsEnabled(value: boolean) {
  669. if (this._shadowsEnabled === value) {
  670. return;
  671. }
  672. this._shadowsEnabled = value;
  673. this.markAllMaterialsAsDirty(Material.LightDirtyFlag);
  674. }
  675. public get shadowsEnabled(): boolean {
  676. return this._shadowsEnabled;
  677. }
  678. private _lightsEnabled = true;
  679. /**
  680. * Gets or sets a boolean indicating if lights are enabled on this scene
  681. */
  682. public set lightsEnabled(value: boolean) {
  683. if (this._lightsEnabled === value) {
  684. return;
  685. }
  686. this._lightsEnabled = value;
  687. this.markAllMaterialsAsDirty(Material.LightDirtyFlag);
  688. }
  689. public get lightsEnabled(): boolean {
  690. return this._lightsEnabled;
  691. }
  692. /**
  693. * All of the lights added to this scene
  694. * @see http://doc.babylonjs.com/babylon101/lights
  695. */
  696. public lights = new Array<Light>();
  697. // Cameras
  698. /** All of the cameras added to this scene.
  699. * @see http://doc.babylonjs.com/babylon101/cameras
  700. */
  701. public cameras = new Array<Camera>();
  702. /** All of the active cameras added to this scene. */
  703. public activeCameras = new Array<Camera>();
  704. /** The current active camera */
  705. public activeCamera: Nullable<Camera>;
  706. // Meshes
  707. /**
  708. * All of the tranform nodes added to this scene
  709. * @see http://doc.babylonjs.com/how_to/transformnode
  710. */
  711. public transformNodes = new Array<TransformNode>();
  712. /**
  713. * All of the (abstract) meshes added to this scene
  714. */
  715. public meshes = new Array<AbstractMesh>();
  716. /**
  717. * All of the animation groups added to this scene
  718. * @see http://doc.babylonjs.com/how_to/group
  719. */
  720. public animationGroups = new Array<AnimationGroup>();
  721. // Geometries
  722. private _geometries = new Array<Geometry>();
  723. /**
  724. * All of the materials added to this scene
  725. * @see http://doc.babylonjs.com/babylon101/materials
  726. */
  727. public materials = new Array<Material>();
  728. /**
  729. * All of the multi-materials added to this scene
  730. * @see http://doc.babylonjs.com/how_to/multi_materials
  731. */
  732. public multiMaterials = new Array<MultiMaterial>();
  733. private _defaultMaterial: Material;
  734. /** The default material used on meshes when no material is affected */
  735. public get defaultMaterial(): Material {
  736. if (!this._defaultMaterial) {
  737. this._defaultMaterial = new StandardMaterial("default material", this);
  738. }
  739. return this._defaultMaterial;
  740. }
  741. /** The default material used on meshes when no material is affected */
  742. public set defaultMaterial(value: Material) {
  743. this._defaultMaterial = value;
  744. }
  745. // Textures
  746. private _texturesEnabled = true;
  747. /**
  748. * Gets or sets a boolean indicating if textures are enabled on this scene
  749. */
  750. public set texturesEnabled(value: boolean) {
  751. if (this._texturesEnabled === value) {
  752. return;
  753. }
  754. this._texturesEnabled = value;
  755. this.markAllMaterialsAsDirty(Material.TextureDirtyFlag);
  756. }
  757. public get texturesEnabled(): boolean {
  758. return this._texturesEnabled;
  759. }
  760. /**
  761. * All of the textures added to this scene
  762. */
  763. public textures = new Array<BaseTexture>();
  764. // Particles
  765. /**
  766. * Gets or sets a boolean indicating if particles are enabled on this scene
  767. */
  768. public particlesEnabled = true;
  769. /**
  770. * All of the particle systems added to this scene
  771. * @see http://doc.babylonjs.com/babylon101/particles
  772. */
  773. public particleSystems = new Array<IParticleSystem>();
  774. // Sprites
  775. /**
  776. * Gets or sets a boolean indicating if sprites are enabled on this scene
  777. */
  778. public spritesEnabled = true;
  779. /**
  780. * All of the sprite managers added to this scene
  781. * @see http://doc.babylonjs.com/babylon101/sprites
  782. */
  783. public spriteManagers = new Array<SpriteManager>();
  784. /**
  785. * The list of layers (background and foreground) of the scene
  786. */
  787. public layers = new Array<Layer>();
  788. /**
  789. * The list of effect layers (highlights/glow) added to the scene
  790. * @see http://doc.babylonjs.com/how_to/highlight_layer
  791. * @see http://doc.babylonjs.com/how_to/glow_layer
  792. */
  793. public effectLayers = new Array<EffectLayer>();
  794. // Skeletons
  795. private _skeletonsEnabled = true;
  796. /**
  797. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  798. */
  799. public set skeletonsEnabled(value: boolean) {
  800. if (this._skeletonsEnabled === value) {
  801. return;
  802. }
  803. this._skeletonsEnabled = value;
  804. this.markAllMaterialsAsDirty(Material.AttributesDirtyFlag);
  805. }
  806. public get skeletonsEnabled(): boolean {
  807. return this._skeletonsEnabled;
  808. }
  809. /**
  810. * The list of skeletons added to the scene
  811. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  812. */
  813. public skeletons = new Array<Skeleton>();
  814. // Morph targets
  815. /**
  816. * The list of morph target managers added to the scene
  817. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  818. */
  819. public morphTargetManagers = new Array<MorphTargetManager>();
  820. // Lens flares
  821. /**
  822. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  823. */
  824. public lensFlaresEnabled = true;
  825. /**
  826. * The list of lens flare system added to the scene
  827. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  828. */
  829. public lensFlareSystems = new Array<LensFlareSystem>();
  830. // Collisions
  831. /**
  832. * Gets or sets a boolean indicating if collisions are enabled on this scene
  833. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  834. */
  835. public collisionsEnabled = true;
  836. private _workerCollisions: boolean;
  837. /** @hidden */
  838. public collisionCoordinator: ICollisionCoordinator;
  839. /**
  840. * Defines the gravity applied to this scene (used only for collisions)
  841. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  842. */
  843. public gravity = new Vector3(0, -9.807, 0);
  844. // Postprocesses
  845. /**
  846. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  847. */
  848. public postProcessesEnabled = true;
  849. /**
  850. * The list of postprocesses added to the scene
  851. */
  852. public postProcesses = new Array<PostProcess>();
  853. /**
  854. * Gets the current postprocess manager
  855. */
  856. public postProcessManager: PostProcessManager;
  857. private _postProcessRenderPipelineManager: PostProcessRenderPipelineManager
  858. /**
  859. * Gets the postprocess render pipeline manager
  860. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  861. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  862. */
  863. public get postProcessRenderPipelineManager(): PostProcessRenderPipelineManager {
  864. if (!this._postProcessRenderPipelineManager) {
  865. this._postProcessRenderPipelineManager = new PostProcessRenderPipelineManager();
  866. }
  867. return this._postProcessRenderPipelineManager;
  868. }
  869. // Customs render targets
  870. /**
  871. * Gets or sets a boolean indicating if render targets are enabled on this scene
  872. */
  873. public renderTargetsEnabled = true;
  874. /**
  875. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  876. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  877. */
  878. public dumpNextRenderTargets = false;
  879. /**
  880. * The list of user defined render targets added to the scene
  881. */
  882. public customRenderTargets = new Array<RenderTargetTexture>();
  883. /**
  884. * Defines if texture loading must be delayed
  885. * If true, textures will only be loaded when they need to be rendered
  886. */
  887. public useDelayedTextureLoading: boolean;
  888. /**
  889. * Gets the list of meshes imported to the scene through SceneLoader
  890. */
  891. public importedMeshesFiles = new Array<String>();
  892. // Probes
  893. /**
  894. * Gets or sets a boolean indicating if probes are enabled on this scene
  895. */
  896. public probesEnabled = true;
  897. /**
  898. * The list of reflection probes added to the scene
  899. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  900. */
  901. public reflectionProbes = new Array<ReflectionProbe>();
  902. // Database
  903. /**
  904. * @hidden
  905. */
  906. public database: Database;
  907. /**
  908. * Gets or sets the action manager associated with the scene
  909. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  910. */
  911. public actionManager: ActionManager;
  912. /** @hidden */
  913. public _actionManagers = new Array<ActionManager>();
  914. private _meshesForIntersections = new SmartArrayNoDuplicate<AbstractMesh>(256);
  915. // Procedural textures
  916. /**
  917. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  918. */
  919. public proceduralTexturesEnabled = true;
  920. /**
  921. * The list of procedural textures added to the scene
  922. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  923. */
  924. public proceduralTextures = new Array<ProceduralTexture>();
  925. // Sound Tracks
  926. private _mainSoundTrack: SoundTrack;
  927. /**
  928. * The list of sound tracks added to the scene
  929. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  930. */
  931. public soundTracks = new Array<SoundTrack>();
  932. private _audioEnabled = true;
  933. private _headphone = false;
  934. /**
  935. * Gets the main soundtrack associated with the scene
  936. */
  937. public get mainSoundTrack(): SoundTrack {
  938. if (!this._mainSoundTrack) {
  939. this._mainSoundTrack = new SoundTrack(this, { mainTrack: true });
  940. }
  941. return this._mainSoundTrack;
  942. }
  943. /**
  944. * Gets or sets the VRExperienceHelper attached to the scene
  945. * @see http://doc.babylonjs.com/how_to/webvr_helper
  946. * @ignorenaming
  947. */
  948. public VRHelper: VRExperienceHelper;
  949. /**
  950. * Gets or sets the simplification queue attached to the scene
  951. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  952. */
  953. public simplificationQueue: SimplificationQueue;
  954. // Private
  955. private _engine: Engine;
  956. // Performance counters
  957. private _totalVertices = new PerfCounter();
  958. /** @hidden */
  959. public _activeIndices = new PerfCounter();
  960. /** @hidden */
  961. public _activeParticles = new PerfCounter();
  962. /** @hidden */
  963. public _activeBones = new PerfCounter();
  964. private _animationRatio: number;
  965. private _animationTimeLast: number;
  966. private _animationTime: number = 0;
  967. /**
  968. * Gets or sets a general scale for animation speed
  969. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  970. */
  971. public animationTimeScale: number = 1;
  972. /** @hidden */
  973. public _cachedMaterial: Nullable<Material>;
  974. /** @hidden */
  975. public _cachedEffect: Nullable<Effect>;
  976. /** @hidden */
  977. public _cachedVisibility: Nullable<number>;
  978. private _renderId = 0;
  979. private _executeWhenReadyTimeoutId = -1;
  980. private _intermediateRendering = false;
  981. private _viewUpdateFlag = -1;
  982. private _projectionUpdateFlag = -1;
  983. private _alternateViewUpdateFlag = -1;
  984. private _alternateProjectionUpdateFlag = -1;
  985. /** @hidden */
  986. public _toBeDisposed = new SmartArray<Nullable<IDisposable>>(256);
  987. private _activeRequests = new Array<IFileRequest>();
  988. private _pendingData = new Array();
  989. private _isDisposed = false;
  990. /**
  991. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  992. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  993. */
  994. public dispatchAllSubMeshesOfActiveMeshes: boolean = false;
  995. private _activeMeshes = new SmartArray<AbstractMesh>(256);
  996. private _processedMaterials = new SmartArray<Material>(256);
  997. private _renderTargets = new SmartArrayNoDuplicate<RenderTargetTexture>(256);
  998. /** @hidden */
  999. public _activeParticleSystems = new SmartArray<IParticleSystem>(256);
  1000. private _activeSkeletons = new SmartArrayNoDuplicate<Skeleton>(32);
  1001. private _softwareSkinnedMeshes = new SmartArrayNoDuplicate<Mesh>(32);
  1002. private _renderingManager: RenderingManager;
  1003. private _physicsEngine: Nullable<PhysicsEngine>;
  1004. /** @hidden */
  1005. public _activeAnimatables = new Array<Animatable>();
  1006. private _transformMatrix = Matrix.Zero();
  1007. private _sceneUbo: UniformBuffer;
  1008. private _alternateSceneUbo: UniformBuffer;
  1009. private _pickWithRayInverseMatrix: Matrix;
  1010. private _boundingBoxRenderer: BoundingBoxRenderer;
  1011. private _outlineRenderer: OutlineRenderer;
  1012. private _viewMatrix: Matrix;
  1013. private _projectionMatrix: Matrix;
  1014. private _alternateViewMatrix: Matrix;
  1015. private _alternateProjectionMatrix: Matrix;
  1016. private _alternateTransformMatrix: Matrix;
  1017. private _useAlternateCameraConfiguration = false;
  1018. private _alternateRendering = false;
  1019. /** @hidden */
  1020. public _forcedViewPosition: Nullable<Vector3>;
  1021. /** @hidden */
  1022. public get _isAlternateRenderingEnabled(): boolean {
  1023. return this._alternateRendering;
  1024. }
  1025. private _frustumPlanes: Plane[];
  1026. /**
  1027. * Gets the list of frustum planes (built from the active camera)
  1028. */
  1029. public get frustumPlanes(): Plane[] {
  1030. return this._frustumPlanes;
  1031. }
  1032. /**
  1033. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  1034. * This is useful if there are more lights that the maximum simulteanous authorized
  1035. */
  1036. public requireLightSorting = false;
  1037. private _selectionOctree: Octree<AbstractMesh>;
  1038. private _pointerOverMesh: Nullable<AbstractMesh>;
  1039. private _pointerOverSprite: Nullable<Sprite>;
  1040. private _debugLayer: DebugLayer;
  1041. private _depthRenderer: { [id: string]: DepthRenderer } = {};
  1042. private _geometryBufferRenderer: Nullable<GeometryBufferRenderer>;
  1043. /**
  1044. * Gets the current geometry buffer associated to the scene.
  1045. */
  1046. public get geometryBufferRenderer(): Nullable<GeometryBufferRenderer> {
  1047. return this._geometryBufferRenderer;
  1048. }
  1049. /**
  1050. * Sets the current geometry buffer for the scene.
  1051. */
  1052. public set geometryBufferRenderer(geometryBufferRenderer: Nullable<GeometryBufferRenderer>) {
  1053. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  1054. this._geometryBufferRenderer = geometryBufferRenderer;
  1055. }
  1056. }
  1057. private _pickedDownMesh: Nullable<AbstractMesh>;
  1058. private _pickedUpMesh: Nullable<AbstractMesh>;
  1059. private _pickedDownSprite: Nullable<Sprite>;
  1060. private _externalData: StringDictionary<Object>;
  1061. private _uid: Nullable<string>;
  1062. /**
  1063. * Creates a new Scene
  1064. * @param engine defines the engine to use to render this scene
  1065. */
  1066. constructor(engine: Engine) {
  1067. this._engine = engine || Engine.LastCreatedEngine;
  1068. this._engine.scenes.push(this);
  1069. this._uid = null;
  1070. this._renderingManager = new RenderingManager(this);
  1071. if (PostProcessManager) {
  1072. this.postProcessManager = new PostProcessManager(this);
  1073. }
  1074. if (OutlineRenderer) {
  1075. this._outlineRenderer = new OutlineRenderer(this);
  1076. }
  1077. if (Tools.IsWindowObjectExist()) {
  1078. this.attachControl();
  1079. }
  1080. //simplification queue
  1081. if (SimplificationQueue) {
  1082. this.simplificationQueue = new SimplificationQueue();
  1083. }
  1084. //collision coordinator initialization. For now legacy per default.
  1085. this.workerCollisions = false;//(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  1086. // Uniform Buffer
  1087. this._createUbo();
  1088. // Default Image processing definition
  1089. if (ImageProcessingConfiguration) {
  1090. this._imageProcessingConfiguration = new ImageProcessingConfiguration();
  1091. }
  1092. }
  1093. /**
  1094. * Gets the debug layer (aka Inspector) associated with the scene
  1095. * @see http://doc.babylonjs.com/features/playground_debuglayer
  1096. */
  1097. public get debugLayer(): DebugLayer {
  1098. if (!this._debugLayer) {
  1099. this._debugLayer = new DebugLayer(this);
  1100. }
  1101. return this._debugLayer;
  1102. }
  1103. public set workerCollisions(enabled: boolean) {
  1104. if (!CollisionCoordinatorLegacy) {
  1105. return;
  1106. }
  1107. enabled = (enabled && !!Worker && !!CollisionWorker);
  1108. this._workerCollisions = enabled;
  1109. if (this.collisionCoordinator) {
  1110. this.collisionCoordinator.destroy();
  1111. }
  1112. this.collisionCoordinator = enabled ? new CollisionCoordinatorWorker() : new CollisionCoordinatorLegacy();
  1113. this.collisionCoordinator.init(this);
  1114. }
  1115. /**
  1116. * Gets a boolean indicating if collisions are processed on a web worker
  1117. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  1118. */
  1119. public get workerCollisions(): boolean {
  1120. return this._workerCollisions;
  1121. }
  1122. /**
  1123. * Gets the octree used to boost mesh selection (picking)
  1124. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  1125. */
  1126. public get selectionOctree(): Octree<AbstractMesh> {
  1127. return this._selectionOctree;
  1128. }
  1129. /**
  1130. * Gets the mesh that is currently under the pointer
  1131. */
  1132. public get meshUnderPointer(): Nullable<AbstractMesh> {
  1133. return this._pointerOverMesh;
  1134. }
  1135. /**
  1136. * Gets the current on-screen X position of the pointer
  1137. */
  1138. public get pointerX(): number {
  1139. return this._pointerX;
  1140. }
  1141. /**
  1142. * Gets the current on-screen Y position of the pointer
  1143. */
  1144. public get pointerY(): number {
  1145. return this._pointerY;
  1146. }
  1147. /**
  1148. * Gets the cached material (ie. the latest rendered one)
  1149. * @returns the cached material
  1150. */
  1151. public getCachedMaterial(): Nullable<Material> {
  1152. return this._cachedMaterial;
  1153. }
  1154. /**
  1155. * Gets the cached effect (ie. the latest rendered one)
  1156. * @returns the cached effect
  1157. */
  1158. public getCachedEffect(): Nullable<Effect> {
  1159. return this._cachedEffect;
  1160. }
  1161. /**
  1162. * Gets the cached visibility state (ie. the latest rendered one)
  1163. * @returns the cached visibility state
  1164. */
  1165. public getCachedVisibility(): Nullable<number> {
  1166. return this._cachedVisibility;
  1167. }
  1168. /**
  1169. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  1170. * @param material defines the current material
  1171. * @param effect defines the current effect
  1172. * @param visibility defines the current visibility state
  1173. * @returns true if one parameter is not cached
  1174. */
  1175. public isCachedMaterialInvalid(material: Material, effect: Effect, visibility: number = 1) {
  1176. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  1177. }
  1178. /**
  1179. * Gets the bounding box renderer associated with the scene
  1180. * @returns a BoundingBoxRenderer
  1181. */
  1182. public getBoundingBoxRenderer(): BoundingBoxRenderer {
  1183. if (!this._boundingBoxRenderer) {
  1184. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  1185. }
  1186. return this._boundingBoxRenderer;
  1187. }
  1188. /**
  1189. * Gets the outline renderer associated with the scene
  1190. * @returns a OutlineRenderer
  1191. */
  1192. public getOutlineRenderer(): OutlineRenderer {
  1193. return this._outlineRenderer;
  1194. }
  1195. /**
  1196. * Gets the engine associated with the scene
  1197. * @returns an Engine
  1198. */
  1199. public getEngine(): Engine {
  1200. return this._engine;
  1201. }
  1202. /**
  1203. * Gets the total number of vertices rendered per frame
  1204. * @returns the total number of vertices rendered per frame
  1205. */
  1206. public getTotalVertices(): number {
  1207. return this._totalVertices.current;
  1208. }
  1209. /**
  1210. * Gets the performance counter for total vertices
  1211. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  1212. */
  1213. public get totalVerticesPerfCounter(): PerfCounter {
  1214. return this._totalVertices;
  1215. }
  1216. /**
  1217. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  1218. * @returns the total number of active indices rendered per frame
  1219. */
  1220. public getActiveIndices(): number {
  1221. return this._activeIndices.current;
  1222. }
  1223. /**
  1224. * Gets the performance counter for active indices
  1225. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  1226. */
  1227. public get totalActiveIndicesPerfCounter(): PerfCounter {
  1228. return this._activeIndices;
  1229. }
  1230. /**
  1231. * Gets the total number of active particles rendered per frame
  1232. * @returns the total number of active particles rendered per frame
  1233. */
  1234. public getActiveParticles(): number {
  1235. return this._activeParticles.current;
  1236. }
  1237. /**
  1238. * Gets the performance counter for active particles
  1239. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  1240. */
  1241. public get activeParticlesPerfCounter(): PerfCounter {
  1242. return this._activeParticles;
  1243. }
  1244. /**
  1245. * Gets the total number of active bones rendered per frame
  1246. * @returns the total number of active bones rendered per frame
  1247. */
  1248. public getActiveBones(): number {
  1249. return this._activeBones.current;
  1250. }
  1251. /**
  1252. * Gets the performance counter for active bones
  1253. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  1254. */
  1255. public get activeBonesPerfCounter(): PerfCounter {
  1256. return this._activeBones;
  1257. }
  1258. /** @hidden */
  1259. public getInterFramePerfCounter(): number {
  1260. Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  1261. return 0;
  1262. }
  1263. /** @hidden */
  1264. public get interFramePerfCounter(): Nullable<PerfCounter> {
  1265. Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  1266. return null;
  1267. }
  1268. /** @hidden */
  1269. public getLastFrameDuration(): number {
  1270. Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  1271. return 0;
  1272. }
  1273. /** @hidden */
  1274. public get lastFramePerfCounter(): Nullable<PerfCounter> {
  1275. Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  1276. return null;
  1277. }
  1278. /** @hidden */
  1279. public getEvaluateActiveMeshesDuration(): number {
  1280. Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  1281. return 0;
  1282. }
  1283. /** @hidden */
  1284. public get evaluateActiveMeshesDurationPerfCounter(): Nullable<PerfCounter> {
  1285. Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  1286. return null;
  1287. }
  1288. /**
  1289. * Gets the array of active meshes
  1290. * @returns an array of AbstractMesh
  1291. */
  1292. public getActiveMeshes(): SmartArray<AbstractMesh> {
  1293. return this._activeMeshes;
  1294. }
  1295. /** @hidden */
  1296. public getRenderTargetsDuration(): number {
  1297. Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  1298. return 0;
  1299. }
  1300. /** @hidden */
  1301. public getRenderDuration(): number {
  1302. Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  1303. return 0;
  1304. }
  1305. /** @hidden */
  1306. public get renderDurationPerfCounter(): Nullable<PerfCounter> {
  1307. Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  1308. return null;
  1309. }
  1310. /** @hidden */
  1311. public getParticlesDuration(): number {
  1312. Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  1313. return 0;
  1314. }
  1315. /** @hidden */
  1316. public get particlesDurationPerfCounter(): Nullable<PerfCounter> {
  1317. Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  1318. return null;
  1319. }
  1320. /** @hidden */
  1321. public getSpritesDuration(): number {
  1322. Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  1323. return 0;
  1324. }
  1325. /** @hidden */
  1326. public get spriteDuractionPerfCounter(): Nullable<PerfCounter> {
  1327. Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  1328. return null;
  1329. }
  1330. /**
  1331. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  1332. * @returns a number
  1333. */
  1334. public getAnimationRatio(): number {
  1335. return this._animationRatio;
  1336. }
  1337. /**
  1338. * Gets an unique Id for the current frame
  1339. * @returns a number
  1340. */
  1341. public getRenderId(): number {
  1342. return this._renderId;
  1343. }
  1344. /** Call this function if you want to manually increment the render Id*/
  1345. public incrementRenderId(): void {
  1346. this._renderId++;
  1347. }
  1348. private _updatePointerPosition(evt: PointerEvent): void {
  1349. var canvasRect = this._engine.getRenderingCanvasClientRect();
  1350. if (!canvasRect) {
  1351. return;
  1352. }
  1353. this._pointerX = evt.clientX - canvasRect.left;
  1354. this._pointerY = evt.clientY - canvasRect.top;
  1355. this._unTranslatedPointerX = this._pointerX;
  1356. this._unTranslatedPointerY = this._pointerY;
  1357. }
  1358. private _createUbo(): void {
  1359. this._sceneUbo = new UniformBuffer(this._engine, undefined, true);
  1360. this._sceneUbo.addUniform("viewProjection", 16);
  1361. this._sceneUbo.addUniform("view", 16);
  1362. }
  1363. private _createAlternateUbo(): void {
  1364. this._alternateSceneUbo = new UniformBuffer(this._engine, undefined, true);
  1365. this._alternateSceneUbo.addUniform("viewProjection", 16);
  1366. this._alternateSceneUbo.addUniform("view", 16);
  1367. }
  1368. // Pointers handling
  1369. private _pickSpriteButKeepRay(originalPointerInfo:Nullable<PickingInfo>, x: number, y: number, predicate?: (sprite: Sprite) => boolean, fastCheck?: boolean, camera?: Camera): Nullable<PickingInfo>{
  1370. var result = this.pickSprite(x,y,predicate,fastCheck,camera);
  1371. if(result){
  1372. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  1373. }
  1374. return result;
  1375. }
  1376. private _setRayOnPointerInfo(pointerInfo:PointerInfo){
  1377. if(pointerInfo.pickInfo){
  1378. if(!pointerInfo.pickInfo.ray){
  1379. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, Matrix.Identity(), this.activeCamera);
  1380. }
  1381. }
  1382. }
  1383. /**
  1384. * Use this method to simulate a pointer move on a mesh
  1385. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  1386. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  1387. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  1388. * @returns the current scene
  1389. */
  1390. public simulatePointerMove(pickResult: PickingInfo, pointerEventInit?: PointerEventInit): Scene {
  1391. let evt = new PointerEvent("pointermove", pointerEventInit);
  1392. if(this._checkPrePointerObservable(pickResult, evt, PointerEventTypes.POINTERMOVE)){
  1393. return this;
  1394. }
  1395. return this._processPointerMove(pickResult, evt);
  1396. }
  1397. private _processPointerMove(pickResult: Nullable<PickingInfo>, evt: PointerEvent): Scene {
  1398. var canvas = this._engine.getRenderingCanvas();
  1399. if (!canvas) {
  1400. return this;
  1401. }
  1402. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  1403. this.setPointerOverSprite(null);
  1404. this.setPointerOverMesh(pickResult.pickedMesh);
  1405. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  1406. if (this._pointerOverMesh.actionManager.hoverCursor) {
  1407. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  1408. } else {
  1409. canvas.style.cursor = this.hoverCursor;
  1410. }
  1411. } else {
  1412. canvas.style.cursor = this.defaultCursor;
  1413. }
  1414. } else {
  1415. this.setPointerOverMesh(null);
  1416. // Sprites
  1417. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  1418. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  1419. this.setPointerOverSprite(pickResult.pickedSprite);
  1420. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  1421. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  1422. } else {
  1423. canvas.style.cursor = this.hoverCursor;
  1424. }
  1425. } else {
  1426. this.setPointerOverSprite(null);
  1427. // Restore pointer
  1428. canvas.style.cursor = this.defaultCursor;
  1429. }
  1430. }
  1431. if (pickResult) {
  1432. let type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  1433. if (this.onPointerMove) {
  1434. this.onPointerMove(evt, pickResult, type);
  1435. }
  1436. if (this.onPointerObservable.hasObservers()) {
  1437. let pi = new PointerInfo(type, evt, pickResult);
  1438. this._setRayOnPointerInfo(pi);
  1439. this.onPointerObservable.notifyObservers(pi, type);
  1440. }
  1441. }
  1442. return this;
  1443. }
  1444. private _checkPrePointerObservable(pickResult: Nullable<PickingInfo>, evt: PointerEvent, type: number){
  1445. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1446. if(pickResult){
  1447. pi.ray = pickResult.ray;
  1448. }
  1449. this.onPrePointerObservable.notifyObservers(pi, type);
  1450. if (pi.skipOnPointerObservable) {
  1451. return true;
  1452. }else{
  1453. return false;
  1454. }
  1455. }
  1456. /**
  1457. * Use this method to simulate a pointer down on a mesh
  1458. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  1459. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  1460. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  1461. * @returns the current scene
  1462. */
  1463. public simulatePointerDown(pickResult: PickingInfo, pointerEventInit?: PointerEventInit): Scene {
  1464. let evt = new PointerEvent("pointerdown", pointerEventInit);
  1465. if(this._checkPrePointerObservable(pickResult, evt, PointerEventTypes.POINTERDOWN)){
  1466. return this;
  1467. }
  1468. return this._processPointerDown(pickResult, evt);
  1469. }
  1470. private _processPointerDown(pickResult: Nullable<PickingInfo>, evt: PointerEvent): Scene {
  1471. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  1472. this._pickedDownMesh = pickResult.pickedMesh;
  1473. var actionManager = pickResult.pickedMesh.actionManager;
  1474. if (actionManager) {
  1475. if (actionManager.hasPickTriggers) {
  1476. actionManager.processTrigger(ActionManager.OnPickDownTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1477. switch (evt.button) {
  1478. case 0:
  1479. actionManager.processTrigger(ActionManager.OnLeftPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1480. break;
  1481. case 1:
  1482. actionManager.processTrigger(ActionManager.OnCenterPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1483. break;
  1484. case 2:
  1485. actionManager.processTrigger(ActionManager.OnRightPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1486. break;
  1487. }
  1488. }
  1489. if (actionManager.hasSpecificTrigger(ActionManager.OnLongPressTrigger)) {
  1490. window.setTimeout(() => {
  1491. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY,
  1492. (mesh: AbstractMesh): boolean => (<boolean>(mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(ActionManager.OnLongPressTrigger) && mesh == this._pickedDownMesh)),
  1493. false, this.cameraToUseForPointers);
  1494. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  1495. if (this._totalPointersPressed !== 0 &&
  1496. ((Date.now() - this._startingPointerTime) > Scene.LongPressDelay) &&
  1497. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  1498. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  1499. this._startingPointerTime = 0;
  1500. actionManager.processTrigger(ActionManager.OnLongPressTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1501. }
  1502. }
  1503. }, Scene.LongPressDelay);
  1504. }
  1505. }
  1506. }
  1507. if (pickResult) {
  1508. let type = PointerEventTypes.POINTERDOWN;
  1509. if (this.onPointerDown) {
  1510. this.onPointerDown(evt, pickResult, type);
  1511. }
  1512. if (this.onPointerObservable.hasObservers()) {
  1513. let pi = new PointerInfo(type, evt, pickResult);
  1514. this._setRayOnPointerInfo(pi);
  1515. this.onPointerObservable.notifyObservers(pi, type);
  1516. }
  1517. }
  1518. return this;
  1519. }
  1520. /**
  1521. * Use this method to simulate a pointer up on a mesh
  1522. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  1523. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  1524. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  1525. * @returns the current scene
  1526. */
  1527. public simulatePointerUp(pickResult: PickingInfo, pointerEventInit?: PointerEventInit): Scene {
  1528. let evt = new PointerEvent("pointerup", pointerEventInit);
  1529. let clickInfo = new ClickInfo();
  1530. clickInfo.singleClick = true;
  1531. clickInfo.ignore = true;
  1532. if(this._checkPrePointerObservable(pickResult, evt, PointerEventTypes.POINTERUP)){
  1533. return this;
  1534. }
  1535. return this._processPointerUp(pickResult, evt, clickInfo);
  1536. }
  1537. private _processPointerUp(pickResult: Nullable<PickingInfo>, evt: PointerEvent, clickInfo: ClickInfo): Scene {
  1538. if (pickResult && pickResult && pickResult.pickedMesh) {
  1539. this._pickedUpMesh = pickResult.pickedMesh;
  1540. if (this._pickedDownMesh === this._pickedUpMesh) {
  1541. if (this.onPointerPick) {
  1542. this.onPointerPick(evt, pickResult);
  1543. }
  1544. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  1545. let type = PointerEventTypes.POINTERPICK;
  1546. let pi = new PointerInfo(type, evt, pickResult);
  1547. this._setRayOnPointerInfo(pi);
  1548. this.onPointerObservable.notifyObservers(pi, type);
  1549. }
  1550. }
  1551. if (pickResult.pickedMesh.actionManager) {
  1552. if (clickInfo.ignore) {
  1553. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnPickUpTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1554. }
  1555. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  1556. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1557. }
  1558. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(ActionManager.OnDoublePickTrigger)) {
  1559. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnDoublePickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1560. }
  1561. }
  1562. }
  1563. if (this._pickedDownMesh &&
  1564. this._pickedDownMesh.actionManager &&
  1565. this._pickedDownMesh.actionManager.hasSpecificTrigger(ActionManager.OnPickOutTrigger) &&
  1566. this._pickedDownMesh !== this._pickedUpMesh) {
  1567. this._pickedDownMesh.actionManager.processTrigger(ActionManager.OnPickOutTrigger, ActionEvent.CreateNew(this._pickedDownMesh, evt));
  1568. }
  1569. let type = PointerEventTypes.POINTERUP;
  1570. if (this.onPointerObservable.hasObservers()) {
  1571. if (!clickInfo.ignore) {
  1572. if (!clickInfo.hasSwiped) {
  1573. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  1574. let type = PointerEventTypes.POINTERTAP;
  1575. let pi = new PointerInfo(type, evt, pickResult);
  1576. this._setRayOnPointerInfo(pi);
  1577. this.onPointerObservable.notifyObservers(pi, type);
  1578. }
  1579. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  1580. let type = PointerEventTypes.POINTERDOUBLETAP;
  1581. let pi = new PointerInfo(type, evt, pickResult);
  1582. this._setRayOnPointerInfo(pi);
  1583. this.onPointerObservable.notifyObservers(pi, type);
  1584. }
  1585. }
  1586. }
  1587. else {
  1588. let pi = new PointerInfo(type, evt, pickResult);
  1589. this._setRayOnPointerInfo(pi);
  1590. this.onPointerObservable.notifyObservers(pi, type);
  1591. }
  1592. }
  1593. if (this.onPointerUp) {
  1594. this.onPointerUp(evt, pickResult, type);
  1595. }
  1596. return this;
  1597. }
  1598. /**
  1599. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  1600. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  1601. * @returns true if the pointer was captured
  1602. */
  1603. public isPointerCaptured(pointerId = 0): boolean {
  1604. return this._pointerCaptures[pointerId];
  1605. }
  1606. /**
  1607. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  1608. * @param attachUp defines if you want to attach events to pointerup
  1609. * @param attachDown defines if you want to attach events to pointerdown
  1610. * @param attachMove defines if you want to attach events to pointermove
  1611. */
  1612. public attachControl(attachUp = true, attachDown = true, attachMove = true): void {
  1613. this._initActionManager = (act: Nullable<ActionManager>, clickInfo: ClickInfo): Nullable<ActionManager> => {
  1614. if (!this._meshPickProceed) {
  1615. let pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, this.pointerDownPredicate, false, this.cameraToUseForPointers);
  1616. this._currentPickResult = pickResult;
  1617. if (pickResult) {
  1618. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  1619. }
  1620. this._meshPickProceed = true;
  1621. }
  1622. return act;
  1623. };
  1624. this._delayedSimpleClick = (btn: number, clickInfo: ClickInfo, cb: (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => void) => {
  1625. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  1626. if ((Date.now() - this._previousStartingPointerTime > Scene.DoubleClickDelay && !this._doubleClickOccured) ||
  1627. btn !== this._previousButtonPressed) {
  1628. this._doubleClickOccured = false;
  1629. clickInfo.singleClick = true;
  1630. clickInfo.ignore = false;
  1631. cb(clickInfo, this._currentPickResult);
  1632. }
  1633. }
  1634. this._initClickEvent = (obs1: Observable<PointerInfoPre>, obs2: Observable<PointerInfo>, evt: PointerEvent, cb: (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => void): void => {
  1635. let clickInfo = new ClickInfo();
  1636. this._currentPickResult = null;
  1637. let act: Nullable<ActionManager> = null;
  1638. let checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  1639. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  1640. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  1641. if (!checkPicking && ActionManager && ActionManager.HasPickTriggers) {
  1642. act = this._initActionManager(act, clickInfo);
  1643. if (act)
  1644. checkPicking = act.hasPickTriggers;
  1645. }
  1646. if (checkPicking) {
  1647. let btn = evt.button;
  1648. clickInfo.hasSwiped = Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  1649. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  1650. if (!clickInfo.hasSwiped) {
  1651. let checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  1652. if (!checkSingleClickImmediately) {
  1653. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  1654. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  1655. if (checkSingleClickImmediately && !ActionManager.HasSpecificTrigger(ActionManager.OnDoublePickTrigger)) {
  1656. act = this._initActionManager(act, clickInfo);
  1657. if (act)
  1658. checkSingleClickImmediately = !act.hasSpecificTrigger(ActionManager.OnDoublePickTrigger);
  1659. }
  1660. }
  1661. if (checkSingleClickImmediately) {
  1662. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  1663. if (Date.now() - this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  1664. btn !== this._previousButtonPressed) {
  1665. clickInfo.singleClick = true;
  1666. cb(clickInfo, this._currentPickResult);
  1667. }
  1668. }
  1669. // at least one double click is required to be check and exclusive double click is enabled
  1670. else {
  1671. // wait that no double click has been raised during the double click delay
  1672. this._previousDelayedSimpleClickTimeout = this._delayedSimpleClickTimeout;
  1673. this._delayedSimpleClickTimeout = window.setTimeout(this._delayedSimpleClick.bind(this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  1674. }
  1675. let checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  1676. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  1677. if (!checkDoubleClick && ActionManager.HasSpecificTrigger(ActionManager.OnDoublePickTrigger)) {
  1678. act = this._initActionManager(act, clickInfo);
  1679. if (act)
  1680. checkDoubleClick = act.hasSpecificTrigger(ActionManager.OnDoublePickTrigger);
  1681. }
  1682. if (checkDoubleClick) {
  1683. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  1684. if (btn === this._previousButtonPressed &&
  1685. Date.now() - this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  1686. !this._doubleClickOccured
  1687. ) {
  1688. // pointer has not moved for 2 clicks, it's a double click
  1689. if (!clickInfo.hasSwiped &&
  1690. Math.abs(this._previousStartingPointerPosition.x - this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  1691. Math.abs(this._previousStartingPointerPosition.y - this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  1692. this._previousStartingPointerTime = 0;
  1693. this._doubleClickOccured = true;
  1694. clickInfo.doubleClick = true;
  1695. clickInfo.ignore = false;
  1696. if (Scene.ExclusiveDoubleClickMode && this._previousDelayedSimpleClickTimeout) {
  1697. clearTimeout(this._previousDelayedSimpleClickTimeout);
  1698. }
  1699. this._previousDelayedSimpleClickTimeout = this._delayedSimpleClickTimeout;
  1700. cb(clickInfo, this._currentPickResult);
  1701. }
  1702. // if the two successive clicks are too far, it's just two simple clicks
  1703. else {
  1704. this._doubleClickOccured = false;
  1705. this._previousStartingPointerTime = this._startingPointerTime;
  1706. this._previousStartingPointerPosition.x = this._startingPointerPosition.x;
  1707. this._previousStartingPointerPosition.y = this._startingPointerPosition.y;
  1708. this._previousButtonPressed = btn;
  1709. if (Scene.ExclusiveDoubleClickMode) {
  1710. if (this._previousDelayedSimpleClickTimeout) {
  1711. clearTimeout(this._previousDelayedSimpleClickTimeout);
  1712. }
  1713. this._previousDelayedSimpleClickTimeout = this._delayedSimpleClickTimeout;
  1714. cb(clickInfo, this._previousPickResult);
  1715. }
  1716. else {
  1717. cb(clickInfo, this._currentPickResult);
  1718. }
  1719. }
  1720. }
  1721. // just the first click of the double has been raised
  1722. else {
  1723. this._doubleClickOccured = false;
  1724. this._previousStartingPointerTime = this._startingPointerTime;
  1725. this._previousStartingPointerPosition.x = this._startingPointerPosition.x;
  1726. this._previousStartingPointerPosition.y = this._startingPointerPosition.y;
  1727. this._previousButtonPressed = btn;
  1728. }
  1729. }
  1730. }
  1731. }
  1732. clickInfo.ignore = true;
  1733. cb(clickInfo, this._currentPickResult);
  1734. };
  1735. this._spritePredicate = (sprite: Sprite): boolean => {
  1736. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  1737. };
  1738. this._onPointerMove = (evt: PointerEvent) => {
  1739. this._updatePointerPosition(evt);
  1740. // PreObservable support
  1741. if(this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE)){
  1742. return;
  1743. }
  1744. if (!this.cameraToUseForPointers && !this.activeCamera) {
  1745. return;
  1746. }
  1747. if (!this.pointerMovePredicate) {
  1748. this.pointerMovePredicate = (mesh: AbstractMesh): boolean => mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined));
  1749. }
  1750. // Meshes
  1751. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, this.pointerMovePredicate, false, this.cameraToUseForPointers);
  1752. this._processPointerMove(pickResult, evt);
  1753. };
  1754. this._onPointerDown = (evt: PointerEvent) => {
  1755. this._totalPointersPressed++;
  1756. this._pickedDownMesh = null;
  1757. this._meshPickProceed = false;
  1758. this._updatePointerPosition(evt);
  1759. if (this.preventDefaultOnPointerDown && canvas) {
  1760. evt.preventDefault();
  1761. canvas.focus();
  1762. }
  1763. // PreObservable support
  1764. if(this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERDOWN)){
  1765. return;
  1766. }
  1767. if (!this.cameraToUseForPointers && !this.activeCamera) {
  1768. return;
  1769. }
  1770. this._pointerCaptures[evt.pointerId] = true;
  1771. this._startingPointerPosition.x = this._pointerX;
  1772. this._startingPointerPosition.y = this._pointerY;
  1773. this._startingPointerTime = Date.now();
  1774. if (!this.pointerDownPredicate) {
  1775. this.pointerDownPredicate = (mesh: AbstractMesh): boolean => {
  1776. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  1777. };
  1778. }
  1779. // Meshes
  1780. this._pickedDownMesh = null;
  1781. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, this.pointerDownPredicate, false, this.cameraToUseForPointers);
  1782. this._processPointerDown(pickResult, evt);
  1783. // Sprites
  1784. this._pickedDownSprite = null;
  1785. if (this.spriteManagers.length > 0) {
  1786. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  1787. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  1788. if (pickResult.pickedSprite.actionManager) {
  1789. this._pickedDownSprite = pickResult.pickedSprite;
  1790. switch (evt.button) {
  1791. case 0:
  1792. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnLeftPickTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  1793. break;
  1794. case 1:
  1795. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnCenterPickTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  1796. break;
  1797. case 2:
  1798. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnRightPickTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  1799. break;
  1800. }
  1801. if (pickResult.pickedSprite.actionManager) {
  1802. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnPickDownTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  1803. }
  1804. }
  1805. }
  1806. }
  1807. };
  1808. this._onPointerUp = (evt: PointerEvent) => {
  1809. if (this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  1810. return; // So we need to test it the pointer down was pressed before.
  1811. }
  1812. this._totalPointersPressed--;
  1813. this._pickedUpMesh = null;
  1814. this._meshPickProceed = false;
  1815. this._updatePointerPosition(evt);
  1816. this._initClickEvent(this.onPrePointerObservable, this.onPointerObservable, evt, (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => {
  1817. // PreObservable support
  1818. if (this.onPrePointerObservable.hasObservers()) {
  1819. if (!clickInfo.ignore) {
  1820. if (!clickInfo.hasSwiped) {
  1821. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  1822. if(this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERTAP)){
  1823. return;
  1824. }
  1825. }
  1826. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  1827. if(this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERDOUBLETAP)){
  1828. return;
  1829. }
  1830. }
  1831. }
  1832. }
  1833. else {
  1834. if(this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERUP)){
  1835. return;
  1836. }
  1837. }
  1838. }
  1839. if (!this.cameraToUseForPointers && !this.activeCamera) {
  1840. return;
  1841. }
  1842. this._pointerCaptures[evt.pointerId] = false;
  1843. if (!this.pointerUpPredicate) {
  1844. this.pointerUpPredicate = (mesh: AbstractMesh): boolean => {
  1845. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  1846. };
  1847. }
  1848. // Meshes
  1849. if (!this._meshPickProceed && (ActionManager && ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  1850. this._initActionManager(null, clickInfo);
  1851. }
  1852. if (!pickResult) {
  1853. pickResult = this._currentPickResult;
  1854. }
  1855. this._processPointerUp(pickResult, evt, clickInfo);
  1856. // Sprites
  1857. if(!clickInfo.ignore){
  1858. if (this.spriteManagers.length > 0) {
  1859. let spritePickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  1860. if (spritePickResult) {
  1861. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  1862. if (spritePickResult.pickedSprite.actionManager) {
  1863. spritePickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnPickUpTrigger, ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, this, evt));
  1864. if (spritePickResult.pickedSprite.actionManager) {
  1865. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  1866. spritePickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnPickTrigger, ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, this, evt));
  1867. }
  1868. }
  1869. }
  1870. }
  1871. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== spritePickResult.pickedSprite) {
  1872. this._pickedDownSprite.actionManager.processTrigger(ActionManager.OnPickOutTrigger, ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  1873. }
  1874. }
  1875. }
  1876. }
  1877. this._previousPickResult = this._currentPickResult;
  1878. });
  1879. };
  1880. this._onKeyDown = (evt: KeyboardEvent) => {
  1881. let type = KeyboardEventTypes.KEYDOWN;
  1882. if (this.onPreKeyboardObservable.hasObservers()) {
  1883. let pi = new KeyboardInfoPre(type, evt);
  1884. this.onPreKeyboardObservable.notifyObservers(pi, type);
  1885. if (pi.skipOnPointerObservable) {
  1886. return;
  1887. }
  1888. }
  1889. if (this.onKeyboardObservable.hasObservers()) {
  1890. let pi = new KeyboardInfo(type, evt);
  1891. this.onKeyboardObservable.notifyObservers(pi, type);
  1892. }
  1893. if (this.actionManager) {
  1894. this.actionManager.processTrigger(ActionManager.OnKeyDownTrigger, ActionEvent.CreateNewFromScene(this, evt));
  1895. }
  1896. };
  1897. this._onKeyUp = (evt: KeyboardEvent) => {
  1898. let type = KeyboardEventTypes.KEYUP;
  1899. if (this.onPreKeyboardObservable.hasObservers()) {
  1900. let pi = new KeyboardInfoPre(type, evt);
  1901. this.onPreKeyboardObservable.notifyObservers(pi, type);
  1902. if (pi.skipOnPointerObservable) {
  1903. return;
  1904. }
  1905. }
  1906. if (this.onKeyboardObservable.hasObservers()) {
  1907. let pi = new KeyboardInfo(type, evt);
  1908. this.onKeyboardObservable.notifyObservers(pi, type);
  1909. }
  1910. if (this.actionManager) {
  1911. this.actionManager.processTrigger(ActionManager.OnKeyUpTrigger, ActionEvent.CreateNewFromScene(this, evt));
  1912. }
  1913. };
  1914. let engine = this.getEngine();
  1915. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(() => {
  1916. if (!canvas) {
  1917. return;
  1918. }
  1919. canvas.addEventListener("keydown", this._onKeyDown, false);
  1920. canvas.addEventListener("keyup", this._onKeyUp, false);
  1921. });
  1922. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(() => {
  1923. if (!canvas) {
  1924. return;
  1925. }
  1926. canvas.removeEventListener("keydown", this._onKeyDown);
  1927. canvas.removeEventListener("keyup", this._onKeyUp);
  1928. });
  1929. var eventPrefix = Tools.GetPointerPrefix();
  1930. var canvas = this._engine.getRenderingCanvas();
  1931. if (!canvas) {
  1932. return;
  1933. }
  1934. if (attachMove) {
  1935. canvas.addEventListener(eventPrefix + "move", <any>this._onPointerMove, false);
  1936. // Wheel
  1937. canvas.addEventListener('mousewheel', <any>this._onPointerMove, false);
  1938. canvas.addEventListener('DOMMouseScroll', <any>this._onPointerMove, false);
  1939. }
  1940. if (attachDown) {
  1941. canvas.addEventListener(eventPrefix + "down", <any>this._onPointerDown, false);
  1942. }
  1943. if (attachUp) {
  1944. window.addEventListener(eventPrefix + "up", <any>this._onPointerUp, false);
  1945. }
  1946. canvas.tabIndex = 1;
  1947. }
  1948. /** Detaches all event handlers*/
  1949. public detachControl() {
  1950. let engine = this.getEngine();
  1951. var eventPrefix = Tools.GetPointerPrefix();
  1952. var canvas = engine.getRenderingCanvas();
  1953. if (!canvas) {
  1954. return;
  1955. }
  1956. canvas.removeEventListener(eventPrefix + "move", <any>this._onPointerMove);
  1957. canvas.removeEventListener(eventPrefix + "down", <any>this._onPointerDown);
  1958. window.removeEventListener(eventPrefix + "up", <any>this._onPointerUp);
  1959. if (this._onCanvasBlurObserver) {
  1960. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  1961. }
  1962. if (this._onCanvasFocusObserver) {
  1963. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  1964. }
  1965. // Wheel
  1966. canvas.removeEventListener('mousewheel', <any>this._onPointerMove);
  1967. canvas.removeEventListener('DOMMouseScroll', <any>this._onPointerMove);
  1968. // Keyboard
  1969. canvas.removeEventListener("keydown", this._onKeyDown);
  1970. canvas.removeEventListener("keyup", this._onKeyUp);
  1971. // Observables
  1972. this.onKeyboardObservable.clear();
  1973. this.onPreKeyboardObservable.clear();
  1974. this.onPointerObservable.clear();
  1975. this.onPrePointerObservable.clear();
  1976. }
  1977. /**
  1978. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  1979. * Delay loaded resources are not taking in account
  1980. * @return true if all required resources are ready
  1981. */
  1982. public isReady(): boolean {
  1983. if (this._isDisposed) {
  1984. return false;
  1985. }
  1986. if (this._pendingData.length > 0) {
  1987. return false;
  1988. }
  1989. let index: number;
  1990. let engine = this.getEngine();
  1991. // Geometries
  1992. for (index = 0; index < this._geometries.length; index++) {
  1993. var geometry = this._geometries[index];
  1994. if (geometry.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  1995. return false;
  1996. }
  1997. }
  1998. // Meshes
  1999. for (index = 0; index < this.meshes.length; index++) {
  2000. var mesh = this.meshes[index];
  2001. if (!mesh.isEnabled()) {
  2002. continue;
  2003. }
  2004. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  2005. continue;
  2006. }
  2007. if (!mesh.isReady(true)) {
  2008. return false;
  2009. }
  2010. // Effect layers
  2011. let hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && (<Mesh>mesh).instances.length > 0;
  2012. for (var layer of this.effectLayers) {
  2013. if (!layer.hasMesh(mesh)) {
  2014. continue;
  2015. }
  2016. for (var subMesh of mesh.subMeshes) {
  2017. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  2018. return false;
  2019. }
  2020. }
  2021. }
  2022. }
  2023. // Post-processes
  2024. if (this.activeCameras && this.activeCameras.length > 0) {
  2025. for (var camera of this.activeCameras) {
  2026. if (!camera.isReady(true)) {
  2027. return false;
  2028. }
  2029. }
  2030. } else if (this.activeCamera) {
  2031. if (!this.activeCamera.isReady(true)) {
  2032. return false;
  2033. }
  2034. }
  2035. // Particles
  2036. for (var particleSystem of this.particleSystems) {
  2037. if (!particleSystem.isReady()) {
  2038. return false;
  2039. }
  2040. }
  2041. return true;
  2042. }
  2043. /** Resets all cached information relative to material (including effect and visibility) */
  2044. public resetCachedMaterial(): void {
  2045. this._cachedMaterial = null;
  2046. this._cachedEffect = null;
  2047. this._cachedVisibility = null;
  2048. }
  2049. /**
  2050. * Registers a function to be called before every frame render
  2051. * @param func defines the function to register
  2052. */
  2053. public registerBeforeRender(func: () => void): void {
  2054. this.onBeforeRenderObservable.add(func);
  2055. }
  2056. /**
  2057. * Unregisters a function called before every frame render
  2058. * @param func defines the function to unregister
  2059. */
  2060. public unregisterBeforeRender(func: () => void): void {
  2061. this.onBeforeRenderObservable.removeCallback(func);
  2062. }
  2063. /**
  2064. * Registers a function to be called after every frame render
  2065. * @param func defines the function to register
  2066. */
  2067. public registerAfterRender(func: () => void): void {
  2068. this.onAfterRenderObservable.add(func);
  2069. }
  2070. /**
  2071. * Unregisters a function called after every frame render
  2072. * @param func defines the function to unregister
  2073. */
  2074. public unregisterAfterRender(func: () => void): void {
  2075. this.onAfterRenderObservable.removeCallback(func);
  2076. }
  2077. private _executeOnceBeforeRender(func: () => void): void {
  2078. let execFunc = () => {
  2079. func();
  2080. setTimeout(() => {
  2081. this.unregisterBeforeRender(execFunc);
  2082. });
  2083. }
  2084. this.registerBeforeRender(execFunc);
  2085. }
  2086. /**
  2087. * The provided function will run before render once and will be disposed afterwards.
  2088. * A timeout delay can be provided so that the function will be executed in N ms.
  2089. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  2090. * @param func The function to be executed.
  2091. * @param timeout optional delay in ms
  2092. */
  2093. public executeOnceBeforeRender(func: () => void, timeout?: number): void {
  2094. if (timeout !== undefined) {
  2095. setTimeout(() => {
  2096. this._executeOnceBeforeRender(func);
  2097. }, timeout);
  2098. } else {
  2099. this._executeOnceBeforeRender(func);
  2100. }
  2101. }
  2102. /** @hidden */
  2103. public _addPendingData(data: any): void {
  2104. this._pendingData.push(data);
  2105. }
  2106. /** @hidden */
  2107. public _removePendingData(data: any): void {
  2108. var wasLoading = this.isLoading;
  2109. var index = this._pendingData.indexOf(data);
  2110. if (index !== -1) {
  2111. this._pendingData.splice(index, 1);
  2112. }
  2113. if (wasLoading && !this.isLoading) {
  2114. this.onDataLoadedObservable.notifyObservers(this);
  2115. }
  2116. }
  2117. /**
  2118. * Returns the number of items waiting to be loaded
  2119. * @returns the number of items waiting to be loaded
  2120. */
  2121. public getWaitingItemsCount(): number {
  2122. return this._pendingData.length;
  2123. }
  2124. /**
  2125. * Returns a boolean indicating if the scene is still loading data
  2126. */
  2127. public get isLoading(): boolean {
  2128. return this._pendingData.length > 0;
  2129. }
  2130. /**
  2131. * Registers a function to be executed when the scene is ready
  2132. * @param {Function} func - the function to be executed
  2133. */
  2134. public executeWhenReady(func: () => void): void {
  2135. this.onReadyObservable.add(func);
  2136. if (this._executeWhenReadyTimeoutId !== -1) {
  2137. return;
  2138. }
  2139. this._executeWhenReadyTimeoutId = setTimeout(() => {
  2140. this._checkIsReady();
  2141. }, 150);
  2142. }
  2143. /**
  2144. * Returns a promise that resolves when the scene is ready
  2145. * @returns A promise that resolves when the scene is ready
  2146. */
  2147. public whenReadyAsync(): Promise<void> {
  2148. return new Promise(resolve => {
  2149. this.executeWhenReady(() => {
  2150. resolve();
  2151. });
  2152. });
  2153. }
  2154. /** @hidden */
  2155. public _checkIsReady() {
  2156. if (this.isReady()) {
  2157. this.onReadyObservable.notifyObservers(this);
  2158. this.onReadyObservable.clear();
  2159. this._executeWhenReadyTimeoutId = -1;
  2160. return;
  2161. }
  2162. this._executeWhenReadyTimeoutId = setTimeout(() => {
  2163. this._checkIsReady();
  2164. }, 150);
  2165. }
  2166. // Animations
  2167. /**
  2168. * Will start the animation sequence of a given target
  2169. * @param target defines the target
  2170. * @param from defines from which frame should animation start
  2171. * @param to defines until which frame should animation run.
  2172. * @param weight defines the weight to apply to the animation (1.0 by default)
  2173. * @param loop defines if the animation loops
  2174. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  2175. * @param onAnimationEnd defines the function to be executed when the animation ends
  2176. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  2177. * @returns the animatable object created for this animation
  2178. */
  2179. public beginWeightedAnimation(target: any, from: number, to: number, weight = 1.0, loop?: boolean, speedRatio: number = 1.0, onAnimationEnd?: () => void, animatable?: Animatable): Animatable {
  2180. let returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  2181. returnedAnimatable.weight = weight;
  2182. return returnedAnimatable;
  2183. }
  2184. /**
  2185. * Will start the animation sequence of a given target
  2186. * @param target defines the target
  2187. * @param from defines from which frame should animation start
  2188. * @param to defines until which frame should animation run.
  2189. * @param loop defines if the animation loops
  2190. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  2191. * @param onAnimationEnd defines the function to be executed when the animation ends
  2192. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  2193. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  2194. * @returns the animatable object created for this animation
  2195. */
  2196. public beginAnimation(target: any, from: number, to: number, loop?: boolean, speedRatio: number = 1.0, onAnimationEnd?: () => void, animatable?: Animatable, stopCurrent = true): Animatable {
  2197. if (from > to && speedRatio > 0) {
  2198. speedRatio *= -1;
  2199. }
  2200. if (stopCurrent) {
  2201. this.stopAnimation(target);
  2202. }
  2203. if (!animatable) {
  2204. animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  2205. }
  2206. // Local animations
  2207. if (target.animations) {
  2208. animatable.appendAnimations(target, target.animations);
  2209. }
  2210. // Children animations
  2211. if (target.getAnimatables) {
  2212. var animatables = target.getAnimatables();
  2213. for (var index = 0; index < animatables.length; index++) {
  2214. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  2215. }
  2216. }
  2217. animatable.reset();
  2218. return animatable;
  2219. }
  2220. /**
  2221. * Begin a new animation on a given node
  2222. * @param target defines the target where the animation will take place
  2223. * @param animations defines the list of animations to start
  2224. * @param from defines the initial value
  2225. * @param to defines the final value
  2226. * @param loop defines if you want animation to loop (off by default)
  2227. * @param speedRatio defines the speed ratio to apply to all animations
  2228. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  2229. * @returns the list of created animatables
  2230. */
  2231. public beginDirectAnimation(target: any, animations: Animation[], from: number, to: number, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void): Animatable {
  2232. if (speedRatio === undefined) {
  2233. speedRatio = 1.0;
  2234. }
  2235. var animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  2236. return animatable;
  2237. }
  2238. /**
  2239. * Begin a new animation on a given node and its hierarchy
  2240. * @param target defines the root node where the animation will take place
  2241. * @param 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.
  2242. * @param animations defines the list of animations to start
  2243. * @param from defines the initial value
  2244. * @param to defines the final value
  2245. * @param loop defines if you want animation to loop (off by default)
  2246. * @param speedRatio defines the speed ratio to apply to all animations
  2247. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  2248. * @returns the list of animatables created for all nodes
  2249. */
  2250. public beginDirectHierarchyAnimation(target: Node, directDescendantsOnly: boolean, animations: Animation[], from: number, to: number, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void): Animatable[] {
  2251. let children = target.getDescendants(directDescendantsOnly);
  2252. let result = [];
  2253. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  2254. for (var child of children) {
  2255. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  2256. }
  2257. return result;
  2258. }
  2259. /**
  2260. * Gets the animatable associated with a specific target
  2261. * @param target defines the target of the animatable
  2262. * @returns the required animatable if found
  2263. */
  2264. public getAnimatableByTarget(target: any): Nullable<Animatable> {
  2265. for (var index = 0; index < this._activeAnimatables.length; index++) {
  2266. if (this._activeAnimatables[index].target === target) {
  2267. return this._activeAnimatables[index];
  2268. }
  2269. }
  2270. return null;
  2271. }
  2272. /**
  2273. * Gets all animatables associated with a given target
  2274. * @param target defines the target to look animatables for
  2275. * @returns an array of Animatables
  2276. */
  2277. public getAllAnimatablesByTarget(target: any): Array<Animatable> {
  2278. let result = [];
  2279. for (var index = 0; index < this._activeAnimatables.length; index++) {
  2280. if (this._activeAnimatables[index].target === target) {
  2281. result.push(this._activeAnimatables[index]);
  2282. }
  2283. }
  2284. return result;
  2285. }
  2286. /**
  2287. * Gets all animatable attached to the scene
  2288. */
  2289. public get animatables(): Animatable[] {
  2290. return this._activeAnimatables;
  2291. }
  2292. /**
  2293. * Will stop the animation of the given target
  2294. * @param target - the target
  2295. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  2296. */
  2297. public stopAnimation(target: any, animationName?: string): void {
  2298. var animatables = this.getAllAnimatablesByTarget(target);
  2299. for (var animatable of animatables) {
  2300. animatable.stop(animationName);
  2301. }
  2302. }
  2303. /**
  2304. * Stops and removes all animations that have been applied to the scene
  2305. */
  2306. public stopAllAnimations(): void {
  2307. if (this._activeAnimatables) {
  2308. for (let i = 0; i < this._activeAnimatables.length; i++) {
  2309. this._activeAnimatables[i].stop();
  2310. }
  2311. this._activeAnimatables = [];
  2312. }
  2313. for (var group of this.animationGroups) {
  2314. group.stop();
  2315. }
  2316. }
  2317. private _animate(): void {
  2318. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  2319. return;
  2320. }
  2321. // Getting time
  2322. var now = Tools.Now;
  2323. if (!this._animationTimeLast) {
  2324. if (this._pendingData.length > 0) {
  2325. return;
  2326. }
  2327. this._animationTimeLast = now;
  2328. }
  2329. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  2330. this._animationTime += deltaTime;
  2331. this._animationTimeLast = now;
  2332. for (var index = 0; index < this._activeAnimatables.length; index++) {
  2333. this._activeAnimatables[index]._animate(this._animationTime);
  2334. }
  2335. // Late animation bindings
  2336. this._processLateAnimationBindings();
  2337. }
  2338. /** @hidden */
  2339. public _registerTargetForLateAnimationBinding(runtimeAnimation: RuntimeAnimation, originalValue: any): void {
  2340. let target = runtimeAnimation.target;
  2341. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  2342. if (!target._lateAnimationHolders) {
  2343. target._lateAnimationHolders = {};
  2344. }
  2345. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  2346. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  2347. totalWeight: 0,
  2348. animations: [],
  2349. originalValue: originalValue
  2350. }
  2351. }
  2352. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  2353. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  2354. }
  2355. private _processLateAnimationBindingsForMatrices(holder: {
  2356. totalWeight: number,
  2357. animations: RuntimeAnimation[],
  2358. originalValue: Matrix
  2359. }): any {
  2360. let normalizer = 1.0;
  2361. let finalPosition = Tmp.Vector3[0];
  2362. let finalScaling = Tmp.Vector3[1];
  2363. let finalQuaternion = Tmp.Quaternion[0];
  2364. let startIndex = 0;
  2365. let originalAnimation = holder.animations[0];
  2366. let originalValue = holder.originalValue;
  2367. var scale = 1;
  2368. if (holder.totalWeight < 1.0) {
  2369. // We need to mix the original value in
  2370. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  2371. scale = 1.0 - holder.totalWeight;
  2372. } else {
  2373. startIndex = 1;
  2374. // We need to normalize the weights
  2375. normalizer = holder.totalWeight;
  2376. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  2377. scale = originalAnimation.weight / normalizer;
  2378. if (scale == 1) {
  2379. return originalAnimation.currentValue;
  2380. }
  2381. }
  2382. finalScaling.scaleInPlace(scale);
  2383. finalPosition.scaleInPlace(scale);
  2384. finalQuaternion.scaleInPlace(scale);
  2385. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  2386. var runtimeAnimation = holder.animations[animIndex];
  2387. var scale = runtimeAnimation.weight / normalizer;
  2388. let currentPosition = Tmp.Vector3[2];
  2389. let currentScaling = Tmp.Vector3[3];
  2390. let currentQuaternion = Tmp.Quaternion[1];
  2391. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  2392. currentScaling.scaleAndAddToRef(scale, finalScaling);
  2393. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  2394. currentPosition.scaleAndAddToRef(scale, finalPosition);
  2395. }
  2396. Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  2397. return originalAnimation._workValue;
  2398. }
  2399. private _processLateAnimationBindingsForQuaternions(holder: {
  2400. totalWeight: number,
  2401. animations: RuntimeAnimation[],
  2402. originalValue: Quaternion
  2403. }): Quaternion {
  2404. let originalAnimation = holder.animations[0];
  2405. let originalValue = holder.originalValue;
  2406. if (holder.animations.length === 1) {
  2407. return Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  2408. }
  2409. let normalizer = 1.0;
  2410. let quaternions: Array<Quaternion>;
  2411. let weights: Array<number>;
  2412. if (holder.totalWeight < 1.0) {
  2413. let scale = 1.0 - holder.totalWeight;
  2414. quaternions = [];
  2415. weights = [];
  2416. quaternions.push(originalValue);
  2417. weights.push(scale);
  2418. } else {
  2419. if (holder.animations.length === 2) { // Slerp as soon as we can
  2420. return Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  2421. }
  2422. quaternions = [];
  2423. weights = [];
  2424. normalizer = holder.totalWeight;
  2425. }
  2426. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  2427. let runtimeAnimation = holder.animations[animIndex];
  2428. quaternions.push(runtimeAnimation.currentValue);
  2429. weights.push(runtimeAnimation.weight / normalizer);
  2430. }
  2431. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  2432. let cumulativeAmount = 0;
  2433. let cumulativeQuaternion: Nullable<Quaternion> = null;
  2434. for (var index = 0; index < quaternions.length; ) {
  2435. if (!cumulativeQuaternion) {
  2436. cumulativeQuaternion = Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  2437. cumulativeAmount = weights[index] + weights[index + 1];
  2438. index += 2;
  2439. continue;
  2440. }
  2441. cumulativeAmount += weights[index];
  2442. Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  2443. index++;
  2444. }
  2445. return cumulativeQuaternion!;
  2446. }
  2447. private _processLateAnimationBindings(): void {
  2448. if (!this._registeredForLateAnimationBindings.length) {
  2449. return;
  2450. }
  2451. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  2452. var target = this._registeredForLateAnimationBindings.data[index];
  2453. for (var path in target._lateAnimationHolders) {
  2454. var holder = target._lateAnimationHolders[path];
  2455. let originalAnimation: RuntimeAnimation = holder.animations[0];
  2456. let originalValue = holder.originalValue;
  2457. let matrixDecomposeMode = Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  2458. let finalValue: any;
  2459. if (matrixDecomposeMode) {
  2460. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  2461. } else {
  2462. let quaternionMode = originalValue.w !== undefined;
  2463. if (quaternionMode) {
  2464. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  2465. } else {
  2466. let startIndex = 0;
  2467. let normalizer = 1.0;
  2468. if (holder.totalWeight < 1.0) {
  2469. // We need to mix the original value in
  2470. if (originalValue.scale) {
  2471. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  2472. } else {
  2473. finalValue = originalValue * (1.0 - holder.totalWeight);
  2474. }
  2475. } else {
  2476. // We need to normalize the weights
  2477. normalizer = holder.totalWeight;
  2478. let scale = originalAnimation.weight / normalizer;
  2479. if (scale !== 1) {
  2480. if (originalAnimation.currentValue.scale) {
  2481. finalValue = originalAnimation.currentValue.scale(scale);
  2482. } else {
  2483. finalValue = originalAnimation.currentValue * scale;
  2484. }
  2485. } else {
  2486. finalValue = originalAnimation.currentValue;
  2487. }
  2488. startIndex = 1;
  2489. }
  2490. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  2491. var runtimeAnimation = holder.animations[animIndex];
  2492. var scale = runtimeAnimation.weight / normalizer;
  2493. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  2494. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  2495. } else {
  2496. finalValue += runtimeAnimation.currentValue * scale;
  2497. }
  2498. }
  2499. }
  2500. }
  2501. target[path] = finalValue;
  2502. }
  2503. target._lateAnimationHolders = {};
  2504. }
  2505. this._registeredForLateAnimationBindings.reset();
  2506. }
  2507. // Matrix
  2508. /** @hidden */
  2509. public _switchToAlternateCameraConfiguration(active: boolean): void {
  2510. this._useAlternateCameraConfiguration = active;
  2511. }
  2512. /**
  2513. * Gets the current view matrix
  2514. * @returns a Matrix
  2515. */
  2516. public getViewMatrix(): Matrix {
  2517. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  2518. }
  2519. /**
  2520. * Gets the current projection matrix
  2521. * @returns a Matrix
  2522. */
  2523. public getProjectionMatrix(): Matrix {
  2524. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  2525. }
  2526. /**
  2527. * Gets the current transform matrix
  2528. * @returns a Matrix made of View * Projection
  2529. */
  2530. public getTransformMatrix(): Matrix {
  2531. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  2532. }
  2533. /**
  2534. * Sets the current transform matrix
  2535. * @param view defines the View matrix to use
  2536. * @param projection defines the Projection matrix to use
  2537. */
  2538. public setTransformMatrix(view: Matrix, projection: Matrix): void {
  2539. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  2540. return;
  2541. }
  2542. this._viewUpdateFlag = view.updateFlag;
  2543. this._projectionUpdateFlag = projection.updateFlag;
  2544. this._viewMatrix = view;
  2545. this._projectionMatrix = projection;
  2546. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  2547. // Update frustum
  2548. if (!this._frustumPlanes) {
  2549. this._frustumPlanes = Frustum.GetPlanes(this._transformMatrix);
  2550. } else {
  2551. Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  2552. }
  2553. if (this.activeCamera && this.activeCamera._alternateCamera) {
  2554. let otherCamera = this.activeCamera._alternateCamera;
  2555. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), Tmp.Matrix[0]);
  2556. Frustum.GetRightPlaneToRef(Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  2557. }
  2558. if (this._sceneUbo.useUbo) {
  2559. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  2560. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  2561. this._sceneUbo.update();
  2562. }
  2563. }
  2564. /** @hidden */
  2565. public _setAlternateTransformMatrix(view: Matrix, projection: Matrix): void {
  2566. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  2567. return;
  2568. }
  2569. this._alternateViewUpdateFlag = view.updateFlag;
  2570. this._alternateProjectionUpdateFlag = projection.updateFlag;
  2571. this._alternateViewMatrix = view;
  2572. this._alternateProjectionMatrix = projection;
  2573. if (!this._alternateTransformMatrix) {
  2574. this._alternateTransformMatrix = Matrix.Zero();
  2575. }
  2576. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  2577. if (!this._alternateSceneUbo) {
  2578. this._createAlternateUbo();
  2579. }
  2580. if (this._alternateSceneUbo.useUbo) {
  2581. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  2582. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  2583. this._alternateSceneUbo.update();
  2584. }
  2585. }
  2586. /**
  2587. * Gets the uniform buffer used to store scene data
  2588. * @returns a UniformBuffer
  2589. */
  2590. public getSceneUniformBuffer(): UniformBuffer {
  2591. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  2592. }
  2593. /**
  2594. * Gets an unique (relatively to the current scene) Id
  2595. * @returns an unique number for the scene
  2596. */
  2597. public getUniqueId() {
  2598. var result = Scene._uniqueIdCounter;
  2599. Scene._uniqueIdCounter++;
  2600. return result;
  2601. }
  2602. /**
  2603. * Add a mesh to the list of scene's meshes
  2604. * @param newMesh defines the mesh to add
  2605. * @param recursive if all child meshes should also be added to the scene
  2606. */
  2607. public addMesh(newMesh: AbstractMesh, recursive = false) {
  2608. this.meshes.push(newMesh);
  2609. //notify the collision coordinator
  2610. if (this.collisionCoordinator) {
  2611. this.collisionCoordinator.onMeshAdded(newMesh);
  2612. }
  2613. newMesh._resyncLightSources();
  2614. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  2615. if(recursive){
  2616. newMesh.getChildMeshes().forEach((m)=>{
  2617. this.addMesh(m);
  2618. })
  2619. }
  2620. }
  2621. /**
  2622. * Remove a mesh for the list of scene's meshes
  2623. * @param toRemove defines the mesh to remove
  2624. * @param recursive if all child meshes should also be removed from the scene
  2625. * @returns the index where the mesh was in the mesh list
  2626. */
  2627. public removeMesh(toRemove: AbstractMesh, recursive = false): number {
  2628. var index = this.meshes.indexOf(toRemove);
  2629. if (index !== -1) {
  2630. // Remove from the scene if mesh found
  2631. this.meshes.splice(index, 1);
  2632. }
  2633. this.onMeshRemovedObservable.notifyObservers(toRemove);
  2634. if(recursive){
  2635. toRemove.getChildMeshes().forEach((m)=>{
  2636. this.removeMesh(m);
  2637. })
  2638. }
  2639. return index;
  2640. }
  2641. /**
  2642. * Add a transform node to the list of scene's transform nodes
  2643. * @param newTransformNode defines the transform node to add
  2644. */
  2645. public addTransformNode(newTransformNode: TransformNode) {
  2646. this.transformNodes.push(newTransformNode);
  2647. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  2648. }
  2649. /**
  2650. * Remove a transform node for the list of scene's transform nodes
  2651. * @param toRemove defines the transform node to remove
  2652. * @returns the index where the transform node was in the transform node list
  2653. */
  2654. public removeTransformNode(toRemove: TransformNode): number {
  2655. var index = this.transformNodes.indexOf(toRemove);
  2656. if (index !== -1) {
  2657. // Remove from the scene if found
  2658. this.transformNodes.splice(index, 1);
  2659. }
  2660. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  2661. return index;
  2662. }
  2663. /**
  2664. * Remove a skeleton for the list of scene's skeletons
  2665. * @param toRemove defines the skeleton to remove
  2666. * @returns the index where the skeleton was in the skeleton list
  2667. */
  2668. public removeSkeleton(toRemove: Skeleton): number {
  2669. var index = this.skeletons.indexOf(toRemove);
  2670. if (index !== -1) {
  2671. // Remove from the scene if found
  2672. this.skeletons.splice(index, 1);
  2673. }
  2674. return index;
  2675. }
  2676. /**
  2677. * Remove a morph target for the list of scene's morph targets
  2678. * @param toRemove defines the morph target to remove
  2679. * @returns the index where the morph target was in the morph target list
  2680. */
  2681. public removeMorphTargetManager(toRemove: MorphTargetManager): number {
  2682. var index = this.morphTargetManagers.indexOf(toRemove);
  2683. if (index !== -1) {
  2684. // Remove from the scene if found
  2685. this.morphTargetManagers.splice(index, 1);
  2686. }
  2687. return index;
  2688. }
  2689. /**
  2690. * Remove a light for the list of scene's lights
  2691. * @param toRemove defines the light to remove
  2692. * @returns the index where the light was in the light list
  2693. */
  2694. public removeLight(toRemove: Light): number {
  2695. var index = this.lights.indexOf(toRemove);
  2696. if (index !== -1) {
  2697. // Remove from meshes
  2698. for (var mesh of this.meshes) {
  2699. mesh._removeLightSource(toRemove);
  2700. }
  2701. // Remove from the scene if mesh found
  2702. this.lights.splice(index, 1);
  2703. this.sortLightsByPriority();
  2704. }
  2705. this.onLightRemovedObservable.notifyObservers(toRemove);
  2706. return index;
  2707. }
  2708. /**
  2709. * Remove a camera for the list of scene's cameras
  2710. * @param toRemove defines the camera to remove
  2711. * @returns the index where the camera was in the camera list
  2712. */
  2713. public removeCamera(toRemove: Camera): number {
  2714. var index = this.cameras.indexOf(toRemove);
  2715. if (index !== -1) {
  2716. // Remove from the scene if mesh found
  2717. this.cameras.splice(index, 1);
  2718. }
  2719. // Remove from activeCameras
  2720. var index2 = this.activeCameras.indexOf(toRemove);
  2721. if (index2 !== -1) {
  2722. // Remove from the scene if mesh found
  2723. this.activeCameras.splice(index2, 1);
  2724. }
  2725. // Reset the activeCamera
  2726. if (this.activeCamera === toRemove) {
  2727. if (this.cameras.length > 0) {
  2728. this.activeCamera = this.cameras[0];
  2729. } else {
  2730. this.activeCamera = null;
  2731. }
  2732. }
  2733. this.onCameraRemovedObservable.notifyObservers(toRemove);
  2734. return index;
  2735. }
  2736. /**
  2737. * Remove a particle system for the list of scene's particle systems
  2738. * @param toRemove defines the particle system to remove
  2739. * @returns the index where the particle system was in the particle system list
  2740. */
  2741. public removeParticleSystem(toRemove: IParticleSystem): number {
  2742. var index = this.particleSystems.indexOf(toRemove);
  2743. if (index !== -1) {
  2744. this.particleSystems.splice(index, 1);
  2745. }
  2746. return index;
  2747. }
  2748. /**
  2749. * Remove a animation for the list of scene's animations
  2750. * @param toRemove defines the animation to remove
  2751. * @returns the index where the animation was in the animation list
  2752. */
  2753. public removeAnimation(toRemove: Animation): number {
  2754. var index = this.animations.indexOf(toRemove);
  2755. if (index !== -1) {
  2756. this.animations.splice(index, 1);
  2757. }
  2758. return index;
  2759. }
  2760. /**
  2761. * Removes the given animation group from this scene.
  2762. * @param toRemove The animation group to remove
  2763. * @returns The index of the removed animation group
  2764. */
  2765. public removeAnimationGroup(toRemove: AnimationGroup): number {
  2766. var index = this.animationGroups.indexOf(toRemove);
  2767. if (index !== -1) {
  2768. this.animationGroups.splice(index, 1);
  2769. }
  2770. return index;
  2771. }
  2772. /**
  2773. * Removes the given multi-material from this scene.
  2774. * @param toRemove The multi-material to remove
  2775. * @returns The index of the removed multi-material
  2776. */
  2777. public removeMultiMaterial(toRemove: MultiMaterial): number {
  2778. var index = this.multiMaterials.indexOf(toRemove);
  2779. if (index !== -1) {
  2780. this.multiMaterials.splice(index, 1);
  2781. }
  2782. return index;
  2783. }
  2784. /**
  2785. * Removes the given material from this scene.
  2786. * @param toRemove The material to remove
  2787. * @returns The index of the removed material
  2788. */
  2789. public removeMaterial(toRemove: Material): number {
  2790. var index = this.materials.indexOf(toRemove);
  2791. if (index !== -1) {
  2792. this.materials.splice(index, 1);
  2793. }
  2794. return index;
  2795. }
  2796. /**
  2797. * Removes the given lens flare system from this scene.
  2798. * @param toRemove The lens flare system to remove
  2799. * @returns The index of the removed lens flare system
  2800. */
  2801. public removeLensFlareSystem(toRemove: LensFlareSystem): number {
  2802. var index = this.lensFlareSystems.indexOf(toRemove);
  2803. if (index !== -1) {
  2804. this.lensFlareSystems.splice(index, 1);
  2805. }
  2806. return index;
  2807. }
  2808. /**
  2809. * Removes the given action manager from this scene.
  2810. * @param toRemove The action manager to remove
  2811. * @returns The index of the removed action manager
  2812. */
  2813. public removeActionManager(toRemove: ActionManager): number {
  2814. var index = this._actionManagers.indexOf(toRemove);
  2815. if (index !== -1) {
  2816. this._actionManagers.splice(index, 1);
  2817. }
  2818. return index;
  2819. }
  2820. /**
  2821. * Removes the given effect layer from this scene.
  2822. * @param toRemove defines the effect layer to remove
  2823. * @returns the index of the removed effect layer
  2824. */
  2825. public removeEffectLayer(toRemove: EffectLayer): number {
  2826. var index = this.effectLayers.indexOf(toRemove);
  2827. if (index !== -1) {
  2828. this.effectLayers.splice(index, 1);
  2829. }
  2830. return index;
  2831. }
  2832. /**
  2833. * Removes the given texture from this scene.
  2834. * @param toRemove The texture to remove
  2835. * @returns The index of the removed texture
  2836. */
  2837. public removeTexture(toRemove: BaseTexture): number {
  2838. var index = this.textures.indexOf(toRemove);
  2839. if (index !== -1) {
  2840. this.textures.splice(index, 1);
  2841. }
  2842. return index;
  2843. }
  2844. /**
  2845. * Adds the given light to this scene
  2846. * @param newLight The light to add
  2847. */
  2848. public addLight(newLight: Light): void {
  2849. this.lights.push(newLight);
  2850. this.sortLightsByPriority();
  2851. // Add light to all meshes (To support if the light is removed and then readded)
  2852. for (var mesh of this.meshes) {
  2853. if (mesh._lightSources.indexOf(newLight) === -1) {
  2854. mesh._lightSources.push(newLight);
  2855. mesh._resyncLightSources();
  2856. }
  2857. }
  2858. this.onNewLightAddedObservable.notifyObservers(newLight);
  2859. }
  2860. /**
  2861. * Sorts the list list based on light priorities
  2862. */
  2863. public sortLightsByPriority(): void {
  2864. if (this.requireLightSorting) {
  2865. this.lights.sort(Light.CompareLightsPriority);
  2866. }
  2867. }
  2868. /**
  2869. * Adds the given camera to this scene
  2870. * @param newCamera The camera to add
  2871. */
  2872. public addCamera(newCamera: Camera): void {
  2873. this.cameras.push(newCamera);
  2874. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  2875. }
  2876. /**
  2877. * Adds the given skeleton to this scene
  2878. * @param newSkeleton The skeleton to add
  2879. */
  2880. public addSkeleton(newSkeleton: Skeleton): void {
  2881. this.skeletons.push(newSkeleton);
  2882. }
  2883. /**
  2884. * Adds the given particle system to this scene
  2885. * @param newParticleSystem The particle system to add
  2886. */
  2887. public addParticleSystem(newParticleSystem: IParticleSystem): void {
  2888. this.particleSystems.push(newParticleSystem);
  2889. }
  2890. /**
  2891. * Adds the given animation to this scene
  2892. * @param newAnimation The animation to add
  2893. */
  2894. public addAnimation(newAnimation: Animation): void {
  2895. this.animations.push(newAnimation);
  2896. }
  2897. /**
  2898. * Adds the given animation group to this scene.
  2899. * @param newAnimationGroup The animation group to add
  2900. */
  2901. public addAnimationGroup(newAnimationGroup: AnimationGroup): void {
  2902. this.animationGroups.push(newAnimationGroup);
  2903. }
  2904. /**
  2905. * Adds the given multi-material to this scene
  2906. * @param newMultiMaterial The multi-material to add
  2907. */
  2908. public addMultiMaterial(newMultiMaterial: MultiMaterial): void {
  2909. this.multiMaterials.push(newMultiMaterial);
  2910. }
  2911. /**
  2912. * Adds the given material to this scene
  2913. * @param newMaterial The material to add
  2914. */
  2915. public addMaterial(newMaterial: Material): void {
  2916. this.materials.push(newMaterial);
  2917. }
  2918. /**
  2919. * Adds the given morph target to this scene
  2920. * @param newMorphTargetManager The morph target to add
  2921. */
  2922. public addMorphTargetManager(newMorphTargetManager: MorphTargetManager): void {
  2923. this.morphTargetManagers.push(newMorphTargetManager);
  2924. }
  2925. /**
  2926. * Adds the given geometry to this scene
  2927. * @param newGeometry The geometry to add
  2928. */
  2929. public addGeometry(newGeometry: Geometry): void {
  2930. this._geometries.push(newGeometry);
  2931. }
  2932. /**
  2933. * Adds the given lens flare system to this scene
  2934. * @param newLensFlareSystem The lens flare system to add
  2935. */
  2936. public addLensFlareSystem(newLensFlareSystem: LensFlareSystem): void {
  2937. this.lensFlareSystems.push(newLensFlareSystem);
  2938. }
  2939. /**
  2940. * Adds the given effect layer to this scene
  2941. * @param newEffectLayer defines the effect layer to add
  2942. */
  2943. public addEffectLayer(newEffectLayer: EffectLayer): void {
  2944. this.effectLayers.push(newEffectLayer);
  2945. }
  2946. /**
  2947. * Adds the given action manager to this scene
  2948. * @param newActionManager The action manager to add
  2949. */
  2950. public addActionManager(newActionManager: ActionManager): void {
  2951. this._actionManagers.push(newActionManager);
  2952. }
  2953. /**
  2954. * Adds the given texture to this scene.
  2955. * @param newTexture The texture to add
  2956. */
  2957. public addTexture(newTexture: BaseTexture): void {
  2958. this.textures.push(newTexture);
  2959. }
  2960. /**
  2961. * Switch active camera
  2962. * @param newCamera defines the new active camera
  2963. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  2964. */
  2965. public switchActiveCamera(newCamera: Camera, attachControl = true): void {
  2966. var canvas = this._engine.getRenderingCanvas();
  2967. if (!canvas) {
  2968. return;
  2969. }
  2970. if (this.activeCamera) {
  2971. this.activeCamera.detachControl(canvas);
  2972. }
  2973. this.activeCamera = newCamera;
  2974. if (attachControl) {
  2975. newCamera.attachControl(canvas);
  2976. }
  2977. }
  2978. /**
  2979. * sets the active camera of the scene using its ID
  2980. * @param id defines the camera's ID
  2981. * @return the new active camera or null if none found.
  2982. */
  2983. public setActiveCameraByID(id: string): Nullable<Camera> {
  2984. var camera = this.getCameraByID(id);
  2985. if (camera) {
  2986. this.activeCamera = camera;
  2987. return camera;
  2988. }
  2989. return null;
  2990. }
  2991. /**
  2992. * sets the active camera of the scene using its name
  2993. * @param name defines the camera's name
  2994. * @returns the new active camera or null if none found.
  2995. */
  2996. public setActiveCameraByName(name: string): Nullable<Camera> {
  2997. var camera = this.getCameraByName(name);
  2998. if (camera) {
  2999. this.activeCamera = camera;
  3000. return camera;
  3001. }
  3002. return null;
  3003. }
  3004. /**
  3005. * get an animation group using its name
  3006. * @param name defines the material's name
  3007. * @return the animation group or null if none found.
  3008. */
  3009. public getAnimationGroupByName(name: string): Nullable<AnimationGroup> {
  3010. for (var index = 0; index < this.animationGroups.length; index++) {
  3011. if (this.animationGroups[index].name === name) {
  3012. return this.animationGroups[index];
  3013. }
  3014. }
  3015. return null;
  3016. }
  3017. /**
  3018. * get a material using its id
  3019. * @param id defines the material's ID
  3020. * @return the material or null if none found.
  3021. */
  3022. public getMaterialByID(id: string): Nullable<Material> {
  3023. for (var index = 0; index < this.materials.length; index++) {
  3024. if (this.materials[index].id === id) {
  3025. return this.materials[index];
  3026. }
  3027. }
  3028. return null;
  3029. }
  3030. /**
  3031. * Gets a material using its name
  3032. * @param name defines the material's name
  3033. * @return the material or null if none found.
  3034. */
  3035. public getMaterialByName(name: string): Nullable<Material> {
  3036. for (var index = 0; index < this.materials.length; index++) {
  3037. if (this.materials[index].name === name) {
  3038. return this.materials[index];
  3039. }
  3040. }
  3041. return null;
  3042. }
  3043. /**
  3044. * Gets a lens flare system using its name
  3045. * @param name defines the name to look for
  3046. * @returns the lens flare system or null if not found
  3047. */
  3048. public getLensFlareSystemByName(name: string): Nullable<LensFlareSystem> {
  3049. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  3050. if (this.lensFlareSystems[index].name === name) {
  3051. return this.lensFlareSystems[index];
  3052. }
  3053. }
  3054. return null;
  3055. }
  3056. /**
  3057. * Gets a lens flare system using its id
  3058. * @param id defines the id to look for
  3059. * @returns the lens flare system or null if not found
  3060. */
  3061. public getLensFlareSystemByID(id: string): Nullable<LensFlareSystem> {
  3062. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  3063. if (this.lensFlareSystems[index].id === id) {
  3064. return this.lensFlareSystems[index];
  3065. }
  3066. }
  3067. return null;
  3068. }
  3069. /**
  3070. * Gets a camera using its id
  3071. * @param id defines the id to look for
  3072. * @returns the camera or null if not found
  3073. */
  3074. public getCameraByID(id: string): Nullable<Camera> {
  3075. for (var index = 0; index < this.cameras.length; index++) {
  3076. if (this.cameras[index].id === id) {
  3077. return this.cameras[index];
  3078. }
  3079. }
  3080. return null;
  3081. }
  3082. /**
  3083. * Gets a camera using its unique id
  3084. * @param uniqueId defines the unique id to look for
  3085. * @returns the camera or null if not found
  3086. */
  3087. public getCameraByUniqueID(uniqueId: number): Nullable<Camera> {
  3088. for (var index = 0; index < this.cameras.length; index++) {
  3089. if (this.cameras[index].uniqueId === uniqueId) {
  3090. return this.cameras[index];
  3091. }
  3092. }
  3093. return null;
  3094. }
  3095. /**
  3096. * Gets a camera using its name
  3097. * @param name defines the camera's name
  3098. * @return the camera or null if none found.
  3099. */
  3100. public getCameraByName(name: string): Nullable<Camera> {
  3101. for (var index = 0; index < this.cameras.length; index++) {
  3102. if (this.cameras[index].name === name) {
  3103. return this.cameras[index];
  3104. }
  3105. }
  3106. return null;
  3107. }
  3108. /**
  3109. * Gets a bone using its id
  3110. * @param id defines the bone's id
  3111. * @return the bone or null if not found
  3112. */
  3113. public getBoneByID(id: string): Nullable<Bone> {
  3114. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  3115. var skeleton = this.skeletons[skeletonIndex];
  3116. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  3117. if (skeleton.bones[boneIndex].id === id) {
  3118. return skeleton.bones[boneIndex];
  3119. }
  3120. }
  3121. }
  3122. return null;
  3123. }
  3124. /**
  3125. * Gets a bone using its id
  3126. * @param name defines the bone's name
  3127. * @return the bone or null if not found
  3128. */
  3129. public getBoneByName(name: string): Nullable<Bone> {
  3130. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  3131. var skeleton = this.skeletons[skeletonIndex];
  3132. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  3133. if (skeleton.bones[boneIndex].name === name) {
  3134. return skeleton.bones[boneIndex];
  3135. }
  3136. }
  3137. }
  3138. return null;
  3139. }
  3140. /**
  3141. * Gets a light node using its name
  3142. * @param name defines the the light's name
  3143. * @return the light or null if none found.
  3144. */
  3145. public getLightByName(name: string): Nullable<Light> {
  3146. for (var index = 0; index < this.lights.length; index++) {
  3147. if (this.lights[index].name === name) {
  3148. return this.lights[index];
  3149. }
  3150. }
  3151. return null;
  3152. }
  3153. /**
  3154. * Gets a light node using its id
  3155. * @param id defines the light's id
  3156. * @return the light or null if none found.
  3157. */
  3158. public getLightByID(id: string): Nullable<Light> {
  3159. for (var index = 0; index < this.lights.length; index++) {
  3160. if (this.lights[index].id === id) {
  3161. return this.lights[index];
  3162. }
  3163. }
  3164. return null;
  3165. }
  3166. /**
  3167. * Gets a light node using its scene-generated unique ID
  3168. * @param uniqueId defines the light's unique id
  3169. * @return the light or null if none found.
  3170. */
  3171. public getLightByUniqueID(uniqueId: number): Nullable<Light> {
  3172. for (var index = 0; index < this.lights.length; index++) {
  3173. if (this.lights[index].uniqueId === uniqueId) {
  3174. return this.lights[index];
  3175. }
  3176. }
  3177. return null;
  3178. }
  3179. /**
  3180. * Gets a particle system by id
  3181. * @param id defines the particle system id
  3182. * @return the corresponding system or null if none found
  3183. */
  3184. public getParticleSystemByID(id: string): Nullable<IParticleSystem> {
  3185. for (var index = 0; index < this.particleSystems.length; index++) {
  3186. if (this.particleSystems[index].id === id) {
  3187. return this.particleSystems[index];
  3188. }
  3189. }
  3190. return null;
  3191. }
  3192. /**
  3193. * Gets a geometry using its ID
  3194. * @param id defines the geometry's id
  3195. * @return the geometry or null if none found.
  3196. */
  3197. public getGeometryByID(id: string): Nullable<Geometry> {
  3198. for (var index = 0; index < this._geometries.length; index++) {
  3199. if (this._geometries[index].id === id) {
  3200. return this._geometries[index];
  3201. }
  3202. }
  3203. return null;
  3204. }
  3205. /**
  3206. * Add a new geometry to this scene
  3207. * @param geometry defines the geometry to be added to the scene.
  3208. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  3209. * @return a boolean defining if the geometry was added or not
  3210. */
  3211. public pushGeometry(geometry: Geometry, force?: boolean): boolean {
  3212. if (!force && this.getGeometryByID(geometry.id)) {
  3213. return false;
  3214. }
  3215. this._geometries.push(geometry);
  3216. //notify the collision coordinator
  3217. if (this.collisionCoordinator) {
  3218. this.collisionCoordinator.onGeometryAdded(geometry);
  3219. }
  3220. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  3221. return true;
  3222. }
  3223. /**
  3224. * Removes an existing geometry
  3225. * @param geometry defines the geometry to be removed from the scene
  3226. * @return a boolean defining if the geometry was removed or not
  3227. */
  3228. public removeGeometry(geometry: Geometry): boolean {
  3229. var index = this._geometries.indexOf(geometry);
  3230. if (index > -1) {
  3231. this._geometries.splice(index, 1);
  3232. //notify the collision coordinator
  3233. if (this.collisionCoordinator) {
  3234. this.collisionCoordinator.onGeometryDeleted(geometry);
  3235. }
  3236. this.onGeometryRemovedObservable.notifyObservers(geometry);
  3237. return true;
  3238. }
  3239. return false;
  3240. }
  3241. /**
  3242. * Gets the list of geometries attached to the scene
  3243. * @returns an array of Geometry
  3244. */
  3245. public getGeometries(): Geometry[] {
  3246. return this._geometries;
  3247. }
  3248. /**
  3249. * Gets the first added mesh found of a given ID
  3250. * @param id defines the id to search for
  3251. * @return the mesh found or null if not found at all
  3252. */
  3253. public getMeshByID(id: string): Nullable<AbstractMesh> {
  3254. for (var index = 0; index < this.meshes.length; index++) {
  3255. if (this.meshes[index].id === id) {
  3256. return this.meshes[index];
  3257. }
  3258. }
  3259. return null;
  3260. }
  3261. /**
  3262. * Gets a list of meshes using their id
  3263. * @param id defines the id to search for
  3264. * @returns a list of meshes
  3265. */
  3266. public getMeshesByID(id: string): Array<AbstractMesh> {
  3267. return this.meshes.filter(function (m) {
  3268. return m.id === id;
  3269. })
  3270. }
  3271. /**
  3272. * Gets the first added transform node found of a given ID
  3273. * @param id defines the id to search for
  3274. * @return the found transform node or null if not found at all.
  3275. */
  3276. public getTransformNodeByID(id: string): Nullable<TransformNode> {
  3277. for (var index = 0; index < this.transformNodes.length; index++) {
  3278. if (this.transformNodes[index].id === id) {
  3279. return this.transformNodes[index];
  3280. }
  3281. }
  3282. return null;
  3283. }
  3284. /**
  3285. * Gets a list of transform nodes using their id
  3286. * @param id defines the id to search for
  3287. * @returns a list of transform nodes
  3288. */
  3289. public getTransformNodesByID(id: string): Array<TransformNode> {
  3290. return this.transformNodes.filter(function (m) {
  3291. return m.id === id;
  3292. })
  3293. }
  3294. /**
  3295. * Gets a mesh with its auto-generated unique id
  3296. * @param uniqueId defines the unique id to search for
  3297. * @return the found mesh or null if not found at all.
  3298. */
  3299. public getMeshByUniqueID(uniqueId: number): Nullable<AbstractMesh> {
  3300. for (var index = 0; index < this.meshes.length; index++) {
  3301. if (this.meshes[index].uniqueId === uniqueId) {
  3302. return this.meshes[index];
  3303. }
  3304. }
  3305. return null;
  3306. }
  3307. /**
  3308. * Gets a the last added mesh using a given id
  3309. * @param id defines the id to search for
  3310. * @return the found mesh or null if not found at all.
  3311. */
  3312. public getLastMeshByID(id: string): Nullable<AbstractMesh> {
  3313. for (var index = this.meshes.length - 1; index >= 0; index--) {
  3314. if (this.meshes[index].id === id) {
  3315. return this.meshes[index];
  3316. }
  3317. }
  3318. return null;
  3319. }
  3320. /**
  3321. * Gets a the last added node (Mesh, Camera, Light) using a given id
  3322. * @param id defines the id to search for
  3323. * @return the found node or null if not found at all
  3324. */
  3325. public getLastEntryByID(id: string): Nullable<Node> {
  3326. var index: number;
  3327. for (index = this.meshes.length - 1; index >= 0; index--) {
  3328. if (this.meshes[index].id === id) {
  3329. return this.meshes[index];
  3330. }
  3331. }
  3332. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  3333. if (this.transformNodes[index].id === id) {
  3334. return this.transformNodes[index];
  3335. }
  3336. }
  3337. for (index = this.cameras.length - 1; index >= 0; index--) {
  3338. if (this.cameras[index].id === id) {
  3339. return this.cameras[index];
  3340. }
  3341. }
  3342. for (index = this.lights.length - 1; index >= 0; index--) {
  3343. if (this.lights[index].id === id) {
  3344. return this.lights[index];
  3345. }
  3346. }
  3347. return null;
  3348. }
  3349. /**
  3350. * Gets a node (Mesh, Camera, Light) using a given id
  3351. * @param id defines the id to search for
  3352. * @return the found node or null if not found at all
  3353. */
  3354. public getNodeByID(id: string): Nullable<Node> {
  3355. var mesh = this.getMeshByID(id);
  3356. if (mesh) {
  3357. return mesh;
  3358. }
  3359. var light = this.getLightByID(id);
  3360. if (light) {
  3361. return light;
  3362. }
  3363. var camera = this.getCameraByID(id);
  3364. if (camera) {
  3365. return camera;
  3366. }
  3367. var bone = this.getBoneByID(id);
  3368. return bone;
  3369. }
  3370. /**
  3371. * Gets a node (Mesh, Camera, Light) using a given name
  3372. * @param name defines the name to search for
  3373. * @return the found node or null if not found at all.
  3374. */
  3375. public getNodeByName(name: string): Nullable<Node> {
  3376. var mesh = this.getMeshByName(name);
  3377. if (mesh) {
  3378. return mesh;
  3379. }
  3380. var light = this.getLightByName(name);
  3381. if (light) {
  3382. return light;
  3383. }
  3384. var camera = this.getCameraByName(name);
  3385. if (camera) {
  3386. return camera;
  3387. }
  3388. var bone = this.getBoneByName(name);
  3389. return bone;
  3390. }
  3391. /**
  3392. * Gets a mesh using a given name
  3393. * @param name defines the name to search for
  3394. * @return the found mesh or null if not found at all.
  3395. */
  3396. public getMeshByName(name: string): Nullable<AbstractMesh> {
  3397. for (var index = 0; index < this.meshes.length; index++) {
  3398. if (this.meshes[index].name === name) {
  3399. return this.meshes[index];
  3400. }
  3401. }
  3402. return null;
  3403. }
  3404. /**
  3405. * Gets a transform node using a given name
  3406. * @param name defines the name to search for
  3407. * @return the found transform node or null if not found at all.
  3408. */
  3409. public getTransformNodeByName(name: string): Nullable<TransformNode> {
  3410. for (var index = 0; index < this.transformNodes.length; index++) {
  3411. if (this.transformNodes[index].name === name) {
  3412. return this.transformNodes[index];
  3413. }
  3414. }
  3415. return null;
  3416. }
  3417. /**
  3418. * Gets a sound using a given name
  3419. * @param name defines the name to search for
  3420. * @return the found sound or null if not found at all.
  3421. */
  3422. public getSoundByName(name: string): Nullable<Sound> {
  3423. var index: number;
  3424. if (AudioEngine) {
  3425. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  3426. if (this.mainSoundTrack.soundCollection[index].name === name) {
  3427. return this.mainSoundTrack.soundCollection[index];
  3428. }
  3429. }
  3430. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  3431. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  3432. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  3433. return this.soundTracks[sdIndex].soundCollection[index];
  3434. }
  3435. }
  3436. }
  3437. }
  3438. return null;
  3439. }
  3440. /**
  3441. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  3442. * @param id defines the id to search for
  3443. * @return the found skeleton or null if not found at all.
  3444. */
  3445. public getLastSkeletonByID(id: string): Nullable<Skeleton> {
  3446. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  3447. if (this.skeletons[index].id === id) {
  3448. return this.skeletons[index];
  3449. }
  3450. }
  3451. return null;
  3452. }
  3453. /**
  3454. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  3455. * @param id defines the id to search for
  3456. * @return the found skeleton or null if not found at all.
  3457. */
  3458. public getSkeletonById(id: string): Nullable<Skeleton> {
  3459. for (var index = 0; index < this.skeletons.length; index++) {
  3460. if (this.skeletons[index].id === id) {
  3461. return this.skeletons[index];
  3462. }
  3463. }
  3464. return null;
  3465. }
  3466. /**
  3467. * Gets a skeleton using a given name
  3468. * @param name defines the name to search for
  3469. * @return the found skeleton or null if not found at all.
  3470. */
  3471. public getSkeletonByName(name: string): Nullable<Skeleton> {
  3472. for (var index = 0; index < this.skeletons.length; index++) {
  3473. if (this.skeletons[index].name === name) {
  3474. return this.skeletons[index];
  3475. }
  3476. }
  3477. return null;
  3478. }
  3479. /**
  3480. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  3481. * @param id defines the id to search for
  3482. * @return the found morph target manager or null if not found at all.
  3483. */
  3484. public getMorphTargetManagerById(id: number): Nullable<MorphTargetManager> {
  3485. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  3486. if (this.morphTargetManagers[index].uniqueId === id) {
  3487. return this.morphTargetManagers[index];
  3488. }
  3489. }
  3490. return null;
  3491. }
  3492. /**
  3493. * Gets a boolean indicating if the given mesh is active
  3494. * @param mesh defines the mesh to look for
  3495. * @returns true if the mesh is in the active list
  3496. */
  3497. public isActiveMesh(mesh: AbstractMesh): boolean {
  3498. return (this._activeMeshes.indexOf(mesh) !== -1);
  3499. }
  3500. /**
  3501. * Return a the first highlight layer of the scene with a given name.
  3502. * @param name The name of the highlight layer to look for.
  3503. * @return The highlight layer if found otherwise null.
  3504. */
  3505. public getHighlightLayerByName(name: string): Nullable<HighlightLayer> {
  3506. for (var index = 0; index < this.effectLayers.length; index++) {
  3507. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  3508. return (<any>this.effectLayers[index]) as HighlightLayer;
  3509. }
  3510. }
  3511. return null;
  3512. }
  3513. /**
  3514. * Return a the first highlight layer of the scene with a given name.
  3515. * @param name The name of the highlight layer to look for.
  3516. * @return The highlight layer if found otherwise null.
  3517. */
  3518. public getGlowLayerByName(name: string): Nullable<GlowLayer> {
  3519. for (var index = 0; index < this.effectLayers.length; index++) {
  3520. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  3521. return (<any>this.effectLayers[index]) as GlowLayer;
  3522. }
  3523. }
  3524. return null;
  3525. }
  3526. /**
  3527. * Return a unique id as a string which can serve as an identifier for the scene
  3528. */
  3529. public get uid(): string {
  3530. if (!this._uid) {
  3531. this._uid = Tools.RandomId();
  3532. }
  3533. return this._uid;
  3534. }
  3535. /**
  3536. * Add an externaly attached data from its key.
  3537. * This method call will fail and return false, if such key already exists.
  3538. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  3539. * @param key the unique key that identifies the data
  3540. * @param data the data object to associate to the key for this Engine instance
  3541. * @return true if no such key were already present and the data was added successfully, false otherwise
  3542. */
  3543. public addExternalData<T>(key: string, data: T): boolean {
  3544. if (!this._externalData) {
  3545. this._externalData = new StringDictionary<Object>();
  3546. }
  3547. return this._externalData.add(key, data);
  3548. }
  3549. /**
  3550. * Get an externaly attached data from its key
  3551. * @param key the unique key that identifies the data
  3552. * @return the associated data, if present (can be null), or undefined if not present
  3553. */
  3554. public getExternalData<T>(key: string): Nullable<T> {
  3555. if (!this._externalData) {
  3556. return null;
  3557. }
  3558. return <T>this._externalData.get(key);
  3559. }
  3560. /**
  3561. * Get an externaly attached data from its key, create it using a factory if it's not already present
  3562. * @param key the unique key that identifies the data
  3563. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  3564. * @return the associated data, can be null if the factory returned null.
  3565. */
  3566. public getOrAddExternalDataWithFactory<T>(key: string, factory: (k: string) => T): T {
  3567. if (!this._externalData) {
  3568. this._externalData = new StringDictionary<Object>();
  3569. }
  3570. return <T>this._externalData.getOrAddWithFactory(key, factory);
  3571. }
  3572. /**
  3573. * Remove an externaly attached data from the Engine instance
  3574. * @param key the unique key that identifies the data
  3575. * @return true if the data was successfully removed, false if it doesn't exist
  3576. */
  3577. public removeExternalData(key: string): boolean {
  3578. return this._externalData.remove(key);
  3579. }
  3580. private _evaluateSubMesh(subMesh: SubMesh, mesh: AbstractMesh): void {
  3581. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  3582. if (mesh.showSubMeshesBoundingBox) {
  3583. const boundingInfo = subMesh.getBoundingInfo();
  3584. if (boundingInfo !== null && boundingInfo !== undefined) {
  3585. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  3586. }
  3587. }
  3588. const material = subMesh.getMaterial();
  3589. if (material !== null && material !== undefined) {
  3590. // Render targets
  3591. if (material.getRenderTargetTextures !== undefined) {
  3592. if (this._processedMaterials.indexOf(material) === -1) {
  3593. this._processedMaterials.push(material);
  3594. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  3595. }
  3596. }
  3597. // Dispatch
  3598. this._activeIndices.addCount(subMesh.indexCount, false);
  3599. this._renderingManager.dispatch(subMesh, mesh, material);
  3600. }
  3601. }
  3602. }
  3603. /**
  3604. * Clear the processed materials smart array preventing retention point in material dispose.
  3605. */
  3606. public freeProcessedMaterials(): void {
  3607. this._processedMaterials.dispose();
  3608. }
  3609. /**
  3610. * Clear the active meshes smart array preventing retention point in mesh dispose.
  3611. */
  3612. public freeActiveMeshes(): void {
  3613. this._activeMeshes.dispose();
  3614. if (this.activeCamera && this.activeCamera._activeMeshes) {
  3615. this.activeCamera._activeMeshes.dispose();
  3616. }
  3617. if (this.activeCameras) {
  3618. for (let i = 0; i < this.activeCameras.length; i++) {
  3619. let activeCamera = this.activeCameras[i];
  3620. if (activeCamera && activeCamera._activeMeshes) {
  3621. activeCamera._activeMeshes.dispose();
  3622. }
  3623. }
  3624. }
  3625. }
  3626. /**
  3627. * Clear the info related to rendering groups preventing retention points during dispose.
  3628. */
  3629. public freeRenderingGroups(): void {
  3630. if (this._renderingManager) {
  3631. this._renderingManager.freeRenderingGroups();
  3632. }
  3633. if (this.textures) {
  3634. for (let i = 0; i < this.textures.length; i++) {
  3635. let texture = this.textures[i];
  3636. if (texture && (<RenderTargetTexture>texture).renderList) {
  3637. (<RenderTargetTexture>texture).freeRenderingGroups();
  3638. }
  3639. }
  3640. }
  3641. }
  3642. /** @hidden */
  3643. public _isInIntermediateRendering(): boolean {
  3644. return this._intermediateRendering
  3645. }
  3646. private _activeMeshCandidateProvider: IActiveMeshCandidateProvider;
  3647. /**
  3648. * Defines the current active mesh candidate provider
  3649. * @param provider defines the provider to use
  3650. */
  3651. public setActiveMeshCandidateProvider(provider: IActiveMeshCandidateProvider): void {
  3652. this._activeMeshCandidateProvider = provider;
  3653. }
  3654. /**
  3655. * Gets the current active mesh candidate provider
  3656. * @returns the current active mesh candidate provider
  3657. */
  3658. public getActiveMeshCandidateProvider(): IActiveMeshCandidateProvider {
  3659. return this._activeMeshCandidateProvider;
  3660. }
  3661. private _activeMeshesFrozen = false;
  3662. /**
  3663. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  3664. * @returns the current scene
  3665. */
  3666. public freezeActiveMeshes(): Scene {
  3667. if (!this.activeCamera) {
  3668. return this;
  3669. }
  3670. if (!this._frustumPlanes) {
  3671. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  3672. }
  3673. this._evaluateActiveMeshes();
  3674. this._activeMeshesFrozen = true;
  3675. return this;
  3676. }
  3677. /**
  3678. * Use this function to restart evaluating active meshes on every frame
  3679. * @returns the current scene
  3680. */
  3681. public unfreezeActiveMeshes(): Scene {
  3682. this._activeMeshesFrozen = false;
  3683. return this;
  3684. }
  3685. private _evaluateActiveMeshes(): void {
  3686. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  3687. return;
  3688. }
  3689. if (!this.activeCamera) {
  3690. return;
  3691. }
  3692. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  3693. this.activeCamera._activeMeshes.reset();
  3694. this._activeMeshes.reset();
  3695. this._renderingManager.reset();
  3696. this._processedMaterials.reset();
  3697. this._activeParticleSystems.reset();
  3698. this._activeSkeletons.reset();
  3699. this._softwareSkinnedMeshes.reset();
  3700. if (this._boundingBoxRenderer) {
  3701. this._boundingBoxRenderer.reset();
  3702. }
  3703. // Meshes
  3704. var meshes: AbstractMesh[];
  3705. var len: number;
  3706. var checkIsEnabled = true;
  3707. // Determine mesh candidates
  3708. if (this._activeMeshCandidateProvider !== undefined) {
  3709. // Use _activeMeshCandidateProvider
  3710. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  3711. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  3712. if (meshes !== undefined) {
  3713. len = meshes.length;
  3714. } else {
  3715. len = 0;
  3716. }
  3717. } else if (this._selectionOctree !== undefined) {
  3718. // Octree
  3719. var selection = this._selectionOctree.select(this._frustumPlanes);
  3720. meshes = selection.data;
  3721. len = selection.length;
  3722. } else {
  3723. // Full scene traversal
  3724. len = this.meshes.length;
  3725. meshes = this.meshes;
  3726. }
  3727. // Check each mesh
  3728. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  3729. mesh = meshes[meshIndex];
  3730. if (mesh.isBlocked) {
  3731. continue;
  3732. }
  3733. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  3734. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  3735. continue;
  3736. }
  3737. mesh.computeWorldMatrix();
  3738. // Intersections
  3739. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([ActionManager.OnIntersectionEnterTrigger, ActionManager.OnIntersectionExitTrigger])) {
  3740. this._meshesForIntersections.pushNoDuplicate(mesh);
  3741. }
  3742. // Switch to current LOD
  3743. meshLOD = mesh.getLOD(this.activeCamera);
  3744. if (meshLOD === undefined || meshLOD === null) {
  3745. continue;
  3746. }
  3747. mesh._preActivate();
  3748. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  3749. this._activeMeshes.push(mesh);
  3750. this.activeCamera._activeMeshes.push(mesh);
  3751. mesh._activate(this._renderId);
  3752. if (meshLOD !== mesh) {
  3753. meshLOD._activate(this._renderId);
  3754. }
  3755. this._activeMesh(mesh, meshLOD);
  3756. }
  3757. }
  3758. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  3759. // Particle systems
  3760. if (this.particlesEnabled) {
  3761. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  3762. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  3763. var particleSystem = this.particleSystems[particleIndex];
  3764. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  3765. continue;
  3766. }
  3767. let emitter = <any>particleSystem.emitter;
  3768. if (!emitter.position || emitter.isEnabled()) {
  3769. this._activeParticleSystems.push(particleSystem);
  3770. particleSystem.animate();
  3771. this._renderingManager.dispatchParticles(particleSystem);
  3772. }
  3773. }
  3774. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  3775. }
  3776. }
  3777. private _activeMesh(sourceMesh: AbstractMesh, mesh: AbstractMesh): void {
  3778. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  3779. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  3780. mesh.skeleton.prepare();
  3781. }
  3782. if (!mesh.computeBonesUsingShaders) {
  3783. this._softwareSkinnedMeshes.pushNoDuplicate(<Mesh>mesh);
  3784. }
  3785. }
  3786. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  3787. let boundingInfo = sourceMesh.getBoundingInfo();
  3788. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  3789. }
  3790. if (
  3791. mesh !== undefined && mesh !== null
  3792. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0
  3793. ) {
  3794. // Submeshes Octrees
  3795. var len: number;
  3796. var subMeshes: SubMesh[];
  3797. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  3798. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  3799. len = intersections.length;
  3800. subMeshes = intersections.data;
  3801. } else {
  3802. subMeshes = mesh.subMeshes;
  3803. len = subMeshes.length;
  3804. }
  3805. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  3806. subMesh = subMeshes[subIndex];
  3807. this._evaluateSubMesh(subMesh, mesh);
  3808. }
  3809. }
  3810. }
  3811. /**
  3812. * Update the transform matrix to update from the current active camera
  3813. * @param force defines a boolean used to force the update even if cache is up to date
  3814. */
  3815. public updateTransformMatrix(force?: boolean): void {
  3816. if (!this.activeCamera) {
  3817. return;
  3818. }
  3819. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  3820. }
  3821. /**
  3822. * Defines an alternate camera (used mostly in VR-like scenario where two cameras can render the same scene from a slightly different point of view)
  3823. * @param alternateCamera defines the camera to use
  3824. */
  3825. public updateAlternateTransformMatrix(alternateCamera: Camera): void {
  3826. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  3827. }
  3828. private _renderForCamera(camera: Camera, rigParent?: Camera): void {
  3829. if (camera && camera._skipRendering) {
  3830. return;
  3831. }
  3832. var engine = this._engine;
  3833. this.activeCamera = camera;
  3834. if (!this.activeCamera)
  3835. throw new Error("Active camera not set");
  3836. Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  3837. // Viewport
  3838. engine.setViewport(this.activeCamera.viewport);
  3839. // Camera
  3840. this.resetCachedMaterial();
  3841. this._renderId++;
  3842. this.updateTransformMatrix();
  3843. if (camera._alternateCamera) {
  3844. this.updateAlternateTransformMatrix(camera._alternateCamera);
  3845. this._alternateRendering = true;
  3846. }
  3847. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  3848. // Meshes
  3849. this._evaluateActiveMeshes();
  3850. // Software skinning
  3851. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  3852. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  3853. mesh.applySkeleton(<Skeleton>mesh.skeleton);
  3854. }
  3855. // Render targets
  3856. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  3857. var needsRestoreFrameBuffer = false;
  3858. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  3859. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  3860. }
  3861. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  3862. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  3863. }
  3864. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  3865. this._intermediateRendering = true;
  3866. Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  3867. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  3868. let renderTarget = this._renderTargets.data[renderIndex];
  3869. if (renderTarget._shouldRender()) {
  3870. this._renderId++;
  3871. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  3872. renderTarget.render((<boolean>hasSpecialRenderTargetCamera), this.dumpNextRenderTargets);
  3873. }
  3874. }
  3875. Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  3876. this._intermediateRendering = false;
  3877. this._renderId++;
  3878. needsRestoreFrameBuffer = true; // Restore back buffer
  3879. }
  3880. // Render EffecttLayer Texture
  3881. var stencilState = this._engine.getStencilBuffer();
  3882. var renderEffects = false;
  3883. var needStencil = false;
  3884. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  3885. this._intermediateRendering = true;
  3886. for (let i = 0; i < this.effectLayers.length; i++) {
  3887. let effectLayer = this.effectLayers[i];
  3888. if (effectLayer.shouldRender() &&
  3889. (!effectLayer.camera ||
  3890. (effectLayer.camera.cameraRigMode === Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  3891. (effectLayer.camera.cameraRigMode !== Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  3892. renderEffects = true;
  3893. needStencil = needStencil || effectLayer.needStencil();
  3894. let renderTarget = (<RenderTargetTexture>(<any>effectLayer)._mainTexture);
  3895. if (renderTarget._shouldRender()) {
  3896. this._renderId++;
  3897. renderTarget.render(false, false);
  3898. needsRestoreFrameBuffer = true;
  3899. }
  3900. }
  3901. }
  3902. this._intermediateRendering = false;
  3903. this._renderId++;
  3904. }
  3905. if (needsRestoreFrameBuffer) {
  3906. engine.restoreDefaultFramebuffer(); // Restore back buffer
  3907. }
  3908. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  3909. // Prepare Frame
  3910. if (this.postProcessManager) {
  3911. this.postProcessManager._prepareFrame();
  3912. }
  3913. // Backgrounds
  3914. var layerIndex;
  3915. var layer;
  3916. if (this.layers.length) {
  3917. engine.setDepthBuffer(false);
  3918. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  3919. layer = this.layers[layerIndex];
  3920. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  3921. layer.render();
  3922. }
  3923. }
  3924. engine.setDepthBuffer(true);
  3925. }
  3926. // Activate effect Layer stencil
  3927. if (needStencil) {
  3928. this._engine.setStencilBuffer(true);
  3929. }
  3930. // Render
  3931. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  3932. this._renderingManager.render(null, null, true, true);
  3933. this.onAfterDrawPhaseObservable.notifyObservers(this);
  3934. // Restore effect Layer stencil
  3935. if (needStencil) {
  3936. this._engine.setStencilBuffer(stencilState);
  3937. }
  3938. // Bounding boxes
  3939. if (this._boundingBoxRenderer) {
  3940. this._boundingBoxRenderer.render();
  3941. }
  3942. // Lens flares
  3943. if (this.lensFlaresEnabled) {
  3944. Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  3945. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  3946. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  3947. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  3948. lensFlareSystem.render();
  3949. }
  3950. }
  3951. Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  3952. }
  3953. // Effect Layer
  3954. if (renderEffects) {
  3955. engine.setDepthBuffer(false);
  3956. for (let i = 0; i < this.effectLayers.length; i++) {
  3957. if (this.effectLayers[i].shouldRender()) {
  3958. this.effectLayers[i].render();
  3959. }
  3960. }
  3961. engine.setDepthBuffer(true);
  3962. }
  3963. // Foregrounds
  3964. if (this.layers.length) {
  3965. engine.setDepthBuffer(false);
  3966. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  3967. layer = this.layers[layerIndex];
  3968. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  3969. layer.render();
  3970. }
  3971. }
  3972. engine.setDepthBuffer(true);
  3973. }
  3974. // Finalize frame
  3975. if (this.postProcessManager) {
  3976. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  3977. }
  3978. // Reset some special arrays
  3979. this._renderTargets.reset();
  3980. this._alternateRendering = false;
  3981. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  3982. Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  3983. }
  3984. private _processSubCameras(camera: Camera): void {
  3985. if (camera.cameraRigMode === Camera.RIG_MODE_NONE) {
  3986. this._renderForCamera(camera);
  3987. return;
  3988. }
  3989. // rig cameras
  3990. for (var index = 0; index < camera._rigCameras.length; index++) {
  3991. this._renderForCamera(camera._rigCameras[index], camera);
  3992. }
  3993. this.activeCamera = camera;
  3994. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  3995. }
  3996. private _checkIntersections(): void {
  3997. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  3998. var sourceMesh = this._meshesForIntersections.data[index];
  3999. if (!sourceMesh.actionManager) {
  4000. continue;
  4001. }
  4002. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  4003. var action = sourceMesh.actionManager.actions[actionIndex];
  4004. if (action.trigger === ActionManager.OnIntersectionEnterTrigger || action.trigger === ActionManager.OnIntersectionExitTrigger) {
  4005. var parameters = action.getTriggerParameter();
  4006. var otherMesh = parameters instanceof AbstractMesh ? parameters : parameters.mesh;
  4007. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  4008. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  4009. if (areIntersecting && currentIntersectionInProgress === -1) {
  4010. if (action.trigger === ActionManager.OnIntersectionEnterTrigger) {
  4011. action._executeCurrent(ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  4012. sourceMesh._intersectionsInProgress.push(otherMesh);
  4013. } else if (action.trigger === ActionManager.OnIntersectionExitTrigger) {
  4014. sourceMesh._intersectionsInProgress.push(otherMesh);
  4015. }
  4016. } else if (!areIntersecting && currentIntersectionInProgress > -1) {
  4017. //They intersected, and now they don't.
  4018. //is this trigger an exit trigger? execute an event.
  4019. if (action.trigger === ActionManager.OnIntersectionExitTrigger) {
  4020. action._executeCurrent(ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  4021. }
  4022. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  4023. if (!sourceMesh.actionManager.hasSpecificTrigger(ActionManager.OnIntersectionExitTrigger, parameter => {
  4024. var parameterMesh = parameter instanceof AbstractMesh ? parameter : parameter.mesh;
  4025. return otherMesh === parameterMesh;
  4026. }) || action.trigger === ActionManager.OnIntersectionExitTrigger) {
  4027. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  4028. }
  4029. }
  4030. }
  4031. }
  4032. }
  4033. }
  4034. /**
  4035. * Render the scene
  4036. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  4037. */
  4038. public render(updateCameras = true): void {
  4039. if (this.isDisposed) {
  4040. return;
  4041. }
  4042. this._activeParticles.fetchNewFrame();
  4043. this._totalVertices.fetchNewFrame();
  4044. this._activeIndices.fetchNewFrame();
  4045. this._activeBones.fetchNewFrame();
  4046. this._meshesForIntersections.reset();
  4047. this.resetCachedMaterial();
  4048. this.onBeforeAnimationsObservable.notifyObservers(this);
  4049. // Actions
  4050. if (this.actionManager) {
  4051. this.actionManager.processTrigger(ActionManager.OnEveryFrameTrigger);
  4052. }
  4053. //Simplification Queue
  4054. if (this.simplificationQueue && !this.simplificationQueue.running) {
  4055. this.simplificationQueue.executeNext();
  4056. }
  4057. if (this._engine.isDeterministicLockStep()) {
  4058. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  4059. var defaultFPS = (60.0 / 1000.0);
  4060. let defaultFrameTime = 1000 / 60; // frame time in MS
  4061. if (this._physicsEngine) {
  4062. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  4063. }
  4064. let stepsTaken = 0;
  4065. var maxSubSteps = this._engine.getLockstepMaxSteps();
  4066. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  4067. internalSteps = Math.min(internalSteps, maxSubSteps);
  4068. do {
  4069. this.onBeforeStepObservable.notifyObservers(this);
  4070. // Animations
  4071. this._animationRatio = defaultFrameTime * defaultFPS;
  4072. this._animate();
  4073. this.onAfterAnimationsObservable.notifyObservers(this);
  4074. // Physics
  4075. if (this._physicsEngine) {
  4076. this.onBeforePhysicsObservable.notifyObservers(this);
  4077. this._physicsEngine._step(defaultFrameTime / 1000);
  4078. this.onAfterPhysicsObservable.notifyObservers(this);
  4079. }
  4080. this.onAfterStepObservable.notifyObservers(this);
  4081. this._currentStepId++;
  4082. stepsTaken++;
  4083. deltaTime -= defaultFrameTime;
  4084. } while (deltaTime > 0 && stepsTaken < internalSteps);
  4085. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  4086. }
  4087. else {
  4088. // Animations
  4089. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  4090. this._animationRatio = deltaTime * (60.0 / 1000.0);
  4091. this._animate();
  4092. this.onAfterAnimationsObservable.notifyObservers(this);
  4093. // Physics
  4094. if (this._physicsEngine) {
  4095. this.onBeforePhysicsObservable.notifyObservers(this);
  4096. this._physicsEngine._step(deltaTime / 1000.0);
  4097. this.onAfterPhysicsObservable.notifyObservers(this);
  4098. }
  4099. }
  4100. // update gamepad manager
  4101. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  4102. this._gamepadManager._checkGamepadsStatus();
  4103. }
  4104. // Update Cameras
  4105. if (updateCameras) {
  4106. if (this.activeCameras.length > 0) {
  4107. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  4108. let camera = this.activeCameras[cameraIndex];
  4109. camera.update();
  4110. if (camera.cameraRigMode !== Camera.RIG_MODE_NONE) {
  4111. // rig cameras
  4112. for (var index = 0; index < camera._rigCameras.length; index++) {
  4113. camera._rigCameras[index].update();
  4114. }
  4115. }
  4116. }
  4117. } else if (this.activeCamera) {
  4118. this.activeCamera.update();
  4119. if (this.activeCamera.cameraRigMode !== Camera.RIG_MODE_NONE) {
  4120. // rig cameras
  4121. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  4122. this.activeCamera._rigCameras[index].update();
  4123. }
  4124. }
  4125. }
  4126. }
  4127. // Before render
  4128. this.onBeforeRenderObservable.notifyObservers(this);
  4129. // Customs render targets
  4130. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  4131. var engine = this.getEngine();
  4132. var currentActiveCamera = this.activeCamera;
  4133. if (this.renderTargetsEnabled) {
  4134. Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  4135. this._intermediateRendering = true;
  4136. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  4137. var renderTarget = this.customRenderTargets[customIndex];
  4138. if (renderTarget._shouldRender()) {
  4139. this._renderId++;
  4140. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  4141. if (!this.activeCamera)
  4142. throw new Error("Active camera not set");
  4143. // Viewport
  4144. engine.setViewport(this.activeCamera.viewport);
  4145. // Camera
  4146. this.updateTransformMatrix();
  4147. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  4148. }
  4149. }
  4150. Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  4151. this._intermediateRendering = false;
  4152. this._renderId++;
  4153. }
  4154. // Restore back buffer
  4155. if (this.customRenderTargets.length > 0) {
  4156. engine.restoreDefaultFramebuffer();
  4157. }
  4158. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  4159. this.activeCamera = currentActiveCamera;
  4160. // Procedural textures
  4161. if (this.proceduralTexturesEnabled) {
  4162. Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  4163. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  4164. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  4165. if (proceduralTexture._shouldRender()) {
  4166. proceduralTexture.render();
  4167. }
  4168. }
  4169. Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  4170. }
  4171. // Clear
  4172. if (this.autoClearDepthAndStencil || this.autoClear) {
  4173. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  4174. }
  4175. // Shadows
  4176. if (this.shadowsEnabled) {
  4177. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  4178. var light = this.lights[lightIndex];
  4179. var shadowGenerator = light.getShadowGenerator();
  4180. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  4181. var shadowMap = <RenderTargetTexture>(shadowGenerator.getShadowMap());
  4182. if (this.textures.indexOf(shadowMap) !== -1) {
  4183. this._renderTargets.push(shadowMap);
  4184. }
  4185. }
  4186. }
  4187. }
  4188. // Depth renderer
  4189. for (var key in this._depthRenderer) {
  4190. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  4191. }
  4192. // Geometry renderer
  4193. if (this._geometryBufferRenderer) {
  4194. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  4195. }
  4196. // RenderPipeline
  4197. if (this._postProcessRenderPipelineManager) {
  4198. this._postProcessRenderPipelineManager.update();
  4199. }
  4200. // Multi-cameras?
  4201. if (this.activeCameras.length > 0) {
  4202. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  4203. if (cameraIndex > 0) {
  4204. this._engine.clear(null, false, true, true);
  4205. }
  4206. this._processSubCameras(this.activeCameras[cameraIndex]);
  4207. }
  4208. } else {
  4209. if (!this.activeCamera) {
  4210. throw new Error("No camera defined");
  4211. }
  4212. this._processSubCameras(this.activeCamera);
  4213. }
  4214. // Intersection checks
  4215. this._checkIntersections();
  4216. // Update the audio listener attached to the camera
  4217. if (AudioEngine) {
  4218. this._updateAudioParameters();
  4219. }
  4220. // After render
  4221. if (this.afterRender) {
  4222. this.afterRender();
  4223. }
  4224. this.onAfterRenderObservable.notifyObservers(this);
  4225. // Cleaning
  4226. for (var index = 0; index < this._toBeDisposed.length; index++) {
  4227. var data = this._toBeDisposed.data[index];
  4228. if (data) {
  4229. data.dispose();
  4230. }
  4231. this._toBeDisposed[index] = null;
  4232. }
  4233. this._toBeDisposed.reset();
  4234. if (this.dumpNextRenderTargets) {
  4235. this.dumpNextRenderTargets = false;
  4236. }
  4237. this._activeBones.addCount(0, true);
  4238. this._activeIndices.addCount(0, true);
  4239. this._activeParticles.addCount(0, true);
  4240. }
  4241. private _updateAudioParameters() {
  4242. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  4243. return;
  4244. }
  4245. var listeningCamera: Nullable<Camera>;
  4246. var audioEngine = Engine.audioEngine;
  4247. if (this.activeCameras.length > 0) {
  4248. listeningCamera = this.activeCameras[0];
  4249. } else {
  4250. listeningCamera = this.activeCamera;
  4251. }
  4252. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  4253. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  4254. // for VR cameras
  4255. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  4256. listeningCamera = listeningCamera.rigCameras[0];
  4257. }
  4258. var mat = Matrix.Invert(listeningCamera.getViewMatrix());
  4259. var cameraDirection = Vector3.TransformNormal(new Vector3(0, 0, -1), mat);
  4260. cameraDirection.normalize();
  4261. // To avoid some errors on GearVR
  4262. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  4263. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  4264. }
  4265. var i: number;
  4266. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  4267. var sound = this.mainSoundTrack.soundCollection[i];
  4268. if (sound.useCustomAttenuation) {
  4269. sound.updateDistanceFromListener();
  4270. }
  4271. }
  4272. for (i = 0; i < this.soundTracks.length; i++) {
  4273. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  4274. sound = this.soundTracks[i].soundCollection[j];
  4275. if (sound.useCustomAttenuation) {
  4276. sound.updateDistanceFromListener();
  4277. }
  4278. }
  4279. }
  4280. }
  4281. }
  4282. // Audio
  4283. /**
  4284. * Gets or sets if audio support is enabled
  4285. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  4286. */
  4287. public get audioEnabled(): boolean {
  4288. return this._audioEnabled;
  4289. }
  4290. public set audioEnabled(value: boolean) {
  4291. this._audioEnabled = value;
  4292. if (AudioEngine) {
  4293. if (this._audioEnabled) {
  4294. this._enableAudio();
  4295. }
  4296. else {
  4297. this._disableAudio();
  4298. }
  4299. }
  4300. }
  4301. private _disableAudio() {
  4302. var i: number;
  4303. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  4304. this.mainSoundTrack.soundCollection[i].pause();
  4305. }
  4306. for (i = 0; i < this.soundTracks.length; i++) {
  4307. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  4308. this.soundTracks[i].soundCollection[j].pause();
  4309. }
  4310. }
  4311. }
  4312. private _enableAudio() {
  4313. var i: number;
  4314. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  4315. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  4316. this.mainSoundTrack.soundCollection[i].play();
  4317. }
  4318. }
  4319. for (i = 0; i < this.soundTracks.length; i++) {
  4320. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  4321. if (this.soundTracks[i].soundCollection[j].isPaused) {
  4322. this.soundTracks[i].soundCollection[j].play();
  4323. }
  4324. }
  4325. }
  4326. }
  4327. /**
  4328. * Gets or sets if audio will be output to headphones
  4329. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  4330. */
  4331. public get headphone(): boolean {
  4332. return this._headphone;
  4333. }
  4334. public set headphone(value: boolean) {
  4335. this._headphone = value;
  4336. if (AudioEngine) {
  4337. if (this._headphone) {
  4338. this._switchAudioModeForHeadphones();
  4339. }
  4340. else {
  4341. this._switchAudioModeForNormalSpeakers();
  4342. }
  4343. }
  4344. }
  4345. private _switchAudioModeForHeadphones() {
  4346. this.mainSoundTrack.switchPanningModelToHRTF();
  4347. for (var i = 0; i < this.soundTracks.length; i++) {
  4348. this.soundTracks[i].switchPanningModelToHRTF();
  4349. }
  4350. }
  4351. private _switchAudioModeForNormalSpeakers() {
  4352. this.mainSoundTrack.switchPanningModelToEqualPower();
  4353. for (var i = 0; i < this.soundTracks.length; i++) {
  4354. this.soundTracks[i].switchPanningModelToEqualPower();
  4355. }
  4356. }
  4357. /**
  4358. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  4359. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  4360. * @returns the created depth renderer
  4361. */
  4362. public enableDepthRenderer(camera?: Nullable<Camera>): DepthRenderer {
  4363. camera = camera || this.activeCamera;
  4364. if (!camera) {
  4365. throw "No camera available to enable depth renderer";
  4366. }
  4367. if (!this._depthRenderer[camera.id]) {
  4368. var textureType = 0;
  4369. if (this._engine.getCaps().textureHalfFloatRender) {
  4370. textureType = Engine.TEXTURETYPE_HALF_FLOAT;
  4371. }
  4372. else if (this._engine.getCaps().textureFloatRender) {
  4373. textureType = Engine.TEXTURETYPE_FLOAT;
  4374. } else {
  4375. throw "Depth renderer does not support int texture type";
  4376. }
  4377. this._depthRenderer[camera.id] = new DepthRenderer(this, textureType, camera);
  4378. }
  4379. return this._depthRenderer[camera.id];
  4380. }
  4381. /**
  4382. * Disables a depth renderer for a given camera
  4383. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  4384. */
  4385. public disableDepthRenderer(camera?: Nullable<Camera>): void {
  4386. camera = camera || this.activeCamera;
  4387. if (!camera || !this._depthRenderer[camera.id]) {
  4388. return;
  4389. }
  4390. this._depthRenderer[camera.id].dispose();
  4391. delete this._depthRenderer[camera.id];
  4392. }
  4393. /**
  4394. * Enables a GeometryBufferRender and associates it with the scene
  4395. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  4396. * @returns the GeometryBufferRenderer
  4397. */
  4398. public enableGeometryBufferRenderer(ratio: number = 1): Nullable<GeometryBufferRenderer> {
  4399. if (this._geometryBufferRenderer) {
  4400. return this._geometryBufferRenderer;
  4401. }
  4402. this._geometryBufferRenderer = new GeometryBufferRenderer(this, ratio);
  4403. if (!this._geometryBufferRenderer.isSupported) {
  4404. this._geometryBufferRenderer = null;
  4405. }
  4406. return this._geometryBufferRenderer;
  4407. }
  4408. /**
  4409. * Disables the GeometryBufferRender associated with the scene
  4410. */
  4411. public disableGeometryBufferRenderer(): void {
  4412. if (!this._geometryBufferRenderer) {
  4413. return;
  4414. }
  4415. this._geometryBufferRenderer.dispose();
  4416. this._geometryBufferRenderer = null;
  4417. }
  4418. /**
  4419. * Freeze all materials
  4420. * A frozen material will not be updatable but should be faster to render
  4421. */
  4422. public freezeMaterials(): void {
  4423. for (var i = 0; i < this.materials.length; i++) {
  4424. this.materials[i].freeze();
  4425. }
  4426. }
  4427. /**
  4428. * Unfreeze all materials
  4429. * A frozen material will not be updatable but should be faster to render
  4430. */
  4431. public unfreezeMaterials(): void {
  4432. for (var i = 0; i < this.materials.length; i++) {
  4433. this.materials[i].unfreeze();
  4434. }
  4435. }
  4436. /**
  4437. * Releases all held ressources
  4438. */
  4439. public dispose(): void {
  4440. this.beforeRender = null;
  4441. this.afterRender = null;
  4442. this.skeletons = [];
  4443. this.morphTargetManagers = [];
  4444. this.importedMeshesFiles = new Array<string>();
  4445. this.stopAllAnimations();
  4446. this.resetCachedMaterial();
  4447. for (var key in this._depthRenderer) {
  4448. this._depthRenderer[key].dispose();
  4449. }
  4450. if (this._gamepadManager) {
  4451. this._gamepadManager.dispose();
  4452. this._gamepadManager = null;
  4453. }
  4454. // Smart arrays
  4455. if (this.activeCamera) {
  4456. this.activeCamera._activeMeshes.dispose();
  4457. this.activeCamera = null;
  4458. }
  4459. this._activeMeshes.dispose();
  4460. this._renderingManager.dispose();
  4461. this._processedMaterials.dispose();
  4462. this._activeParticleSystems.dispose();
  4463. this._activeSkeletons.dispose();
  4464. this._softwareSkinnedMeshes.dispose();
  4465. this._renderTargets.dispose();
  4466. this._registeredForLateAnimationBindings.dispose();
  4467. if (this._boundingBoxRenderer) {
  4468. this._boundingBoxRenderer.dispose();
  4469. }
  4470. this._meshesForIntersections.dispose();
  4471. this._toBeDisposed.dispose();
  4472. // Abort active requests
  4473. for (let request of this._activeRequests) {
  4474. request.abort();
  4475. }
  4476. // Debug layer
  4477. if (this._debugLayer) {
  4478. this._debugLayer.hide();
  4479. }
  4480. // Events
  4481. this.onDisposeObservable.notifyObservers(this);
  4482. this.onDisposeObservable.clear();
  4483. this.onBeforeRenderObservable.clear();
  4484. this.onAfterRenderObservable.clear();
  4485. this.onBeforeRenderTargetsRenderObservable.clear();
  4486. this.onAfterRenderTargetsRenderObservable.clear();
  4487. this.onAfterStepObservable.clear();
  4488. this.onBeforeStepObservable.clear();
  4489. this.onBeforeActiveMeshesEvaluationObservable.clear();
  4490. this.onAfterActiveMeshesEvaluationObservable.clear();
  4491. this.onBeforeParticlesRenderingObservable.clear();
  4492. this.onAfterParticlesRenderingObservable.clear();
  4493. this.onBeforeSpritesRenderingObservable.clear();
  4494. this.onAfterSpritesRenderingObservable.clear();
  4495. this.onBeforeDrawPhaseObservable.clear();
  4496. this.onAfterDrawPhaseObservable.clear();
  4497. this.onBeforePhysicsObservable.clear();
  4498. this.onAfterPhysicsObservable.clear();
  4499. this.onBeforeAnimationsObservable.clear();
  4500. this.onAfterAnimationsObservable.clear();
  4501. this.onDataLoadedObservable.clear();
  4502. this.detachControl();
  4503. // Release sounds & sounds tracks
  4504. if (AudioEngine) {
  4505. this.disposeSounds();
  4506. }
  4507. // VR Helper
  4508. if (this.VRHelper) {
  4509. this.VRHelper.dispose();
  4510. }
  4511. // Detach cameras
  4512. var canvas = this._engine.getRenderingCanvas();
  4513. if (canvas) {
  4514. var index;
  4515. for (index = 0; index < this.cameras.length; index++) {
  4516. this.cameras[index].detachControl(canvas);
  4517. }
  4518. }
  4519. // Release animation groups
  4520. while (this.animationGroups.length) {
  4521. this.animationGroups[0].dispose();
  4522. }
  4523. // Release lights
  4524. while (this.lights.length) {
  4525. this.lights[0].dispose();
  4526. }
  4527. // Release meshes
  4528. while (this.meshes.length) {
  4529. this.meshes[0].dispose(true);
  4530. }
  4531. while (this.transformNodes.length) {
  4532. this.removeTransformNode(this.transformNodes[0]);
  4533. }
  4534. // Release cameras
  4535. while (this.cameras.length) {
  4536. this.cameras[0].dispose();
  4537. }
  4538. // Release materials
  4539. if (this.defaultMaterial) {
  4540. this.defaultMaterial.dispose()
  4541. }
  4542. while (this.multiMaterials.length) {
  4543. this.multiMaterials[0].dispose();
  4544. }
  4545. while (this.materials.length) {
  4546. this.materials[0].dispose();
  4547. }
  4548. // Release particles
  4549. while (this.particleSystems.length) {
  4550. this.particleSystems[0].dispose();
  4551. }
  4552. // Release sprites
  4553. while (this.spriteManagers.length) {
  4554. this.spriteManagers[0].dispose();
  4555. }
  4556. // Release postProcesses
  4557. while (this.postProcesses.length) {
  4558. this.postProcesses[0].dispose();
  4559. }
  4560. // Release layers
  4561. while (this.layers.length) {
  4562. this.layers[0].dispose();
  4563. }
  4564. while (this.effectLayers.length) {
  4565. this.effectLayers[0].dispose();
  4566. }
  4567. // Release textures
  4568. while (this.textures.length) {
  4569. this.textures[0].dispose();
  4570. }
  4571. // Release UBO
  4572. this._sceneUbo.dispose();
  4573. if (this._alternateSceneUbo) {
  4574. this._alternateSceneUbo.dispose();
  4575. }
  4576. // Post-processes
  4577. this.postProcessManager.dispose();
  4578. if (this._postProcessRenderPipelineManager) {
  4579. this._postProcessRenderPipelineManager.dispose();
  4580. }
  4581. // Physics
  4582. if (this._physicsEngine) {
  4583. this.disablePhysicsEngine();
  4584. }
  4585. // Remove from engine
  4586. index = this._engine.scenes.indexOf(this);
  4587. if (index > -1) {
  4588. this._engine.scenes.splice(index, 1);
  4589. }
  4590. this._engine.wipeCaches(true);
  4591. this._isDisposed = true;
  4592. }
  4593. /**
  4594. * Gets if the scene is already disposed
  4595. */
  4596. public get isDisposed(): boolean {
  4597. return this._isDisposed;
  4598. }
  4599. /**
  4600. * Releases sounds & soundtracks
  4601. */
  4602. public disposeSounds() {
  4603. if (!this._mainSoundTrack) {
  4604. return;
  4605. }
  4606. this.mainSoundTrack.dispose();
  4607. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  4608. this.soundTracks[scIndex].dispose();
  4609. }
  4610. }
  4611. /**
  4612. * Call this function to reduce memory footprint of the scene.
  4613. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  4614. */
  4615. public clearCachedVertexData(): void {
  4616. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  4617. var mesh = this.meshes[meshIndex];
  4618. var geometry = (<Mesh>mesh).geometry;
  4619. if (geometry) {
  4620. geometry._indices = [];
  4621. for (var vbName in geometry._vertexBuffers) {
  4622. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  4623. continue;
  4624. }
  4625. geometry._vertexBuffers[vbName]._buffer._data = null;
  4626. }
  4627. }
  4628. }
  4629. }
  4630. /**
  4631. * This function will remove the local cached buffer data from texture.
  4632. * It will save memory but will prevent the texture from being rebuilt
  4633. */
  4634. public cleanCachedTextureBuffer(): void {
  4635. for (var baseTexture of this.textures) {
  4636. let buffer = (<Texture>baseTexture)._buffer;
  4637. if (buffer) {
  4638. (<Texture>baseTexture)._buffer = null;
  4639. }
  4640. }
  4641. }
  4642. // Octrees
  4643. /**
  4644. * Get the world extend vectors with an optional filter
  4645. *
  4646. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  4647. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  4648. */
  4649. public getWorldExtends(filterPredicate?: (mesh: AbstractMesh) => boolean): { min: Vector3; max: Vector3 } {
  4650. var min = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4651. var max = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4652. filterPredicate = filterPredicate || (() => true);
  4653. this.meshes.filter(filterPredicate).forEach(mesh => {
  4654. mesh.computeWorldMatrix(true);
  4655. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  4656. return;
  4657. }
  4658. let boundingInfo = mesh.getBoundingInfo();
  4659. var minBox = boundingInfo.boundingBox.minimumWorld;
  4660. var maxBox = boundingInfo.boundingBox.maximumWorld;
  4661. Tools.CheckExtends(minBox, min, max);
  4662. Tools.CheckExtends(maxBox, min, max);
  4663. })
  4664. return {
  4665. min: min,
  4666. max: max
  4667. };
  4668. }
  4669. /**
  4670. * Creates or updates the octree used to boost selection (picking)
  4671. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  4672. * @param maxCapacity defines the maximum capacity per leaf
  4673. * @param maxDepth defines the maximum depth of the octree
  4674. * @returns an octree of AbstractMesh
  4675. */
  4676. public createOrUpdateSelectionOctree(maxCapacity = 64, maxDepth = 2): Octree<AbstractMesh> {
  4677. if (!this._selectionOctree) {
  4678. this._selectionOctree = new Octree<AbstractMesh>(Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  4679. }
  4680. var worldExtends = this.getWorldExtends();
  4681. // Update octree
  4682. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  4683. return this._selectionOctree;
  4684. }
  4685. // Picking
  4686. /**
  4687. * Creates a ray that can be used to pick in the scene
  4688. * @param x defines the x coordinate of the origin (on-screen)
  4689. * @param y defines the y coordinate of the origin (on-screen)
  4690. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  4691. * @param camera defines the camera to use for the picking
  4692. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  4693. * @returns a Ray
  4694. */
  4695. public createPickingRay(x: number, y: number, world: Matrix, camera: Nullable<Camera>, cameraViewSpace = false): Ray {
  4696. let result = Ray.Zero();
  4697. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  4698. return result;
  4699. }
  4700. /**
  4701. * Creates a ray that can be used to pick in the scene
  4702. * @param x defines the x coordinate of the origin (on-screen)
  4703. * @param y defines the y coordinate of the origin (on-screen)
  4704. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  4705. * @param result defines the ray where to store the picking ray
  4706. * @param camera defines the camera to use for the picking
  4707. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  4708. * @returns the current scene
  4709. */
  4710. public createPickingRayToRef(x: number, y: number, world: Matrix, result: Ray, camera: Nullable<Camera>, cameraViewSpace = false): Scene {
  4711. var engine = this._engine;
  4712. if (!camera) {
  4713. if (!this.activeCamera)
  4714. throw new Error("Active camera not set");
  4715. camera = this.activeCamera;
  4716. }
  4717. var cameraViewport = camera.viewport;
  4718. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4719. // Moving coordinates to local viewport world
  4720. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  4721. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  4722. result.update(x, y, viewport.width, viewport.height, world ? world : Matrix.Identity(), cameraViewSpace ? Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  4723. return this;
  4724. }
  4725. /**
  4726. * Creates a ray that can be used to pick in the scene
  4727. * @param x defines the x coordinate of the origin (on-screen)
  4728. * @param y defines the y coordinate of the origin (on-screen)
  4729. * @param camera defines the camera to use for the picking
  4730. * @returns a Ray
  4731. */
  4732. public createPickingRayInCameraSpace(x: number, y: number, camera?: Camera): Ray {
  4733. let result = Ray.Zero();
  4734. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  4735. return result;
  4736. }
  4737. /**
  4738. * Creates a ray that can be used to pick in the scene
  4739. * @param x defines the x coordinate of the origin (on-screen)
  4740. * @param y defines the y coordinate of the origin (on-screen)
  4741. * @param result defines the ray where to store the picking ray
  4742. * @param camera defines the camera to use for the picking
  4743. * @returns the current scene
  4744. */
  4745. public createPickingRayInCameraSpaceToRef(x: number, y: number, result: Ray, camera?: Camera): Scene {
  4746. if (!PickingInfo) {
  4747. return this;
  4748. }
  4749. var engine = this._engine;
  4750. if (!camera) {
  4751. if (!this.activeCamera)
  4752. throw new Error("Active camera not set");
  4753. camera = this.activeCamera;
  4754. }
  4755. var cameraViewport = camera.viewport;
  4756. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4757. var identity = Matrix.Identity();
  4758. // Moving coordinates to local viewport world
  4759. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  4760. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  4761. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  4762. return this;
  4763. }
  4764. private _internalPick(rayFunction: (world: Matrix) => Ray, predicate?: (mesh: AbstractMesh) => boolean, fastCheck?: boolean): Nullable<PickingInfo> {
  4765. if (!PickingInfo) {
  4766. return null;
  4767. }
  4768. var pickingInfo = null;
  4769. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  4770. var mesh = this.meshes[meshIndex];
  4771. if (predicate) {
  4772. if (!predicate(mesh)) {
  4773. continue;
  4774. }
  4775. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  4776. continue;
  4777. }
  4778. var world = mesh.getWorldMatrix();
  4779. var ray = rayFunction(world);
  4780. var result = mesh.intersects(ray, fastCheck);
  4781. if (!result || !result.hit)
  4782. continue;
  4783. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  4784. continue;
  4785. pickingInfo = result;
  4786. if (fastCheck) {
  4787. break;
  4788. }
  4789. }
  4790. return pickingInfo || new PickingInfo();
  4791. }
  4792. private _internalMultiPick(rayFunction: (world: Matrix) => Ray, predicate?: (mesh: AbstractMesh) => boolean): Nullable<PickingInfo[]> {
  4793. if (!PickingInfo) {
  4794. return null;
  4795. }
  4796. var pickingInfos = new Array<PickingInfo>();
  4797. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  4798. var mesh = this.meshes[meshIndex];
  4799. if (predicate) {
  4800. if (!predicate(mesh)) {
  4801. continue;
  4802. }
  4803. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  4804. continue;
  4805. }
  4806. var world = mesh.getWorldMatrix();
  4807. var ray = rayFunction(world);
  4808. var result = mesh.intersects(ray, false);
  4809. if (!result || !result.hit)
  4810. continue;
  4811. pickingInfos.push(result);
  4812. }
  4813. return pickingInfos;
  4814. }
  4815. private _internalPickSprites(ray: Ray, predicate?: (sprite: Sprite) => boolean, fastCheck?: boolean, camera?: Camera): Nullable<PickingInfo> {
  4816. if (!PickingInfo) {
  4817. return null;
  4818. }
  4819. var pickingInfo = null;
  4820. if (!camera) {
  4821. if (!this.activeCamera) {
  4822. return null;
  4823. }
  4824. camera = this.activeCamera;
  4825. }
  4826. if (this.spriteManagers.length > 0) {
  4827. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  4828. var spriteManager = this.spriteManagers[spriteIndex];
  4829. if (!spriteManager.isPickable) {
  4830. continue;
  4831. }
  4832. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  4833. if (!result || !result.hit)
  4834. continue;
  4835. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  4836. continue;
  4837. pickingInfo = result;
  4838. if (fastCheck) {
  4839. break;
  4840. }
  4841. }
  4842. }
  4843. return pickingInfo || new PickingInfo();
  4844. }
  4845. private _tempPickingRay: Nullable<Ray> = Ray ? Ray.Zero() : null;
  4846. /** Launch a ray to try to pick a mesh in the scene
  4847. * @param x position on screen
  4848. * @param y position on screen
  4849. * @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
  4850. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  4851. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  4852. * @returns a PickingInfo
  4853. */
  4854. public pick(x: number, y: number, predicate?: (mesh: AbstractMesh) => boolean, fastCheck?: boolean, camera?: Nullable<Camera>): Nullable<PickingInfo> {
  4855. if (!PickingInfo) {
  4856. return null;
  4857. }
  4858. var result = this._internalPick(world => {
  4859. this.createPickingRayToRef(x, y, world, this._tempPickingRay!, camera || null);
  4860. return this._tempPickingRay!;
  4861. }, predicate, fastCheck);
  4862. if(result){
  4863. result.ray = this.createPickingRay(x, y, Matrix.Identity(), camera || null);
  4864. }
  4865. return result;
  4866. }
  4867. /** Launch a ray to try to pick a sprite in the scene
  4868. * @param x position on screen
  4869. * @param y position on screen
  4870. * @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
  4871. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  4872. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  4873. * @returns a PickingInfo
  4874. */
  4875. public pickSprite(x: number, y: number, predicate?: (sprite: Sprite) => boolean, fastCheck?: boolean, camera?: Camera): Nullable<PickingInfo> {
  4876. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay!, camera);
  4877. return this._internalPickSprites(this._tempPickingRay!, predicate, fastCheck, camera);
  4878. }
  4879. private _cachedRayForTransform: Ray;
  4880. /** Use the given ray to pick a mesh in the scene
  4881. * @param ray The ray to use to pick meshes
  4882. * @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
  4883. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  4884. * @returns a PickingInfo
  4885. */
  4886. public pickWithRay(ray: Ray, predicate?: (mesh: AbstractMesh) => boolean, fastCheck?: boolean): Nullable<PickingInfo> {
  4887. var result = this._internalPick(world => {
  4888. if (!this._pickWithRayInverseMatrix) {
  4889. this._pickWithRayInverseMatrix = Matrix.Identity();
  4890. }
  4891. world.invertToRef(this._pickWithRayInverseMatrix);
  4892. if (!this._cachedRayForTransform) {
  4893. this._cachedRayForTransform = Ray.Zero();
  4894. }
  4895. Ray.TransformToRef(ray, this._pickWithRayInverseMatrix, this._cachedRayForTransform);
  4896. return this._cachedRayForTransform;
  4897. }, predicate, fastCheck);
  4898. if(result){
  4899. result.ray = ray;
  4900. }
  4901. return result;
  4902. }
  4903. /**
  4904. * Launch a ray to try to pick a mesh in the scene
  4905. * @param x X position on screen
  4906. * @param y Y position on screen
  4907. * @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
  4908. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  4909. * @returns an array of PickingInfo
  4910. */
  4911. public multiPick(x: number, y: number, predicate?: (mesh: AbstractMesh) => boolean, camera?: Camera): Nullable<PickingInfo[]> {
  4912. return this._internalMultiPick(world => this.createPickingRay(x, y, world, camera || null), predicate);
  4913. }
  4914. /**
  4915. * Launch a ray to try to pick a mesh in the scene
  4916. * @param ray Ray to use
  4917. * @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
  4918. * @returns an array of PickingInfo
  4919. */
  4920. public multiPickWithRay(ray: Ray, predicate: (mesh: AbstractMesh) => boolean): Nullable<PickingInfo[]> {
  4921. return this._internalMultiPick(world => {
  4922. if (!this._pickWithRayInverseMatrix) {
  4923. this._pickWithRayInverseMatrix = Matrix.Identity();
  4924. }
  4925. world.invertToRef(this._pickWithRayInverseMatrix);
  4926. if (!this._cachedRayForTransform) {
  4927. this._cachedRayForTransform = Ray.Zero();
  4928. }
  4929. Ray.TransformToRef(ray, this._pickWithRayInverseMatrix, this._cachedRayForTransform);
  4930. return this._cachedRayForTransform;
  4931. }, predicate);
  4932. }
  4933. /**
  4934. * Force the value of meshUnderPointer
  4935. * @param mesh defines the mesh to use
  4936. */
  4937. public setPointerOverMesh(mesh: Nullable<AbstractMesh>): void {
  4938. if (this._pointerOverMesh === mesh) {
  4939. return;
  4940. }
  4941. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  4942. this._pointerOverMesh.actionManager.processTrigger(ActionManager.OnPointerOutTrigger, ActionEvent.CreateNew(this._pointerOverMesh));
  4943. }
  4944. this._pointerOverMesh = mesh;
  4945. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  4946. this._pointerOverMesh.actionManager.processTrigger(ActionManager.OnPointerOverTrigger, ActionEvent.CreateNew(this._pointerOverMesh));
  4947. }
  4948. }
  4949. /**
  4950. * Gets the mesh under the pointer
  4951. * @returns a Mesh or null if no mesh is under the pointer
  4952. */
  4953. public getPointerOverMesh(): Nullable<AbstractMesh> {
  4954. return this._pointerOverMesh;
  4955. }
  4956. /**
  4957. * Force the sprite under the pointer
  4958. * @param sprite defines the sprite to use
  4959. */
  4960. public setPointerOverSprite(sprite: Nullable<Sprite>): void {
  4961. if (this._pointerOverSprite === sprite) {
  4962. return;
  4963. }
  4964. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  4965. this._pointerOverSprite.actionManager.processTrigger(ActionManager.OnPointerOutTrigger, ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  4966. }
  4967. this._pointerOverSprite = sprite;
  4968. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  4969. this._pointerOverSprite.actionManager.processTrigger(ActionManager.OnPointerOverTrigger, ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  4970. }
  4971. }
  4972. /**
  4973. * Gets the sprite under the pointer
  4974. * @returns a Sprite or null if no sprite is under the pointer
  4975. */
  4976. public getPointerOverSprite(): Nullable<Sprite> {
  4977. return this._pointerOverSprite;
  4978. }
  4979. // Physics
  4980. /**
  4981. * Gets the current physics engine
  4982. * @returns a PhysicsEngine or null if none attached
  4983. */
  4984. public getPhysicsEngine(): Nullable<PhysicsEngine> {
  4985. return this._physicsEngine;
  4986. }
  4987. /**
  4988. * Enables physics to the current scene
  4989. * @param gravity defines the scene's gravity for the physics engine
  4990. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  4991. * @return a boolean indicating if the physics engine was initialized
  4992. */
  4993. public enablePhysics(gravity: Nullable<Vector3> = null, plugin?: IPhysicsEnginePlugin): boolean {
  4994. if (this._physicsEngine) {
  4995. return true;
  4996. }
  4997. try {
  4998. this._physicsEngine = new PhysicsEngine(gravity, plugin);
  4999. return true;
  5000. } catch (e) {
  5001. Tools.Error(e.message);
  5002. return false;
  5003. }
  5004. }
  5005. /**
  5006. * Disables and disposes the physics engine associated with the scene
  5007. */
  5008. public disablePhysicsEngine(): void {
  5009. if (!this._physicsEngine) {
  5010. return;
  5011. }
  5012. this._physicsEngine.dispose();
  5013. this._physicsEngine = null;
  5014. }
  5015. /**
  5016. * Gets a boolean indicating if there is an active physics engine
  5017. * @returns a boolean indicating if there is an active physics engine
  5018. */
  5019. public isPhysicsEnabled(): boolean {
  5020. return this._physicsEngine !== undefined;
  5021. }
  5022. /**
  5023. * Deletes a physics compound impostor
  5024. * @param compound defines the compound to delete
  5025. */
  5026. public deleteCompoundImpostor(compound: any): void {
  5027. var mesh: AbstractMesh = compound.parts[0].mesh;
  5028. if (mesh.physicsImpostor) {
  5029. mesh.physicsImpostor.dispose(/*true*/);
  5030. mesh.physicsImpostor = null;
  5031. }
  5032. }
  5033. // Misc.
  5034. /** @hidden */
  5035. public _rebuildGeometries(): void {
  5036. for (var geometry of this._geometries) {
  5037. geometry._rebuild();
  5038. }
  5039. for (var mesh of this.meshes) {
  5040. mesh._rebuild();
  5041. }
  5042. if (this.postProcessManager) {
  5043. this.postProcessManager._rebuild();
  5044. }
  5045. for (var layer of this.layers) {
  5046. layer._rebuild();
  5047. }
  5048. for (var effectLayer of this.effectLayers) {
  5049. effectLayer._rebuild();
  5050. }
  5051. if (this._boundingBoxRenderer) {
  5052. this._boundingBoxRenderer._rebuild();
  5053. }
  5054. for (var system of this.particleSystems) {
  5055. system.rebuild();
  5056. }
  5057. if (this._postProcessRenderPipelineManager) {
  5058. this._postProcessRenderPipelineManager._rebuild();
  5059. }
  5060. }
  5061. /** @hidden */
  5062. public _rebuildTextures(): void {
  5063. for (var texture of this.textures) {
  5064. texture._rebuild();
  5065. }
  5066. this.markAllMaterialsAsDirty(Material.TextureDirtyFlag);
  5067. }
  5068. /**
  5069. * Creates a default light for the scene.
  5070. * @param replace Whether to replace the existing lights in the scene.
  5071. */
  5072. public createDefaultLight(replace = false): void {
  5073. // Dispose existing light in replace mode.
  5074. if (replace) {
  5075. if (this.lights) {
  5076. for (var i = 0; i < this.lights.length; i++) {
  5077. this.lights[i].dispose();
  5078. }
  5079. }
  5080. }
  5081. // Light
  5082. if (this.lights.length === 0) {
  5083. new HemisphericLight("default light", Vector3.Up(), this);
  5084. }
  5085. }
  5086. /**
  5087. * Creates a default camera for the scene.
  5088. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  5089. * @param replace Whether to replace the existing active camera in the scene.
  5090. * @param attachCameraControls Whether to attach camera controls to the canvas.
  5091. */
  5092. public createDefaultCamera(createArcRotateCamera = false, replace = false, attachCameraControls = false): void {
  5093. // Dispose existing camera in replace mode.
  5094. if (replace) {
  5095. if (this.activeCamera) {
  5096. this.activeCamera.dispose();
  5097. this.activeCamera = null;
  5098. }
  5099. }
  5100. // Camera
  5101. if (!this.activeCamera) {
  5102. var worldExtends = this.getWorldExtends();
  5103. var worldSize = worldExtends.max.subtract(worldExtends.min);
  5104. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  5105. var camera: TargetCamera;
  5106. var radius = worldSize.length() * 1.5;
  5107. // empty scene scenario!
  5108. if (!isFinite(radius)) {
  5109. radius = 1;
  5110. worldCenter.copyFromFloats(0, 0, 0);
  5111. }
  5112. if (createArcRotateCamera) {
  5113. var arcRotateCamera = new ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  5114. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  5115. arcRotateCamera.wheelPrecision = 100 / radius;
  5116. camera = arcRotateCamera;
  5117. }
  5118. else {
  5119. var freeCamera = new FreeCamera("default camera", new Vector3(worldCenter.x, worldCenter.y, -radius), this);
  5120. freeCamera.setTarget(worldCenter);
  5121. camera = freeCamera;
  5122. }
  5123. camera.minZ = radius * 0.01;
  5124. camera.maxZ = radius * 1000;
  5125. camera.speed = radius * 0.2;
  5126. this.activeCamera = camera;
  5127. let canvas = this.getEngine().getRenderingCanvas();
  5128. if (attachCameraControls && canvas) {
  5129. camera.attachControl(canvas);
  5130. }
  5131. }
  5132. }
  5133. /**
  5134. * Creates a default camera and a default light
  5135. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  5136. * @param replace defines if the camera and/or light will replace the existing ones
  5137. * @param attachCameraControls defines if attachControl will be called on the new camera
  5138. */
  5139. public createDefaultCameraOrLight(createArcRotateCamera = false, replace = false, attachCameraControls = false): void {
  5140. this.createDefaultLight(replace);
  5141. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  5142. }
  5143. /**
  5144. * Creates a new sky box
  5145. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  5146. * @param environmentTexture defines the texture to use as environment texture
  5147. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  5148. * @param scale defines the overall scale of the skybox
  5149. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  5150. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  5151. * @returns a new mesh holding the sky box
  5152. */
  5153. public createDefaultSkybox(environmentTexture?: BaseTexture, pbr = false, scale = 1000, blur = 0, setGlobalEnvTexture = true): Nullable<Mesh> {
  5154. if (!environmentTexture) {
  5155. Tools.Warn("Can not create default skybox without environment texture.");
  5156. return null;
  5157. }
  5158. if (setGlobalEnvTexture) {
  5159. if (environmentTexture) {
  5160. this.environmentTexture = environmentTexture;
  5161. }
  5162. }
  5163. // Skybox
  5164. var hdrSkybox = Mesh.CreateBox("hdrSkyBox", scale, this);
  5165. if (pbr) {
  5166. let hdrSkyboxMaterial = new PBRMaterial("skyBox", this);
  5167. hdrSkyboxMaterial.backFaceCulling = false;
  5168. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  5169. if (hdrSkyboxMaterial.reflectionTexture) {
  5170. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = Texture.SKYBOX_MODE;
  5171. }
  5172. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  5173. hdrSkyboxMaterial.disableLighting = true;
  5174. hdrSkyboxMaterial.twoSidedLighting = true;
  5175. hdrSkybox.infiniteDistance = true;
  5176. hdrSkybox.material = hdrSkyboxMaterial;
  5177. }
  5178. else {
  5179. let skyboxMaterial = new StandardMaterial("skyBox", this);
  5180. skyboxMaterial.backFaceCulling = false;
  5181. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  5182. if (skyboxMaterial.reflectionTexture) {
  5183. skyboxMaterial.reflectionTexture.coordinatesMode = Texture.SKYBOX_MODE;
  5184. }
  5185. skyboxMaterial.disableLighting = true;
  5186. hdrSkybox.infiniteDistance = true;
  5187. hdrSkybox.material = skyboxMaterial;
  5188. }
  5189. return hdrSkybox;
  5190. }
  5191. /**
  5192. * Creates a new environment
  5193. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  5194. * @param options defines the options you can use to configure the environment
  5195. * @returns the new EnvironmentHelper
  5196. */
  5197. public createDefaultEnvironment(options: Partial<IEnvironmentHelperOptions>): Nullable<EnvironmentHelper> {
  5198. if (EnvironmentHelper) {
  5199. return new EnvironmentHelper(options, this);
  5200. }
  5201. return null;
  5202. }
  5203. /**
  5204. * Creates a new VREXperienceHelper
  5205. * @see http://doc.babylonjs.com/how_to/webvr_helper
  5206. * @param webVROptions defines the options used to create the new VREXperienceHelper
  5207. * @returns a new VREXperienceHelper
  5208. */
  5209. public createDefaultVRExperience(webVROptions: VRExperienceHelperOptions = {}): VRExperienceHelper {
  5210. return new VRExperienceHelper(this, webVROptions);
  5211. }
  5212. // Tags
  5213. private _getByTags(list: any[], tagsQuery: string, forEach?: (item: any) => void): any[] {
  5214. if (tagsQuery === undefined) {
  5215. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  5216. return list;
  5217. }
  5218. var listByTags = [];
  5219. forEach = forEach || ((item: any) => { return; });
  5220. for (var i in list) {
  5221. var item = list[i];
  5222. if (Tags && Tags.MatchesQuery(item, tagsQuery)) {
  5223. listByTags.push(item);
  5224. forEach(item);
  5225. }
  5226. }
  5227. return listByTags;
  5228. }
  5229. /**
  5230. * Get a list of meshes by tags
  5231. * @param tagsQuery defines the tags query to use
  5232. * @param forEach defines a predicate used to filter results
  5233. * @returns an array of Mesh
  5234. */
  5235. public getMeshesByTags(tagsQuery: string, forEach?: (mesh: AbstractMesh) => void): Mesh[] {
  5236. return this._getByTags(this.meshes, tagsQuery, forEach);
  5237. }
  5238. /**
  5239. * Get a list of cameras by tags
  5240. * @param tagsQuery defines the tags query to use
  5241. * @param forEach defines a predicate used to filter results
  5242. * @returns an array of Camera
  5243. */
  5244. public getCamerasByTags(tagsQuery: string, forEach?: (camera: Camera) => void): Camera[] {
  5245. return this._getByTags(this.cameras, tagsQuery, forEach);
  5246. }
  5247. /**
  5248. * Get a list of lights by tags
  5249. * @param tagsQuery defines the tags query to use
  5250. * @param forEach defines a predicate used to filter results
  5251. * @returns an array of Light
  5252. */
  5253. public getLightsByTags(tagsQuery: string, forEach?: (light: Light) => void): Light[] {
  5254. return this._getByTags(this.lights, tagsQuery, forEach);
  5255. }
  5256. /**
  5257. * Get a list of materials by tags
  5258. * @param tagsQuery defines the tags query to use
  5259. * @param forEach defines a predicate used to filter results
  5260. * @returns an array of Material
  5261. */
  5262. public getMaterialByTags(tagsQuery: string, forEach?: (material: Material) => void): Material[] {
  5263. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  5264. }
  5265. /**
  5266. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  5267. * This allowed control for front to back rendering or reversly depending of the special needs.
  5268. *
  5269. * @param renderingGroupId The rendering group id corresponding to its index
  5270. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  5271. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  5272. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  5273. */
  5274. public setRenderingOrder(renderingGroupId: number,
  5275. opaqueSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null,
  5276. alphaTestSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null,
  5277. transparentSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null): void {
  5278. this._renderingManager.setRenderingOrder(renderingGroupId,
  5279. opaqueSortCompareFn,
  5280. alphaTestSortCompareFn,
  5281. transparentSortCompareFn);
  5282. }
  5283. /**
  5284. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  5285. *
  5286. * @param renderingGroupId The rendering group id corresponding to its index
  5287. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  5288. * @param depth Automatically clears depth between groups if true and autoClear is true.
  5289. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  5290. */
  5291. public setRenderingAutoClearDepthStencil(renderingGroupId: number, autoClearDepthStencil: boolean,
  5292. depth = true,
  5293. stencil = true): void {
  5294. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  5295. }
  5296. /**
  5297. * Will flag all materials as dirty to trigger new shader compilation
  5298. * @param flag defines the flag used to specify which material part must be marked as dirty
  5299. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  5300. */
  5301. public markAllMaterialsAsDirty(flag: number, predicate?: (mat: Material) => boolean): void {
  5302. for (var material of this.materials) {
  5303. if (predicate && !predicate(material)) {
  5304. continue;
  5305. }
  5306. material.markAsDirty(flag);
  5307. }
  5308. }
  5309. /** @hidden */
  5310. public _loadFile(url: string, onSuccess: (data: string | ArrayBuffer, responseURL?: string) => void, onProgress?: (data: any) => void, useDatabase?: boolean, useArrayBuffer?: boolean, onError?: (request?: XMLHttpRequest, exception?: any) => void): IFileRequest {
  5311. let request = Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  5312. this._activeRequests.push(request);
  5313. request.onCompleteObservable.add(request => {
  5314. this._activeRequests.splice(this._activeRequests.indexOf(request), 1);
  5315. });
  5316. return request;
  5317. }
  5318. /** @hidden */
  5319. public _loadFileAsync(url: string, useDatabase?: boolean, useArrayBuffer?: boolean): Promise<string | ArrayBuffer> {
  5320. return new Promise((resolve, reject) => {
  5321. this._loadFile(url, (data) => {
  5322. resolve(data);
  5323. }, undefined, useDatabase, useArrayBuffer, (request, exception) => {
  5324. reject(exception);
  5325. })
  5326. });
  5327. }
  5328. }
  5329. }