scene.ts 187 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098
  1. import { Nullable } from "./types";
  2. import { IAnimatable, IFileRequest, Tools, PerfCounter } from "./Misc/tools";
  3. import { PrecisionDate } from "./Misc/precisionDate";
  4. import { Observable, Observer } from "./Misc/observable";
  5. import { SmartArrayNoDuplicate, SmartArray, ISmartArrayLike } from "./Misc/smartArray";
  6. import { StringDictionary } from "./Misc/stringDictionary";
  7. import { Tags } from "./Misc/tags";
  8. import { Color4, Color3, Plane, Vector2, Vector3, Matrix, Tmp, Frustum } from "./Maths/math";
  9. import { Geometry } from "./Meshes/geometry";
  10. import { TransformNode } from "./Meshes/transformNode";
  11. import { SubMesh } from "./Meshes/subMesh";
  12. import { AbstractMesh } from "./Meshes/abstractMesh";
  13. import { Mesh } from "./Meshes/mesh";
  14. import { IParticleSystem } from "./Particles/IParticleSystem";
  15. import { Bone } from "./Bones/bone";
  16. import { Skeleton } from "./Bones/skeleton";
  17. import { MorphTargetManager } from "./Morph/morphTargetManager";
  18. import { Camera } from "./Cameras/camera";
  19. import { AbstractScene } from "./abstractScene";
  20. import { BaseTexture } from "./Materials/Textures/baseTexture";
  21. import { Texture } from "./Materials/Textures/texture";
  22. import { RenderTargetTexture } from "./Materials/Textures/renderTargetTexture";
  23. import { Material } from "./Materials/material";
  24. import { ImageProcessingConfiguration } from "./Materials/imageProcessingConfiguration";
  25. import { Effect } from "./Materials/effect";
  26. import { UniformBuffer } from "./Materials/uniformBuffer";
  27. import { MultiMaterial } from "./Materials/multiMaterial";
  28. import { Light } from "./Lights/light";
  29. import { PickingInfo } from "./Collisions/pickingInfo";
  30. import { ICollisionCoordinator } from "./Collisions/collisionCoordinator";
  31. import { PointerEventTypes, PointerInfoPre, PointerInfo } from "./Events/pointerEvents";
  32. import { KeyboardInfoPre, KeyboardInfo, KeyboardEventTypes } from "./Events/keyboardEvents";
  33. import { ActionEvent } from "./Actions/actionEvent";
  34. import { PostProcess } from "./PostProcesses/postProcess";
  35. import { PostProcessManager } from "./PostProcesses/postProcessManager";
  36. import { IOfflineProvider } from "./Offline/IOfflineProvider";
  37. import { RenderingGroupInfo, RenderingManager, IRenderingManagerAutoClearSetup } from "./Rendering/renderingManager";
  38. import { ISceneComponent, ISceneSerializableComponent, Stage, SimpleStageAction, RenderTargetsStageAction, RenderTargetStageAction, MeshStageAction, EvaluateSubMeshStageAction, ActiveMeshStageAction, CameraStageAction, RenderingGroupStageAction, RenderingMeshStageAction, PointerMoveStageAction, PointerUpDownStageAction } from "./sceneComponent";
  39. import { Engine } from "./Engines/engine";
  40. import { Node } from "./node";
  41. import { MorphTarget } from "./Morph/morphTarget";
  42. import { Constants } from "./Engines/constants";
  43. import { DomManagement } from "./Misc/domManagement";
  44. import { Logger } from "./Misc/logger";
  45. import { EngineStore } from "./Engines/engineStore";
  46. import { AbstractActionManager } from './Actions/abstractActionManager';
  47. import { _DevTools } from './Misc/devTools';
  48. import { WebRequest } from './Misc/webRequest';
  49. declare type Ray = import("./Culling/ray").Ray;
  50. declare type TrianglePickingPredicate = import("./Culling/ray").TrianglePickingPredicate;
  51. declare type Animation = import("./Animations/animation").Animation;
  52. declare type Animatable = import("./Animations/animatable").Animatable;
  53. declare type AnimationGroup = import("./Animations/animationGroup").AnimationGroup;
  54. declare type AnimationPropertiesOverride = import("./Animations/animationPropertiesOverride").AnimationPropertiesOverride;
  55. declare type Collider = import("./Collisions/collider").Collider;
  56. /**
  57. * Define an interface for all classes that will hold resources
  58. */
  59. export interface IDisposable {
  60. /**
  61. * Releases all held resources
  62. */
  63. dispose(): void;
  64. }
  65. /** @hidden */
  66. class ClickInfo {
  67. private _singleClick = false;
  68. private _doubleClick = false;
  69. private _hasSwiped = false;
  70. private _ignore = false;
  71. public get singleClick(): boolean {
  72. return this._singleClick;
  73. }
  74. public get doubleClick(): boolean {
  75. return this._doubleClick;
  76. }
  77. public get hasSwiped(): boolean {
  78. return this._hasSwiped;
  79. }
  80. public get ignore(): boolean {
  81. return this._ignore;
  82. }
  83. public set singleClick(b: boolean) {
  84. this._singleClick = b;
  85. }
  86. public set doubleClick(b: boolean) {
  87. this._doubleClick = b;
  88. }
  89. public set hasSwiped(b: boolean) {
  90. this._hasSwiped = b;
  91. }
  92. public set ignore(b: boolean) {
  93. this._ignore = b;
  94. }
  95. }
  96. /** Interface defining initialization parameters for Scene class */
  97. export interface SceneOptions {
  98. /**
  99. * Defines that scene should keep up-to-date a map of geometry to enable fast look-up by uniqueId
  100. * It will improve performance when the number of geometries becomes important.
  101. */
  102. useGeometryUniqueIdsMap?: boolean;
  103. /**
  104. * Defines that each material of the scene should keep up-to-date a map of referencing meshes for fast diposing
  105. * It will improve performance when the number of mesh becomes important, but might consume a bit more memory
  106. */
  107. useMaterialMeshMap?: boolean;
  108. /**
  109. * Defines that each mesh of the scene should keep up-to-date a map of referencing cloned meshes for fast diposing
  110. * It will improve performance when the number of mesh becomes important, but might consume a bit more memory
  111. */
  112. useClonedMeshhMap?: boolean;
  113. }
  114. /**
  115. * Represents a scene to be rendered by the engine.
  116. * @see http://doc.babylonjs.com/features/scene
  117. */
  118. export class Scene extends AbstractScene implements IAnimatable {
  119. // Statics
  120. private static _uniqueIdCounter = 0;
  121. /** The fog is deactivated */
  122. public static readonly FOGMODE_NONE = 0;
  123. /** The fog density is following an exponential function */
  124. public static readonly FOGMODE_EXP = 1;
  125. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  126. public static readonly FOGMODE_EXP2 = 2;
  127. /** The fog density is following a linear function. */
  128. public static readonly FOGMODE_LINEAR = 3;
  129. /**
  130. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  131. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  132. */
  133. public static MinDeltaTime = 1.0;
  134. /**
  135. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  136. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  137. */
  138. public static MaxDeltaTime = 1000.0;
  139. /**
  140. * Factory used to create the default material.
  141. * @param name The name of the material to create
  142. * @param scene The scene to create the material for
  143. * @returns The default material
  144. */
  145. public static DefaultMaterialFactory(scene: Scene): Material {
  146. throw _DevTools.WarnImport("StandardMaterial");
  147. }
  148. /**
  149. * Factory used to create the a collision coordinator.
  150. * @returns The collision coordinator
  151. */
  152. public static CollisionCoordinatorFactory(): ICollisionCoordinator {
  153. throw _DevTools.WarnImport("DefaultCollisionCoordinator");
  154. }
  155. // Members
  156. /** @hidden */
  157. public readonly _isScene = true;
  158. /**
  159. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  160. */
  161. public autoClear = true;
  162. /**
  163. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  164. */
  165. public autoClearDepthAndStencil = true;
  166. /**
  167. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  168. */
  169. public clearColor: Color4 = new Color4(0.2, 0.2, 0.3, 1.0);
  170. /**
  171. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  172. */
  173. public ambientColor = new Color3(0, 0, 0);
  174. /** @hidden */
  175. public _environmentBRDFTexture: BaseTexture;
  176. /** @hidden */
  177. protected _environmentTexture: Nullable<BaseTexture>;
  178. /**
  179. * Texture used in all pbr material as the reflection texture.
  180. * As in the majority of the scene they are the same (exception for multi room and so on),
  181. * this is easier to reference from here than from all the materials.
  182. */
  183. public get environmentTexture(): Nullable<BaseTexture> {
  184. return this._environmentTexture;
  185. }
  186. /**
  187. * Texture used in all pbr material as the reflection texture.
  188. * As in the majority of the scene they are the same (exception for multi room and so on),
  189. * this is easier to set here than in all the materials.
  190. */
  191. public set environmentTexture(value: Nullable<BaseTexture>) {
  192. if (this._environmentTexture === value) {
  193. return;
  194. }
  195. this._environmentTexture = value;
  196. this.markAllMaterialsAsDirty(Constants.MATERIAL_TextureDirtyFlag);
  197. }
  198. /** @hidden */
  199. protected _imageProcessingConfiguration: ImageProcessingConfiguration;
  200. /**
  201. * Default image processing configuration used either in the rendering
  202. * Forward main pass or through the imageProcessingPostProcess if present.
  203. * As in the majority of the scene they are the same (exception for multi camera),
  204. * this is easier to reference from here than from all the materials and post process.
  205. *
  206. * No setter as we it is a shared configuration, you can set the values instead.
  207. */
  208. public get imageProcessingConfiguration(): ImageProcessingConfiguration {
  209. return this._imageProcessingConfiguration;
  210. }
  211. private _forceWireframe = false;
  212. /**
  213. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  214. */
  215. public set forceWireframe(value: boolean) {
  216. if (this._forceWireframe === value) {
  217. return;
  218. }
  219. this._forceWireframe = value;
  220. this.markAllMaterialsAsDirty(Constants.MATERIAL_MiscDirtyFlag);
  221. }
  222. public get forceWireframe(): boolean {
  223. return this._forceWireframe;
  224. }
  225. private _forcePointsCloud = false;
  226. /**
  227. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  228. */
  229. public set forcePointsCloud(value: boolean) {
  230. if (this._forcePointsCloud === value) {
  231. return;
  232. }
  233. this._forcePointsCloud = value;
  234. this.markAllMaterialsAsDirty(Constants.MATERIAL_MiscDirtyFlag);
  235. }
  236. public get forcePointsCloud(): boolean {
  237. return this._forcePointsCloud;
  238. }
  239. /**
  240. * Gets or sets the active clipplane 1
  241. */
  242. public clipPlane: Nullable<Plane>;
  243. /**
  244. * Gets or sets the active clipplane 2
  245. */
  246. public clipPlane2: Nullable<Plane>;
  247. /**
  248. * Gets or sets the active clipplane 3
  249. */
  250. public clipPlane3: Nullable<Plane>;
  251. /**
  252. * Gets or sets the active clipplane 4
  253. */
  254. public clipPlane4: Nullable<Plane>;
  255. /**
  256. * Gets or sets a boolean indicating if animations are enabled
  257. */
  258. public animationsEnabled = true;
  259. private _animationPropertiesOverride: Nullable<AnimationPropertiesOverride> = null;
  260. /**
  261. * Gets or sets the animation properties override
  262. */
  263. public get animationPropertiesOverride(): Nullable<AnimationPropertiesOverride> {
  264. return this._animationPropertiesOverride;
  265. }
  266. public set animationPropertiesOverride(value: Nullable<AnimationPropertiesOverride>) {
  267. this._animationPropertiesOverride = value;
  268. }
  269. /**
  270. * Gets or sets a boolean indicating if a constant deltatime has to be used
  271. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  272. */
  273. public useConstantAnimationDeltaTime = false;
  274. /**
  275. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  276. * Please note that it requires to run a ray cast through the scene on every frame
  277. */
  278. public constantlyUpdateMeshUnderPointer = false;
  279. /**
  280. * Defines the HTML cursor to use when hovering over interactive elements
  281. */
  282. public hoverCursor = "pointer";
  283. /**
  284. * Defines the HTML default cursor to use (empty by default)
  285. */
  286. public defaultCursor: string = "";
  287. /**
  288. * This is used to call preventDefault() on pointer down
  289. * in order to block unwanted artifacts like system double clicks
  290. */
  291. public preventDefaultOnPointerDown = true;
  292. /**
  293. * This is used to call preventDefault() on pointer up
  294. * in order to block unwanted artifacts like system double clicks
  295. */
  296. public preventDefaultOnPointerUp = true;
  297. // Metadata
  298. /**
  299. * Gets or sets user defined metadata
  300. */
  301. public metadata: any = null;
  302. /**
  303. * For internal use only. Please do not use.
  304. */
  305. public reservedDataStore: any = null;
  306. /**
  307. * Gets the name of the plugin used to load this scene (null by default)
  308. */
  309. public loadingPluginName: string;
  310. /**
  311. * Use this array to add regular expressions used to disable offline support for specific urls
  312. */
  313. public disableOfflineSupportExceptionRules = new Array<RegExp>();
  314. /**
  315. * An event triggered when the scene is disposed.
  316. */
  317. public onDisposeObservable = new Observable<Scene>();
  318. private _onDisposeObserver: Nullable<Observer<Scene>> = null;
  319. /** Sets a function to be executed when this scene is disposed. */
  320. public set onDispose(callback: () => void) {
  321. if (this._onDisposeObserver) {
  322. this.onDisposeObservable.remove(this._onDisposeObserver);
  323. }
  324. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  325. }
  326. /**
  327. * An event triggered before rendering the scene (right after animations and physics)
  328. */
  329. public onBeforeRenderObservable = new Observable<Scene>();
  330. private _onBeforeRenderObserver: Nullable<Observer<Scene>> = null;
  331. /** Sets a function to be executed before rendering this scene */
  332. public set beforeRender(callback: Nullable<() => void>) {
  333. if (this._onBeforeRenderObserver) {
  334. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  335. }
  336. if (callback) {
  337. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  338. }
  339. }
  340. /**
  341. * An event triggered after rendering the scene
  342. */
  343. public onAfterRenderObservable = new Observable<Scene>();
  344. private _onAfterRenderObserver: Nullable<Observer<Scene>> = null;
  345. /** Sets a function to be executed after rendering this scene */
  346. public set afterRender(callback: Nullable<() => void>) {
  347. if (this._onAfterRenderObserver) {
  348. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  349. }
  350. if (callback) {
  351. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  352. }
  353. }
  354. /**
  355. * An event triggered before animating the scene
  356. */
  357. public onBeforeAnimationsObservable = new Observable<Scene>();
  358. /**
  359. * An event triggered after animations processing
  360. */
  361. public onAfterAnimationsObservable = new Observable<Scene>();
  362. /**
  363. * An event triggered before draw calls are ready to be sent
  364. */
  365. public onBeforeDrawPhaseObservable = new Observable<Scene>();
  366. /**
  367. * An event triggered after draw calls have been sent
  368. */
  369. public onAfterDrawPhaseObservable = new Observable<Scene>();
  370. /**
  371. * An event triggered when the scene is ready
  372. */
  373. public onReadyObservable = new Observable<Scene>();
  374. /**
  375. * An event triggered before rendering a camera
  376. */
  377. public onBeforeCameraRenderObservable = new Observable<Camera>();
  378. private _onBeforeCameraRenderObserver: Nullable<Observer<Camera>> = null;
  379. /** Sets a function to be executed before rendering a camera*/
  380. public set beforeCameraRender(callback: () => void) {
  381. if (this._onBeforeCameraRenderObserver) {
  382. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  383. }
  384. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  385. }
  386. /**
  387. * An event triggered after rendering a camera
  388. */
  389. public onAfterCameraRenderObservable = new Observable<Camera>();
  390. private _onAfterCameraRenderObserver: Nullable<Observer<Camera>> = null;
  391. /** Sets a function to be executed after rendering a camera*/
  392. public set afterCameraRender(callback: () => void) {
  393. if (this._onAfterCameraRenderObserver) {
  394. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  395. }
  396. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  397. }
  398. /**
  399. * An event triggered when active meshes evaluation is about to start
  400. */
  401. public onBeforeActiveMeshesEvaluationObservable = new Observable<Scene>();
  402. /**
  403. * An event triggered when active meshes evaluation is done
  404. */
  405. public onAfterActiveMeshesEvaluationObservable = new Observable<Scene>();
  406. /**
  407. * An event triggered when particles rendering is about to start
  408. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  409. */
  410. public onBeforeParticlesRenderingObservable = new Observable<Scene>();
  411. /**
  412. * An event triggered when particles rendering is done
  413. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  414. */
  415. public onAfterParticlesRenderingObservable = new Observable<Scene>();
  416. /**
  417. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  418. */
  419. public onDataLoadedObservable = new Observable<Scene>();
  420. /**
  421. * An event triggered when a camera is created
  422. */
  423. public onNewCameraAddedObservable = new Observable<Camera>();
  424. /**
  425. * An event triggered when a camera is removed
  426. */
  427. public onCameraRemovedObservable = new Observable<Camera>();
  428. /**
  429. * An event triggered when a light is created
  430. */
  431. public onNewLightAddedObservable = new Observable<Light>();
  432. /**
  433. * An event triggered when a light is removed
  434. */
  435. public onLightRemovedObservable = new Observable<Light>();
  436. /**
  437. * An event triggered when a geometry is created
  438. */
  439. public onNewGeometryAddedObservable = new Observable<Geometry>();
  440. /**
  441. * An event triggered when a geometry is removed
  442. */
  443. public onGeometryRemovedObservable = new Observable<Geometry>();
  444. /**
  445. * An event triggered when a transform node is created
  446. */
  447. public onNewTransformNodeAddedObservable = new Observable<TransformNode>();
  448. /**
  449. * An event triggered when a transform node is removed
  450. */
  451. public onTransformNodeRemovedObservable = new Observable<TransformNode>();
  452. /**
  453. * An event triggered when a mesh is created
  454. */
  455. public onNewMeshAddedObservable = new Observable<AbstractMesh>();
  456. /**
  457. * An event triggered when a mesh is removed
  458. */
  459. public onMeshRemovedObservable = new Observable<AbstractMesh>();
  460. /**
  461. * An event triggered when a skeleton is created
  462. */
  463. public onNewSkeletonAddedObservable = new Observable<Skeleton>();
  464. /**
  465. * An event triggered when a skeleton is removed
  466. */
  467. public onSkeletonRemovedObservable = new Observable<Skeleton>();
  468. /**
  469. * An event triggered when a material is created
  470. */
  471. public onNewMaterialAddedObservable = new Observable<Material>();
  472. /**
  473. * An event triggered when a material is removed
  474. */
  475. public onMaterialRemovedObservable = new Observable<Material>();
  476. /**
  477. * An event triggered when a texture is created
  478. */
  479. public onNewTextureAddedObservable = new Observable<BaseTexture>();
  480. /**
  481. * An event triggered when a texture is removed
  482. */
  483. public onTextureRemovedObservable = new Observable<BaseTexture>();
  484. /**
  485. * An event triggered when render targets are about to be rendered
  486. * Can happen multiple times per frame.
  487. */
  488. public onBeforeRenderTargetsRenderObservable = new Observable<Scene>();
  489. /**
  490. * An event triggered when render targets were rendered.
  491. * Can happen multiple times per frame.
  492. */
  493. public onAfterRenderTargetsRenderObservable = new Observable<Scene>();
  494. /**
  495. * An event triggered before calculating deterministic simulation step
  496. */
  497. public onBeforeStepObservable = new Observable<Scene>();
  498. /**
  499. * An event triggered after calculating deterministic simulation step
  500. */
  501. public onAfterStepObservable = new Observable<Scene>();
  502. /**
  503. * An event triggered when the activeCamera property is updated
  504. */
  505. public onActiveCameraChanged = new Observable<Scene>();
  506. /**
  507. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  508. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  509. * 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)
  510. */
  511. public onBeforeRenderingGroupObservable = new Observable<RenderingGroupInfo>();
  512. /**
  513. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  514. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  515. * 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)
  516. */
  517. public onAfterRenderingGroupObservable = new Observable<RenderingGroupInfo>();
  518. /**
  519. * This Observable will when a mesh has been imported into the scene.
  520. */
  521. public onMeshImportedObservable = new Observable<AbstractMesh>();
  522. /**
  523. * Gets or sets a user defined funtion to select LOD from a mesh and a camera.
  524. * By default this function is undefined and Babylon.js will select LOD based on distance to camera
  525. */
  526. public customLODSelector: (mesh: AbstractMesh, camera: Camera) => Nullable<AbstractMesh>;
  527. // Animations
  528. /** @hidden */
  529. public _registeredForLateAnimationBindings = new SmartArrayNoDuplicate<any>(256);
  530. // Pointers
  531. /**
  532. * Gets or sets a predicate used to select candidate meshes for a pointer down event
  533. */
  534. public pointerDownPredicate: (Mesh: AbstractMesh) => boolean;
  535. /**
  536. * Gets or sets a predicate used to select candidate meshes for a pointer up event
  537. */
  538. public pointerUpPredicate: (Mesh: AbstractMesh) => boolean;
  539. /**
  540. * Gets or sets a predicate used to select candidate meshes for a pointer move event
  541. */
  542. public pointerMovePredicate: (Mesh: AbstractMesh) => boolean;
  543. private _onPointerMove: (evt: PointerEvent) => void;
  544. private _onPointerDown: (evt: PointerEvent) => void;
  545. private _onPointerUp: (evt: PointerEvent) => void;
  546. /** Callback called when a pointer move is detected */
  547. public onPointerMove: (evt: PointerEvent, pickInfo: PickingInfo, type: PointerEventTypes) => void;
  548. /** Callback called when a pointer down is detected */
  549. public onPointerDown: (evt: PointerEvent, pickInfo: PickingInfo, type: PointerEventTypes) => void;
  550. /** Callback called when a pointer up is detected */
  551. public onPointerUp: (evt: PointerEvent, pickInfo: Nullable<PickingInfo>, type: PointerEventTypes) => void;
  552. /** Callback called when a pointer pick is detected */
  553. public onPointerPick: (evt: PointerEvent, pickInfo: PickingInfo) => void;
  554. /**
  555. * 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).
  556. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  557. */
  558. public onPrePointerObservable = new Observable<PointerInfoPre>();
  559. /**
  560. * Observable event triggered each time an input event is received from the rendering canvas
  561. */
  562. public onPointerObservable = new Observable<PointerInfo>();
  563. /**
  564. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  565. */
  566. public get unTranslatedPointer(): Vector2 {
  567. return new Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  568. }
  569. /** The distance in pixel that you have to move to prevent some events */
  570. public static DragMovementThreshold = 10; // in pixels
  571. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  572. public static LongPressDelay = 500; // in milliseconds
  573. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  574. public static DoubleClickDelay = 300; // in milliseconds
  575. /** If you need to check double click without raising a single click at first click, enable this flag */
  576. public static ExclusiveDoubleClickMode = false;
  577. private _initClickEvent: (obs1: Observable<PointerInfoPre>, obs2: Observable<PointerInfo>, evt: PointerEvent, cb: (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => void) => void;
  578. private _initActionManager: (act: Nullable<AbstractActionManager>, clickInfo: ClickInfo) => Nullable<AbstractActionManager>;
  579. private _delayedSimpleClick: (btn: number, clickInfo: ClickInfo, cb: (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => void) => void;
  580. private _delayedSimpleClickTimeout: number;
  581. private _previousDelayedSimpleClickTimeout: number;
  582. private _meshPickProceed = false;
  583. private _previousButtonPressed: number;
  584. private _currentPickResult: Nullable<PickingInfo> = null;
  585. private _previousPickResult: Nullable<PickingInfo> = null;
  586. private _totalPointersPressed = 0;
  587. private _doubleClickOccured = false;
  588. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  589. public cameraToUseForPointers: Nullable<Camera> = null;
  590. private _pointerX: number = 0;
  591. private _pointerY: number = 0;
  592. private _unTranslatedPointerX: number;
  593. private _unTranslatedPointerY: number;
  594. private _startingPointerPosition = new Vector2(0, 0);
  595. private _previousStartingPointerPosition = new Vector2(0, 0);
  596. private _startingPointerTime = 0;
  597. private _previousStartingPointerTime = 0;
  598. private _pointerCaptures: { [pointerId: number]: boolean } = {};
  599. // Deterministic lockstep
  600. private _timeAccumulator: number = 0;
  601. private _currentStepId: number = 0;
  602. private _currentInternalStep: number = 0;
  603. // Mirror
  604. /** @hidden */
  605. public _mirroredCameraPosition: Nullable<Vector3>;
  606. // Keyboard
  607. /**
  608. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  609. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  610. */
  611. public onPreKeyboardObservable = new Observable<KeyboardInfoPre>();
  612. /**
  613. * Observable event triggered each time an keyboard event is received from the hosting window
  614. */
  615. public onKeyboardObservable = new Observable<KeyboardInfo>();
  616. private _onKeyDown: (evt: KeyboardEvent) => void;
  617. private _onKeyUp: (evt: KeyboardEvent) => void;
  618. private _onCanvasFocusObserver: Nullable<Observer<Engine>>;
  619. private _onCanvasBlurObserver: Nullable<Observer<Engine>>;
  620. // Coordinates system
  621. private _useRightHandedSystem = false;
  622. /**
  623. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  624. */
  625. public set useRightHandedSystem(value: boolean) {
  626. if (this._useRightHandedSystem === value) {
  627. return;
  628. }
  629. this._useRightHandedSystem = value;
  630. this.markAllMaterialsAsDirty(Constants.MATERIAL_MiscDirtyFlag);
  631. }
  632. public get useRightHandedSystem(): boolean {
  633. return this._useRightHandedSystem;
  634. }
  635. /**
  636. * Sets the step Id used by deterministic lock step
  637. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  638. * @param newStepId defines the step Id
  639. */
  640. public setStepId(newStepId: number): void {
  641. this._currentStepId = newStepId;
  642. }
  643. /**
  644. * Gets the step Id used by deterministic lock step
  645. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  646. * @returns the step Id
  647. */
  648. public getStepId(): number {
  649. return this._currentStepId;
  650. }
  651. /**
  652. * Gets the internal step used by deterministic lock step
  653. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  654. * @returns the internal step
  655. */
  656. public getInternalStep(): number {
  657. return this._currentInternalStep;
  658. }
  659. // Fog
  660. private _fogEnabled = true;
  661. /**
  662. * Gets or sets a boolean indicating if fog is enabled on this scene
  663. * @see http://doc.babylonjs.com/babylon101/environment#fog
  664. * (Default is true)
  665. */
  666. public set fogEnabled(value: boolean) {
  667. if (this._fogEnabled === value) {
  668. return;
  669. }
  670. this._fogEnabled = value;
  671. this.markAllMaterialsAsDirty(Constants.MATERIAL_MiscDirtyFlag);
  672. }
  673. public get fogEnabled(): boolean {
  674. return this._fogEnabled;
  675. }
  676. private _fogMode = Scene.FOGMODE_NONE;
  677. /**
  678. * Gets or sets the fog mode to use
  679. * @see http://doc.babylonjs.com/babylon101/environment#fog
  680. * | mode | value |
  681. * | --- | --- |
  682. * | FOGMODE_NONE | 0 |
  683. * | FOGMODE_EXP | 1 |
  684. * | FOGMODE_EXP2 | 2 |
  685. * | FOGMODE_LINEAR | 3 |
  686. */
  687. public set fogMode(value: number) {
  688. if (this._fogMode === value) {
  689. return;
  690. }
  691. this._fogMode = value;
  692. this.markAllMaterialsAsDirty(Constants.MATERIAL_MiscDirtyFlag);
  693. }
  694. public get fogMode(): number {
  695. return this._fogMode;
  696. }
  697. /**
  698. * Gets or sets the fog color to use
  699. * @see http://doc.babylonjs.com/babylon101/environment#fog
  700. * (Default is Color3(0.2, 0.2, 0.3))
  701. */
  702. public fogColor = new Color3(0.2, 0.2, 0.3);
  703. /**
  704. * Gets or sets the fog density to use
  705. * @see http://doc.babylonjs.com/babylon101/environment#fog
  706. * (Default is 0.1)
  707. */
  708. public fogDensity = 0.1;
  709. /**
  710. * Gets or sets the fog start distance to use
  711. * @see http://doc.babylonjs.com/babylon101/environment#fog
  712. * (Default is 0)
  713. */
  714. public fogStart = 0;
  715. /**
  716. * Gets or sets the fog end distance to use
  717. * @see http://doc.babylonjs.com/babylon101/environment#fog
  718. * (Default is 1000)
  719. */
  720. public fogEnd = 1000.0;
  721. // Lights
  722. private _shadowsEnabled = true;
  723. /**
  724. * Gets or sets a boolean indicating if shadows are enabled on this scene
  725. */
  726. public set shadowsEnabled(value: boolean) {
  727. if (this._shadowsEnabled === value) {
  728. return;
  729. }
  730. this._shadowsEnabled = value;
  731. this.markAllMaterialsAsDirty(Constants.MATERIAL_LightDirtyFlag);
  732. }
  733. public get shadowsEnabled(): boolean {
  734. return this._shadowsEnabled;
  735. }
  736. private _lightsEnabled = true;
  737. /**
  738. * Gets or sets a boolean indicating if lights are enabled on this scene
  739. */
  740. public set lightsEnabled(value: boolean) {
  741. if (this._lightsEnabled === value) {
  742. return;
  743. }
  744. this._lightsEnabled = value;
  745. this.markAllMaterialsAsDirty(Constants.MATERIAL_LightDirtyFlag);
  746. }
  747. public get lightsEnabled(): boolean {
  748. return this._lightsEnabled;
  749. }
  750. /** All of the active cameras added to this scene. */
  751. public activeCameras = new Array<Camera>();
  752. private _activeCamera: Nullable<Camera>;
  753. /** Gets or sets the current active camera */
  754. public get activeCamera(): Nullable<Camera> {
  755. return this._activeCamera;
  756. }
  757. public set activeCamera(value: Nullable<Camera>) {
  758. if (value === this._activeCamera) {
  759. return;
  760. }
  761. this._activeCamera = value;
  762. this.onActiveCameraChanged.notifyObservers(this);
  763. }
  764. private _defaultMaterial: Material;
  765. /** The default material used on meshes when no material is affected */
  766. public get defaultMaterial(): Material {
  767. if (!this._defaultMaterial) {
  768. this._defaultMaterial = Scene.DefaultMaterialFactory(this);
  769. }
  770. return this._defaultMaterial;
  771. }
  772. /** The default material used on meshes when no material is affected */
  773. public set defaultMaterial(value: Material) {
  774. this._defaultMaterial = value;
  775. }
  776. // Textures
  777. private _texturesEnabled = true;
  778. /**
  779. * Gets or sets a boolean indicating if textures are enabled on this scene
  780. */
  781. public set texturesEnabled(value: boolean) {
  782. if (this._texturesEnabled === value) {
  783. return;
  784. }
  785. this._texturesEnabled = value;
  786. this.markAllMaterialsAsDirty(Constants.MATERIAL_TextureDirtyFlag);
  787. }
  788. public get texturesEnabled(): boolean {
  789. return this._texturesEnabled;
  790. }
  791. // Particles
  792. /**
  793. * Gets or sets a boolean indicating if particles are enabled on this scene
  794. */
  795. public particlesEnabled = true;
  796. // Sprites
  797. /**
  798. * Gets or sets a boolean indicating if sprites are enabled on this scene
  799. */
  800. public spritesEnabled = true;
  801. // Skeletons
  802. private _skeletonsEnabled = true;
  803. /**
  804. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  805. */
  806. public set skeletonsEnabled(value: boolean) {
  807. if (this._skeletonsEnabled === value) {
  808. return;
  809. }
  810. this._skeletonsEnabled = value;
  811. this.markAllMaterialsAsDirty(Constants.MATERIAL_AttributesDirtyFlag);
  812. }
  813. public get skeletonsEnabled(): boolean {
  814. return this._skeletonsEnabled;
  815. }
  816. // Lens flares
  817. /**
  818. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  819. */
  820. public lensFlaresEnabled = true;
  821. // Collisions
  822. /**
  823. * Gets or sets a boolean indicating if collisions are enabled on this scene
  824. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  825. */
  826. public collisionsEnabled = true;
  827. private _collisionCoordinator: ICollisionCoordinator;
  828. /** @hidden */
  829. public get collisionCoordinator(): ICollisionCoordinator {
  830. if (!this._collisionCoordinator) {
  831. this._collisionCoordinator = Scene.CollisionCoordinatorFactory();
  832. this._collisionCoordinator.init(this);
  833. }
  834. return this._collisionCoordinator;
  835. }
  836. /**
  837. * Defines the gravity applied to this scene (used only for collisions)
  838. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  839. */
  840. public gravity = new Vector3(0, -9.807, 0);
  841. // Postprocesses
  842. /**
  843. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  844. */
  845. public postProcessesEnabled = true;
  846. /**
  847. * The list of postprocesses added to the scene
  848. */
  849. public postProcesses = new Array<PostProcess>();
  850. /**
  851. * Gets the current postprocess manager
  852. */
  853. public postProcessManager: PostProcessManager;
  854. // Customs render targets
  855. /**
  856. * Gets or sets a boolean indicating if render targets are enabled on this scene
  857. */
  858. public renderTargetsEnabled = true;
  859. /**
  860. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  861. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  862. */
  863. public dumpNextRenderTargets = false;
  864. /**
  865. * The list of user defined render targets added to the scene
  866. */
  867. public customRenderTargets = new Array<RenderTargetTexture>();
  868. /**
  869. * Defines if texture loading must be delayed
  870. * If true, textures will only be loaded when they need to be rendered
  871. */
  872. public useDelayedTextureLoading: boolean;
  873. /**
  874. * Gets the list of meshes imported to the scene through SceneLoader
  875. */
  876. public importedMeshesFiles = new Array<String>();
  877. // Probes
  878. /**
  879. * Gets or sets a boolean indicating if probes are enabled on this scene
  880. */
  881. public probesEnabled = true;
  882. // Offline support
  883. /**
  884. * Gets or sets the current offline provider to use to store scene data
  885. * @see http://doc.babylonjs.com/how_to/caching_resources_in_indexeddb
  886. */
  887. public offlineProvider: IOfflineProvider;
  888. /**
  889. * Gets or sets the action manager associated with the scene
  890. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  891. */
  892. public actionManager: AbstractActionManager;
  893. private _meshesForIntersections = new SmartArrayNoDuplicate<AbstractMesh>(256);
  894. // Procedural textures
  895. /**
  896. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  897. */
  898. public proceduralTexturesEnabled = true;
  899. // Private
  900. private _engine: Engine;
  901. // Performance counters
  902. private _totalVertices = new PerfCounter();
  903. /** @hidden */
  904. public _activeIndices = new PerfCounter();
  905. /** @hidden */
  906. public _activeParticles = new PerfCounter();
  907. /** @hidden */
  908. public _activeBones = new PerfCounter();
  909. private _animationRatio: number;
  910. /** @hidden */
  911. public _animationTimeLast: number;
  912. /** @hidden */
  913. public _animationTime: number = 0;
  914. /**
  915. * Gets or sets a general scale for animation speed
  916. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  917. */
  918. public animationTimeScale: number = 1;
  919. /** @hidden */
  920. public _cachedMaterial: Nullable<Material>;
  921. /** @hidden */
  922. public _cachedEffect: Nullable<Effect>;
  923. /** @hidden */
  924. public _cachedVisibility: Nullable<number>;
  925. private _renderId = 0;
  926. private _frameId = 0;
  927. private _executeWhenReadyTimeoutId = -1;
  928. private _intermediateRendering = false;
  929. private _viewUpdateFlag = -1;
  930. private _projectionUpdateFlag = -1;
  931. private _alternateViewUpdateFlag = -1;
  932. private _alternateProjectionUpdateFlag = -1;
  933. /** @hidden */
  934. public _toBeDisposed = new Array<Nullable<IDisposable>>(256);
  935. private _activeRequests = new Array<IFileRequest>();
  936. /** @hidden */
  937. public _pendingData = new Array();
  938. private _isDisposed = false;
  939. /**
  940. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  941. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  942. */
  943. public dispatchAllSubMeshesOfActiveMeshes: boolean = false;
  944. private _activeMeshes = new SmartArray<AbstractMesh>(256);
  945. private _processedMaterials = new SmartArray<Material>(256);
  946. private _renderTargets = new SmartArrayNoDuplicate<RenderTargetTexture>(256);
  947. /** @hidden */
  948. public _activeParticleSystems = new SmartArray<IParticleSystem>(256);
  949. private _activeSkeletons = new SmartArrayNoDuplicate<Skeleton>(32);
  950. private _softwareSkinnedMeshes = new SmartArrayNoDuplicate<Mesh>(32);
  951. private _renderingManager: RenderingManager;
  952. /** @hidden */
  953. public _activeAnimatables = new Array<Animatable>();
  954. private _transformMatrix = Matrix.Zero();
  955. private _sceneUbo: UniformBuffer;
  956. private _alternateSceneUbo: UniformBuffer;
  957. private _viewMatrix: Matrix;
  958. private _projectionMatrix: Matrix;
  959. private _alternateViewMatrix: Matrix;
  960. private _alternateProjectionMatrix: Matrix;
  961. private _alternateTransformMatrix: Matrix;
  962. private _useAlternateCameraConfiguration = false;
  963. private _alternateRendering = false;
  964. private _wheelEventName = "";
  965. /** @hidden */
  966. public _forcedViewPosition: Nullable<Vector3>;
  967. /** @hidden */
  968. public get _isAlternateRenderingEnabled(): boolean {
  969. return this._alternateRendering;
  970. }
  971. private _frustumPlanes: Plane[];
  972. /**
  973. * Gets the list of frustum planes (built from the active camera)
  974. */
  975. public get frustumPlanes(): Plane[] {
  976. return this._frustumPlanes;
  977. }
  978. /**
  979. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  980. * This is useful if there are more lights that the maximum simulteanous authorized
  981. */
  982. public requireLightSorting = false;
  983. /** @hidden */
  984. public readonly useMaterialMeshMap: boolean;
  985. /** @hidden */
  986. public readonly useClonedMeshhMap: boolean;
  987. private _pointerOverMesh: Nullable<AbstractMesh>;
  988. private _pickedDownMesh: Nullable<AbstractMesh>;
  989. private _pickedUpMesh: Nullable<AbstractMesh>;
  990. private _externalData: StringDictionary<Object>;
  991. private _uid: Nullable<string>;
  992. /**
  993. * @hidden
  994. * Backing store of defined scene components.
  995. */
  996. public _components: ISceneComponent[] = [];
  997. /**
  998. * @hidden
  999. * Backing store of defined scene components.
  1000. */
  1001. public _serializableComponents: ISceneSerializableComponent[] = [];
  1002. /**
  1003. * List of components to register on the next registration step.
  1004. */
  1005. private _transientComponents: ISceneComponent[] = [];
  1006. /**
  1007. * Registers the transient components if needed.
  1008. */
  1009. private _registerTransientComponents(): void {
  1010. // Register components that have been associated lately to the scene.
  1011. if (this._transientComponents.length > 0) {
  1012. for (let component of this._transientComponents) {
  1013. component.register();
  1014. }
  1015. this._transientComponents = [];
  1016. }
  1017. }
  1018. /**
  1019. * @hidden
  1020. * Add a component to the scene.
  1021. * Note that the ccomponent could be registered on th next frame if this is called after
  1022. * the register component stage.
  1023. * @param component Defines the component to add to the scene
  1024. */
  1025. public _addComponent(component: ISceneComponent) {
  1026. this._components.push(component);
  1027. this._transientComponents.push(component);
  1028. const serializableComponent = component as ISceneSerializableComponent;
  1029. if (serializableComponent.addFromContainer) {
  1030. this._serializableComponents.push(serializableComponent);
  1031. }
  1032. }
  1033. /**
  1034. * @hidden
  1035. * Gets a component from the scene.
  1036. * @param name defines the name of the component to retrieve
  1037. * @returns the component or null if not present
  1038. */
  1039. public _getComponent(name: string): Nullable<ISceneComponent> {
  1040. for (let component of this._components) {
  1041. if (component.name === name) {
  1042. return component;
  1043. }
  1044. }
  1045. return null;
  1046. }
  1047. /**
  1048. * @hidden
  1049. * Defines the actions happening before camera updates.
  1050. */
  1051. public _beforeCameraUpdateStage = Stage.Create<SimpleStageAction>();
  1052. /**
  1053. * @hidden
  1054. * Defines the actions happening before clear the canvas.
  1055. */
  1056. public _beforeClearStage = Stage.Create<SimpleStageAction>();
  1057. /**
  1058. * @hidden
  1059. * Defines the actions when collecting render targets for the frame.
  1060. */
  1061. public _gatherRenderTargetsStage = Stage.Create<RenderTargetsStageAction>();
  1062. /**
  1063. * @hidden
  1064. * Defines the actions happening for one camera in the frame.
  1065. */
  1066. public _gatherActiveCameraRenderTargetsStage = Stage.Create<RenderTargetsStageAction>();
  1067. /**
  1068. * @hidden
  1069. * Defines the actions happening during the per mesh ready checks.
  1070. */
  1071. public _isReadyForMeshStage = Stage.Create<MeshStageAction>();
  1072. /**
  1073. * @hidden
  1074. * Defines the actions happening before evaluate active mesh checks.
  1075. */
  1076. public _beforeEvaluateActiveMeshStage = Stage.Create<SimpleStageAction>();
  1077. /**
  1078. * @hidden
  1079. * Defines the actions happening during the evaluate sub mesh checks.
  1080. */
  1081. public _evaluateSubMeshStage = Stage.Create<EvaluateSubMeshStageAction>();
  1082. /**
  1083. * @hidden
  1084. * Defines the actions happening during the active mesh stage.
  1085. */
  1086. public _activeMeshStage = Stage.Create<ActiveMeshStageAction>();
  1087. /**
  1088. * @hidden
  1089. * Defines the actions happening during the per camera render target step.
  1090. */
  1091. public _cameraDrawRenderTargetStage = Stage.Create<CameraStageAction>();
  1092. /**
  1093. * @hidden
  1094. * Defines the actions happening just before the active camera is drawing.
  1095. */
  1096. public _beforeCameraDrawStage = Stage.Create<CameraStageAction>();
  1097. /**
  1098. * @hidden
  1099. * Defines the actions happening just before a render target is drawing.
  1100. */
  1101. public _beforeRenderTargetDrawStage = Stage.Create<RenderTargetStageAction>();
  1102. /**
  1103. * @hidden
  1104. * Defines the actions happening just before a rendering group is drawing.
  1105. */
  1106. public _beforeRenderingGroupDrawStage = Stage.Create<RenderingGroupStageAction>();
  1107. /**
  1108. * @hidden
  1109. * Defines the actions happening just before a mesh is drawing.
  1110. */
  1111. public _beforeRenderingMeshStage = Stage.Create<RenderingMeshStageAction>();
  1112. /**
  1113. * @hidden
  1114. * Defines the actions happening just after a mesh has been drawn.
  1115. */
  1116. public _afterRenderingMeshStage = Stage.Create<RenderingMeshStageAction>();
  1117. /**
  1118. * @hidden
  1119. * Defines the actions happening just after a rendering group has been drawn.
  1120. */
  1121. public _afterRenderingGroupDrawStage = Stage.Create<RenderingGroupStageAction>();
  1122. /**
  1123. * @hidden
  1124. * Defines the actions happening just after the active camera has been drawn.
  1125. */
  1126. public _afterCameraDrawStage = Stage.Create<CameraStageAction>();
  1127. /**
  1128. * @hidden
  1129. * Defines the actions happening just after a render target has been drawn.
  1130. */
  1131. public _afterRenderTargetDrawStage = Stage.Create<RenderTargetStageAction>();
  1132. /**
  1133. * @hidden
  1134. * Defines the actions happening just after rendering all cameras and computing intersections.
  1135. */
  1136. public _afterRenderStage = Stage.Create<SimpleStageAction>();
  1137. /**
  1138. * @hidden
  1139. * Defines the actions happening when a pointer move event happens.
  1140. */
  1141. public _pointerMoveStage = Stage.Create<PointerMoveStageAction>();
  1142. /**
  1143. * @hidden
  1144. * Defines the actions happening when a pointer down event happens.
  1145. */
  1146. public _pointerDownStage = Stage.Create<PointerUpDownStageAction>();
  1147. /**
  1148. * @hidden
  1149. * Defines the actions happening when a pointer up event happens.
  1150. */
  1151. public _pointerUpStage = Stage.Create<PointerUpDownStageAction>();
  1152. /**
  1153. * an optional map from Geometry Id to Geometry index in the 'geometries' array
  1154. */
  1155. private geometriesByUniqueId: Nullable<{ [uniqueId: string]: number | undefined }> = null;
  1156. /**
  1157. * Creates a new Scene
  1158. * @param engine defines the engine to use to render this scene
  1159. * @param options defines the scene options
  1160. */
  1161. constructor(engine: Engine, options?: SceneOptions) {
  1162. super();
  1163. this._engine = engine || EngineStore.LastCreatedEngine;
  1164. this._engine.scenes.push(this);
  1165. this._uid = null;
  1166. this._renderingManager = new RenderingManager(this);
  1167. if (PostProcessManager) {
  1168. this.postProcessManager = new PostProcessManager(this);
  1169. }
  1170. if (DomManagement.IsWindowObjectExist()) {
  1171. this.attachControl();
  1172. }
  1173. // Uniform Buffer
  1174. this._createUbo();
  1175. // Default Image processing definition
  1176. if (ImageProcessingConfiguration) {
  1177. this._imageProcessingConfiguration = new ImageProcessingConfiguration();
  1178. }
  1179. this.setDefaultCandidateProviders();
  1180. if (options && options.useGeometryUniqueIdsMap === true) {
  1181. this.geometriesByUniqueId = {};
  1182. }
  1183. this.useMaterialMeshMap = options && options.useGeometryUniqueIdsMap || false;
  1184. this.useClonedMeshhMap = options && options.useClonedMeshhMap || false;
  1185. this._engine.onNewSceneAddedObservable.notifyObservers(this);
  1186. }
  1187. private _defaultMeshCandidates: ISmartArrayLike<AbstractMesh> = {
  1188. data: [],
  1189. length: 0
  1190. };
  1191. /**
  1192. * @hidden
  1193. */
  1194. public _getDefaultMeshCandidates(): ISmartArrayLike<AbstractMesh> {
  1195. this._defaultMeshCandidates.data = this.meshes;
  1196. this._defaultMeshCandidates.length = this.meshes.length;
  1197. return this._defaultMeshCandidates;
  1198. }
  1199. private _defaultSubMeshCandidates: ISmartArrayLike<SubMesh> = {
  1200. data: [],
  1201. length: 0
  1202. };
  1203. /**
  1204. * @hidden
  1205. */
  1206. public _getDefaultSubMeshCandidates(mesh: AbstractMesh): ISmartArrayLike<SubMesh> {
  1207. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  1208. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  1209. return this._defaultSubMeshCandidates;
  1210. }
  1211. /**
  1212. * Sets the default candidate providers for the scene.
  1213. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  1214. * and getCollidingSubMeshCandidates to their default function
  1215. */
  1216. public setDefaultCandidateProviders(): void {
  1217. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  1218. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  1219. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  1220. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  1221. }
  1222. /**
  1223. * Gets the mesh that is currently under the pointer
  1224. */
  1225. public get meshUnderPointer(): Nullable<AbstractMesh> {
  1226. return this._pointerOverMesh;
  1227. }
  1228. /**
  1229. * Gets or sets the current on-screen X position of the pointer
  1230. */
  1231. public get pointerX(): number {
  1232. return this._pointerX;
  1233. }
  1234. public set pointerX(value: number) {
  1235. this._pointerX = value;
  1236. }
  1237. /**
  1238. * Gets or sets the current on-screen Y position of the pointer
  1239. */
  1240. public get pointerY(): number {
  1241. return this._pointerY;
  1242. }
  1243. public set pointerY(value: number) {
  1244. this._pointerY = value;
  1245. }
  1246. /**
  1247. * Gets the cached material (ie. the latest rendered one)
  1248. * @returns the cached material
  1249. */
  1250. public getCachedMaterial(): Nullable<Material> {
  1251. return this._cachedMaterial;
  1252. }
  1253. /**
  1254. * Gets the cached effect (ie. the latest rendered one)
  1255. * @returns the cached effect
  1256. */
  1257. public getCachedEffect(): Nullable<Effect> {
  1258. return this._cachedEffect;
  1259. }
  1260. /**
  1261. * Gets the cached visibility state (ie. the latest rendered one)
  1262. * @returns the cached visibility state
  1263. */
  1264. public getCachedVisibility(): Nullable<number> {
  1265. return this._cachedVisibility;
  1266. }
  1267. /**
  1268. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  1269. * @param material defines the current material
  1270. * @param effect defines the current effect
  1271. * @param visibility defines the current visibility state
  1272. * @returns true if one parameter is not cached
  1273. */
  1274. public isCachedMaterialInvalid(material: Material, effect: Effect, visibility: number = 1) {
  1275. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  1276. }
  1277. /**
  1278. * Gets the engine associated with the scene
  1279. * @returns an Engine
  1280. */
  1281. public getEngine(): Engine {
  1282. return this._engine;
  1283. }
  1284. /**
  1285. * Gets the total number of vertices rendered per frame
  1286. * @returns the total number of vertices rendered per frame
  1287. */
  1288. public getTotalVertices(): number {
  1289. return this._totalVertices.current;
  1290. }
  1291. /**
  1292. * Gets the performance counter for total vertices
  1293. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  1294. */
  1295. public get totalVerticesPerfCounter(): PerfCounter {
  1296. return this._totalVertices;
  1297. }
  1298. /**
  1299. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  1300. * @returns the total number of active indices rendered per frame
  1301. */
  1302. public getActiveIndices(): number {
  1303. return this._activeIndices.current;
  1304. }
  1305. /**
  1306. * Gets the performance counter for active indices
  1307. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  1308. */
  1309. public get totalActiveIndicesPerfCounter(): PerfCounter {
  1310. return this._activeIndices;
  1311. }
  1312. /**
  1313. * Gets the total number of active particles rendered per frame
  1314. * @returns the total number of active particles rendered per frame
  1315. */
  1316. public getActiveParticles(): number {
  1317. return this._activeParticles.current;
  1318. }
  1319. /**
  1320. * Gets the performance counter for active particles
  1321. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  1322. */
  1323. public get activeParticlesPerfCounter(): PerfCounter {
  1324. return this._activeParticles;
  1325. }
  1326. /**
  1327. * Gets the total number of active bones rendered per frame
  1328. * @returns the total number of active bones rendered per frame
  1329. */
  1330. public getActiveBones(): number {
  1331. return this._activeBones.current;
  1332. }
  1333. /**
  1334. * Gets the performance counter for active bones
  1335. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  1336. */
  1337. public get activeBonesPerfCounter(): PerfCounter {
  1338. return this._activeBones;
  1339. }
  1340. /**
  1341. * Gets the array of active meshes
  1342. * @returns an array of AbstractMesh
  1343. */
  1344. public getActiveMeshes(): SmartArray<AbstractMesh> {
  1345. return this._activeMeshes;
  1346. }
  1347. /**
  1348. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  1349. * @returns a number
  1350. */
  1351. public getAnimationRatio(): number {
  1352. return this._animationRatio !== undefined ? this._animationRatio : 1;
  1353. }
  1354. /**
  1355. * Gets an unique Id for the current render phase
  1356. * @returns a number
  1357. */
  1358. public getRenderId(): number {
  1359. return this._renderId;
  1360. }
  1361. /**
  1362. * Gets an unique Id for the current frame
  1363. * @returns a number
  1364. */
  1365. public getFrameId(): number {
  1366. return this._frameId;
  1367. }
  1368. /** Call this function if you want to manually increment the render Id*/
  1369. public incrementRenderId(): void {
  1370. this._renderId++;
  1371. }
  1372. private _updatePointerPosition(evt: PointerEvent): void {
  1373. var canvasRect = this._engine.getRenderingCanvasClientRect();
  1374. if (!canvasRect) {
  1375. return;
  1376. }
  1377. this._pointerX = evt.clientX - canvasRect.left;
  1378. this._pointerY = evt.clientY - canvasRect.top;
  1379. this._unTranslatedPointerX = this._pointerX;
  1380. this._unTranslatedPointerY = this._pointerY;
  1381. }
  1382. private _createUbo(): void {
  1383. this._sceneUbo = new UniformBuffer(this._engine, undefined, true);
  1384. this._sceneUbo.addUniform("viewProjection", 16);
  1385. this._sceneUbo.addUniform("view", 16);
  1386. }
  1387. private _createAlternateUbo(): void {
  1388. this._alternateSceneUbo = new UniformBuffer(this._engine, undefined, true);
  1389. this._alternateSceneUbo.addUniform("viewProjection", 16);
  1390. this._alternateSceneUbo.addUniform("view", 16);
  1391. }
  1392. // Pointers handling
  1393. private _setRayOnPointerInfo(pointerInfo: PointerInfo) {
  1394. if (pointerInfo.pickInfo && !pointerInfo.pickInfo._pickingUnavailable) {
  1395. if (!pointerInfo.pickInfo.ray) {
  1396. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, Matrix.Identity(), this.activeCamera);
  1397. }
  1398. }
  1399. }
  1400. /**
  1401. * Use this method to simulate a pointer move on a mesh
  1402. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  1403. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  1404. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  1405. * @returns the current scene
  1406. */
  1407. public simulatePointerMove(pickResult: PickingInfo, pointerEventInit?: PointerEventInit): Scene {
  1408. let evt = new PointerEvent("pointermove", pointerEventInit);
  1409. if (this._checkPrePointerObservable(pickResult, evt, PointerEventTypes.POINTERMOVE)) {
  1410. return this;
  1411. }
  1412. return this._processPointerMove(pickResult, evt);
  1413. }
  1414. private _processPointerMove(pickResult: Nullable<PickingInfo>, evt: PointerEvent): Scene {
  1415. var canvas = this._engine.getRenderingCanvas();
  1416. if (!canvas) {
  1417. return this;
  1418. }
  1419. // Restore pointer
  1420. canvas.style.cursor = this.defaultCursor;
  1421. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  1422. if (isMeshPicked) {
  1423. this.setPointerOverMesh(pickResult!.pickedMesh);
  1424. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  1425. if (this._pointerOverMesh.actionManager.hoverCursor) {
  1426. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  1427. } else {
  1428. canvas.style.cursor = this.hoverCursor;
  1429. }
  1430. }
  1431. } else {
  1432. this.setPointerOverMesh(null);
  1433. }
  1434. for (let step of this._pointerMoveStage) {
  1435. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  1436. }
  1437. if (pickResult) {
  1438. let type = evt.type === this._wheelEventName ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  1439. if (this.onPointerMove) {
  1440. this.onPointerMove(evt, pickResult, type);
  1441. }
  1442. if (this.onPointerObservable.hasObservers()) {
  1443. let pi = new PointerInfo(type, evt, pickResult);
  1444. this._setRayOnPointerInfo(pi);
  1445. this.onPointerObservable.notifyObservers(pi, type);
  1446. }
  1447. }
  1448. return this;
  1449. }
  1450. private _checkPrePointerObservable(pickResult: Nullable<PickingInfo>, evt: PointerEvent, type: number) {
  1451. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1452. if (pickResult) {
  1453. pi.ray = pickResult.ray;
  1454. }
  1455. this.onPrePointerObservable.notifyObservers(pi, type);
  1456. if (pi.skipOnPointerObservable) {
  1457. return true;
  1458. } else {
  1459. return false;
  1460. }
  1461. }
  1462. /**
  1463. * Use this method to simulate a pointer down on a mesh
  1464. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  1465. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  1466. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  1467. * @returns the current scene
  1468. */
  1469. public simulatePointerDown(pickResult: PickingInfo, pointerEventInit?: PointerEventInit): Scene {
  1470. let evt = new PointerEvent("pointerdown", pointerEventInit);
  1471. if (this._checkPrePointerObservable(pickResult, evt, PointerEventTypes.POINTERDOWN)) {
  1472. return this;
  1473. }
  1474. return this._processPointerDown(pickResult, evt);
  1475. }
  1476. private _processPointerDown(pickResult: Nullable<PickingInfo>, evt: PointerEvent): Scene {
  1477. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  1478. this._pickedDownMesh = pickResult.pickedMesh;
  1479. var actionManager = pickResult.pickedMesh.actionManager;
  1480. if (actionManager) {
  1481. if (actionManager.hasPickTriggers) {
  1482. actionManager.processTrigger(Constants.ACTION_OnPickDownTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1483. switch (evt.button) {
  1484. case 0:
  1485. actionManager.processTrigger(Constants.ACTION_OnLeftPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1486. break;
  1487. case 1:
  1488. actionManager.processTrigger(Constants.ACTION_OnCenterPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1489. break;
  1490. case 2:
  1491. actionManager.processTrigger(Constants.ACTION_OnRightPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1492. break;
  1493. }
  1494. }
  1495. if (actionManager.hasSpecificTrigger(Constants.ACTION_OnLongPressTrigger)) {
  1496. window.setTimeout(() => {
  1497. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY,
  1498. (mesh: AbstractMesh): boolean => (<boolean>(mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(Constants.ACTION_OnLongPressTrigger) && mesh == this._pickedDownMesh)),
  1499. false, this.cameraToUseForPointers);
  1500. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  1501. if (this._totalPointersPressed !== 0 &&
  1502. ((Date.now() - this._startingPointerTime) > Scene.LongPressDelay) &&
  1503. !this._isPointerSwiping()) {
  1504. this._startingPointerTime = 0;
  1505. actionManager.processTrigger(Constants.ACTION_OnLongPressTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1506. }
  1507. }
  1508. }, Scene.LongPressDelay);
  1509. }
  1510. }
  1511. }
  1512. else {
  1513. for (let step of this._pointerDownStage) {
  1514. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  1515. }
  1516. }
  1517. if (pickResult) {
  1518. let type = PointerEventTypes.POINTERDOWN;
  1519. if (this.onPointerDown) {
  1520. this.onPointerDown(evt, pickResult, type);
  1521. }
  1522. if (this.onPointerObservable.hasObservers()) {
  1523. let pi = new PointerInfo(type, evt, pickResult);
  1524. this._setRayOnPointerInfo(pi);
  1525. this.onPointerObservable.notifyObservers(pi, type);
  1526. }
  1527. }
  1528. return this;
  1529. }
  1530. /**
  1531. * Use this method to simulate a pointer up on a mesh
  1532. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  1533. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  1534. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  1535. * @param doubleTap indicates that the pointer up event should be considered as part of a double click (false by default)
  1536. * @returns the current scene
  1537. */
  1538. public simulatePointerUp(pickResult: PickingInfo, pointerEventInit?: PointerEventInit, doubleTap?: boolean): Scene {
  1539. let evt = new PointerEvent("pointerup", pointerEventInit);
  1540. let clickInfo = new ClickInfo();
  1541. if (doubleTap) {
  1542. clickInfo.doubleClick = true;
  1543. } else {
  1544. clickInfo.singleClick = true;
  1545. }
  1546. if (this._checkPrePointerObservable(pickResult, evt, PointerEventTypes.POINTERUP)) {
  1547. return this;
  1548. }
  1549. return this._processPointerUp(pickResult, evt, clickInfo);
  1550. }
  1551. private _processPointerUp(pickResult: Nullable<PickingInfo>, evt: PointerEvent, clickInfo: ClickInfo): Scene {
  1552. if (pickResult && pickResult && pickResult.pickedMesh) {
  1553. this._pickedUpMesh = pickResult.pickedMesh;
  1554. if (this._pickedDownMesh === this._pickedUpMesh) {
  1555. if (this.onPointerPick) {
  1556. this.onPointerPick(evt, pickResult);
  1557. }
  1558. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  1559. let type = PointerEventTypes.POINTERPICK;
  1560. let pi = new PointerInfo(type, evt, pickResult);
  1561. this._setRayOnPointerInfo(pi);
  1562. this.onPointerObservable.notifyObservers(pi, type);
  1563. }
  1564. }
  1565. let actionManager = pickResult.pickedMesh._getActionManagerForTrigger();
  1566. if (actionManager && !clickInfo.ignore) {
  1567. actionManager.processTrigger(Constants.ACTION_OnPickUpTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1568. if (!clickInfo.hasSwiped && clickInfo.singleClick) {
  1569. actionManager.processTrigger(Constants.ACTION_OnPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1570. }
  1571. let doubleClickActionManager = pickResult.pickedMesh._getActionManagerForTrigger(Constants.ACTION_OnDoublePickTrigger);
  1572. if (clickInfo.doubleClick && doubleClickActionManager) {
  1573. doubleClickActionManager.processTrigger(Constants.ACTION_OnDoublePickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1574. }
  1575. }
  1576. }
  1577. else {
  1578. if (!clickInfo.ignore) {
  1579. for (let step of this._pointerUpStage) {
  1580. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  1581. }
  1582. }
  1583. }
  1584. if (this._pickedDownMesh && this._pickedDownMesh !== this._pickedUpMesh) {
  1585. let pickedDownActionManager = this._pickedDownMesh._getActionManagerForTrigger(Constants.ACTION_OnPickOutTrigger);
  1586. if (pickedDownActionManager) {
  1587. pickedDownActionManager.processTrigger(Constants.ACTION_OnPickOutTrigger, ActionEvent.CreateNew(this._pickedDownMesh, evt));
  1588. }
  1589. }
  1590. let type = 0;
  1591. if (this.onPointerObservable.hasObservers()) {
  1592. if (!clickInfo.ignore && !clickInfo.hasSwiped) {
  1593. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  1594. type = PointerEventTypes.POINTERTAP;
  1595. }
  1596. else if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  1597. type = PointerEventTypes.POINTERDOUBLETAP;
  1598. }
  1599. if (type) {
  1600. let pi = new PointerInfo(type, evt, pickResult);
  1601. this._setRayOnPointerInfo(pi);
  1602. this.onPointerObservable.notifyObservers(pi, type);
  1603. }
  1604. }
  1605. if (!clickInfo.ignore) {
  1606. type = PointerEventTypes.POINTERUP;
  1607. let pi = new PointerInfo(type, evt, pickResult);
  1608. this._setRayOnPointerInfo(pi);
  1609. this.onPointerObservable.notifyObservers(pi, type);
  1610. }
  1611. }
  1612. if (this.onPointerUp && !clickInfo.ignore) {
  1613. this.onPointerUp(evt, pickResult, type);
  1614. }
  1615. return this;
  1616. }
  1617. /**
  1618. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  1619. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  1620. * @returns true if the pointer was captured
  1621. */
  1622. public isPointerCaptured(pointerId = 0): boolean {
  1623. return this._pointerCaptures[pointerId];
  1624. }
  1625. /** @hidden */
  1626. public _isPointerSwiping(): boolean {
  1627. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  1628. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  1629. }
  1630. /**
  1631. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  1632. * @param attachUp defines if you want to attach events to pointerup
  1633. * @param attachDown defines if you want to attach events to pointerdown
  1634. * @param attachMove defines if you want to attach events to pointermove
  1635. */
  1636. public attachControl(attachUp = true, attachDown = true, attachMove = true): void {
  1637. this._initActionManager = (act: Nullable<AbstractActionManager>, clickInfo: ClickInfo): Nullable<AbstractActionManager> => {
  1638. if (!this._meshPickProceed) {
  1639. let pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, this.pointerDownPredicate, false, this.cameraToUseForPointers);
  1640. this._currentPickResult = pickResult;
  1641. if (pickResult) {
  1642. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  1643. }
  1644. this._meshPickProceed = true;
  1645. }
  1646. return act;
  1647. };
  1648. this._delayedSimpleClick = (btn: number, clickInfo: ClickInfo, cb: (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => void) => {
  1649. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  1650. if ((Date.now() - this._previousStartingPointerTime > Scene.DoubleClickDelay && !this._doubleClickOccured) ||
  1651. btn !== this._previousButtonPressed) {
  1652. this._doubleClickOccured = false;
  1653. clickInfo.singleClick = true;
  1654. clickInfo.ignore = false;
  1655. cb(clickInfo, this._currentPickResult);
  1656. }
  1657. };
  1658. this._initClickEvent = (obs1: Observable<PointerInfoPre>, obs2: Observable<PointerInfo>, evt: PointerEvent, cb: (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => void): void => {
  1659. let clickInfo = new ClickInfo();
  1660. this._currentPickResult = null;
  1661. let act: Nullable<AbstractActionManager> = null;
  1662. let checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  1663. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  1664. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  1665. if (!checkPicking && AbstractActionManager) {
  1666. act = this._initActionManager(act, clickInfo);
  1667. if (act) {
  1668. checkPicking = act.hasPickTriggers;
  1669. }
  1670. }
  1671. let needToIgnoreNext = false;
  1672. if (checkPicking) {
  1673. let btn = evt.button;
  1674. clickInfo.hasSwiped = this._isPointerSwiping();
  1675. if (!clickInfo.hasSwiped) {
  1676. let checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  1677. if (!checkSingleClickImmediately) {
  1678. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  1679. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  1680. if (checkSingleClickImmediately && !AbstractActionManager.HasSpecificTrigger(Constants.ACTION_OnDoublePickTrigger)) {
  1681. act = this._initActionManager(act, clickInfo);
  1682. if (act) {
  1683. checkSingleClickImmediately = !act.hasSpecificTrigger(Constants.ACTION_OnDoublePickTrigger);
  1684. }
  1685. }
  1686. }
  1687. if (checkSingleClickImmediately) {
  1688. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  1689. if (Date.now() - this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  1690. btn !== this._previousButtonPressed) {
  1691. clickInfo.singleClick = true;
  1692. cb(clickInfo, this._currentPickResult);
  1693. needToIgnoreNext = true;
  1694. }
  1695. }
  1696. // at least one double click is required to be check and exclusive double click is enabled
  1697. else {
  1698. // wait that no double click has been raised during the double click delay
  1699. this._previousDelayedSimpleClickTimeout = this._delayedSimpleClickTimeout;
  1700. this._delayedSimpleClickTimeout = window.setTimeout(this._delayedSimpleClick.bind(this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  1701. }
  1702. let checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  1703. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  1704. if (!checkDoubleClick && AbstractActionManager.HasSpecificTrigger(Constants.ACTION_OnDoublePickTrigger)) {
  1705. act = this._initActionManager(act, clickInfo);
  1706. if (act) {
  1707. checkDoubleClick = act.hasSpecificTrigger(Constants.ACTION_OnDoublePickTrigger);
  1708. }
  1709. }
  1710. if (checkDoubleClick) {
  1711. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  1712. if (btn === this._previousButtonPressed &&
  1713. Date.now() - this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  1714. !this._doubleClickOccured
  1715. ) {
  1716. // pointer has not moved for 2 clicks, it's a double click
  1717. if (!clickInfo.hasSwiped &&
  1718. !this._isPointerSwiping()) {
  1719. this._previousStartingPointerTime = 0;
  1720. this._doubleClickOccured = true;
  1721. clickInfo.doubleClick = true;
  1722. clickInfo.ignore = false;
  1723. if (Scene.ExclusiveDoubleClickMode && this._previousDelayedSimpleClickTimeout) {
  1724. clearTimeout(this._previousDelayedSimpleClickTimeout);
  1725. }
  1726. this._previousDelayedSimpleClickTimeout = this._delayedSimpleClickTimeout;
  1727. cb(clickInfo, this._currentPickResult);
  1728. }
  1729. // if the two successive clicks are too far, it's just two simple clicks
  1730. else {
  1731. this._doubleClickOccured = false;
  1732. this._previousStartingPointerTime = this._startingPointerTime;
  1733. this._previousStartingPointerPosition.x = this._startingPointerPosition.x;
  1734. this._previousStartingPointerPosition.y = this._startingPointerPosition.y;
  1735. this._previousButtonPressed = btn;
  1736. if (Scene.ExclusiveDoubleClickMode) {
  1737. if (this._previousDelayedSimpleClickTimeout) {
  1738. clearTimeout(this._previousDelayedSimpleClickTimeout);
  1739. }
  1740. this._previousDelayedSimpleClickTimeout = this._delayedSimpleClickTimeout;
  1741. cb(clickInfo, this._previousPickResult);
  1742. }
  1743. else {
  1744. cb(clickInfo, this._currentPickResult);
  1745. }
  1746. }
  1747. needToIgnoreNext = true;
  1748. }
  1749. // just the first click of the double has been raised
  1750. else {
  1751. this._doubleClickOccured = false;
  1752. this._previousStartingPointerTime = this._startingPointerTime;
  1753. this._previousStartingPointerPosition.x = this._startingPointerPosition.x;
  1754. this._previousStartingPointerPosition.y = this._startingPointerPosition.y;
  1755. this._previousButtonPressed = btn;
  1756. }
  1757. }
  1758. }
  1759. }
  1760. if (!needToIgnoreNext) {
  1761. cb(clickInfo, this._currentPickResult);
  1762. }
  1763. };
  1764. this._onPointerMove = (evt: PointerEvent) => {
  1765. this._updatePointerPosition(evt);
  1766. // PreObservable support
  1767. if (this._checkPrePointerObservable(null, evt, evt.type === this._wheelEventName ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE)) {
  1768. return;
  1769. }
  1770. if (!this.cameraToUseForPointers && !this.activeCamera) {
  1771. return;
  1772. }
  1773. if (!this.pointerMovePredicate) {
  1774. this.pointerMovePredicate = (mesh: AbstractMesh): boolean => (mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)) && (!this.cameraToUseForPointers || (this.cameraToUseForPointers.layerMask & mesh.layerMask) !== 0));
  1775. }
  1776. // Meshes
  1777. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, this.pointerMovePredicate, false, this.cameraToUseForPointers);
  1778. this._processPointerMove(pickResult, evt);
  1779. };
  1780. this._onPointerDown = (evt: PointerEvent) => {
  1781. this._totalPointersPressed++;
  1782. this._pickedDownMesh = null;
  1783. this._meshPickProceed = false;
  1784. this._updatePointerPosition(evt);
  1785. if (this.preventDefaultOnPointerDown && canvas) {
  1786. evt.preventDefault();
  1787. canvas.focus();
  1788. }
  1789. this._startingPointerPosition.x = this._pointerX;
  1790. this._startingPointerPosition.y = this._pointerY;
  1791. this._startingPointerTime = Date.now();
  1792. // PreObservable support
  1793. if (this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERDOWN)) {
  1794. return;
  1795. }
  1796. if (!this.cameraToUseForPointers && !this.activeCamera) {
  1797. return;
  1798. }
  1799. this._pointerCaptures[evt.pointerId] = true;
  1800. if (!this.pointerDownPredicate) {
  1801. this.pointerDownPredicate = (mesh: AbstractMesh): boolean => {
  1802. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (!this.cameraToUseForPointers || (this.cameraToUseForPointers.layerMask & mesh.layerMask) !== 0);
  1803. };
  1804. }
  1805. // Meshes
  1806. this._pickedDownMesh = null;
  1807. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, this.pointerDownPredicate, false, this.cameraToUseForPointers);
  1808. this._processPointerDown(pickResult, evt);
  1809. };
  1810. this._onPointerUp = (evt: PointerEvent) => {
  1811. if (this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  1812. return; // So we need to test it the pointer down was pressed before.
  1813. }
  1814. this._totalPointersPressed--;
  1815. this._pickedUpMesh = null;
  1816. this._meshPickProceed = false;
  1817. this._updatePointerPosition(evt);
  1818. if (this.preventDefaultOnPointerUp && canvas) {
  1819. evt.preventDefault();
  1820. canvas.focus();
  1821. }
  1822. this._initClickEvent(this.onPrePointerObservable, this.onPointerObservable, evt, (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => {
  1823. // PreObservable support
  1824. if (this.onPrePointerObservable.hasObservers()) {
  1825. if (!clickInfo.ignore) {
  1826. if (!clickInfo.hasSwiped) {
  1827. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  1828. if (this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERTAP)) {
  1829. return;
  1830. }
  1831. }
  1832. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  1833. if (this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERDOUBLETAP)) {
  1834. return;
  1835. }
  1836. }
  1837. }
  1838. if (this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERUP)) {
  1839. return;
  1840. }
  1841. }
  1842. }
  1843. if (!this._pointerCaptures[evt.pointerId]) {
  1844. return;
  1845. }
  1846. this._pointerCaptures[evt.pointerId] = false;
  1847. if (!this.cameraToUseForPointers && !this.activeCamera) {
  1848. return;
  1849. }
  1850. if (!this.pointerUpPredicate) {
  1851. this.pointerUpPredicate = (mesh: AbstractMesh): boolean => {
  1852. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (!this.cameraToUseForPointers || (this.cameraToUseForPointers.layerMask & mesh.layerMask) !== 0);
  1853. };
  1854. }
  1855. // Meshes
  1856. if (!this._meshPickProceed && (AbstractActionManager && AbstractActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  1857. this._initActionManager(null, clickInfo);
  1858. }
  1859. if (!pickResult) {
  1860. pickResult = this._currentPickResult;
  1861. }
  1862. this._processPointerUp(pickResult, evt, clickInfo);
  1863. this._previousPickResult = this._currentPickResult;
  1864. });
  1865. };
  1866. this._onKeyDown = (evt: KeyboardEvent) => {
  1867. let type = KeyboardEventTypes.KEYDOWN;
  1868. if (this.onPreKeyboardObservable.hasObservers()) {
  1869. let pi = new KeyboardInfoPre(type, evt);
  1870. this.onPreKeyboardObservable.notifyObservers(pi, type);
  1871. if (pi.skipOnPointerObservable) {
  1872. return;
  1873. }
  1874. }
  1875. if (this.onKeyboardObservable.hasObservers()) {
  1876. let pi = new KeyboardInfo(type, evt);
  1877. this.onKeyboardObservable.notifyObservers(pi, type);
  1878. }
  1879. if (this.actionManager) {
  1880. this.actionManager.processTrigger(Constants.ACTION_OnKeyDownTrigger, ActionEvent.CreateNewFromScene(this, evt));
  1881. }
  1882. };
  1883. this._onKeyUp = (evt: KeyboardEvent) => {
  1884. let type = KeyboardEventTypes.KEYUP;
  1885. if (this.onPreKeyboardObservable.hasObservers()) {
  1886. let pi = new KeyboardInfoPre(type, evt);
  1887. this.onPreKeyboardObservable.notifyObservers(pi, type);
  1888. if (pi.skipOnPointerObservable) {
  1889. return;
  1890. }
  1891. }
  1892. if (this.onKeyboardObservable.hasObservers()) {
  1893. let pi = new KeyboardInfo(type, evt);
  1894. this.onKeyboardObservable.notifyObservers(pi, type);
  1895. }
  1896. if (this.actionManager) {
  1897. this.actionManager.processTrigger(Constants.ACTION_OnKeyUpTrigger, ActionEvent.CreateNewFromScene(this, evt));
  1898. }
  1899. };
  1900. let engine = this.getEngine();
  1901. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(() => {
  1902. if (!canvas) {
  1903. return;
  1904. }
  1905. canvas.addEventListener("keydown", this._onKeyDown, false);
  1906. canvas.addEventListener("keyup", this._onKeyUp, false);
  1907. });
  1908. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(() => {
  1909. if (!canvas) {
  1910. return;
  1911. }
  1912. canvas.removeEventListener("keydown", this._onKeyDown);
  1913. canvas.removeEventListener("keyup", this._onKeyUp);
  1914. });
  1915. var eventPrefix = Tools.GetPointerPrefix();
  1916. var canvas = this._engine.getRenderingCanvas();
  1917. if (!canvas) {
  1918. return;
  1919. }
  1920. if (attachMove) {
  1921. canvas.addEventListener(eventPrefix + "move", <any>this._onPointerMove, false);
  1922. // Wheel
  1923. this._wheelEventName = "onwheel" in document.createElement("div") ? "wheel" : // Modern browsers support "wheel"
  1924. (<any>document).onmousewheel !== undefined ? "mousewheel" : // Webkit and IE support at least "mousewheel"
  1925. "DOMMouseScroll"; // let's assume that remaining browsers are older Firefox
  1926. canvas.addEventListener(this._wheelEventName, <any>this._onPointerMove, false);
  1927. }
  1928. if (attachDown) {
  1929. canvas.addEventListener(eventPrefix + "down", <any>this._onPointerDown, false);
  1930. }
  1931. if (attachUp) {
  1932. window.addEventListener(eventPrefix + "up", <any>this._onPointerUp, false);
  1933. }
  1934. canvas.tabIndex = 1;
  1935. }
  1936. /** Detaches all event handlers*/
  1937. public detachControl() {
  1938. let engine = this.getEngine();
  1939. var eventPrefix = Tools.GetPointerPrefix();
  1940. var canvas = engine.getRenderingCanvas();
  1941. if (!canvas) {
  1942. return;
  1943. }
  1944. canvas.removeEventListener(eventPrefix + "move", <any>this._onPointerMove);
  1945. canvas.removeEventListener(eventPrefix + "down", <any>this._onPointerDown);
  1946. window.removeEventListener(eventPrefix + "up", <any>this._onPointerUp);
  1947. if (this._onCanvasBlurObserver) {
  1948. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  1949. }
  1950. if (this._onCanvasFocusObserver) {
  1951. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  1952. }
  1953. // Wheel
  1954. canvas.removeEventListener(this._wheelEventName, <any>this._onPointerMove);
  1955. // Keyboard
  1956. canvas.removeEventListener("keydown", this._onKeyDown);
  1957. canvas.removeEventListener("keyup", this._onKeyUp);
  1958. // Observables
  1959. this.onKeyboardObservable.clear();
  1960. this.onPreKeyboardObservable.clear();
  1961. this.onPointerObservable.clear();
  1962. this.onPrePointerObservable.clear();
  1963. }
  1964. /**
  1965. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  1966. * Delay loaded resources are not taking in account
  1967. * @return true if all required resources are ready
  1968. */
  1969. public isReady(): boolean {
  1970. if (this._isDisposed) {
  1971. return false;
  1972. }
  1973. let index: number;
  1974. let engine = this.getEngine();
  1975. // Effects
  1976. if (!engine.areAllEffectsReady()) {
  1977. return false;
  1978. }
  1979. // Pending data
  1980. if (this._pendingData.length > 0) {
  1981. return false;
  1982. }
  1983. // Meshes
  1984. for (index = 0; index < this.meshes.length; index++) {
  1985. var mesh = this.meshes[index];
  1986. if (!mesh.isEnabled()) {
  1987. continue;
  1988. }
  1989. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  1990. continue;
  1991. }
  1992. if (!mesh.isReady(true)) {
  1993. return false;
  1994. }
  1995. let hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || mesh.getClassName() === "InstancedLinesMesh" || engine.getCaps().instancedArrays && (<Mesh>mesh).instances.length > 0;
  1996. // Is Ready For Mesh
  1997. for (let step of this._isReadyForMeshStage) {
  1998. if (!step.action(mesh, hardwareInstancedRendering)) {
  1999. return false;
  2000. }
  2001. }
  2002. }
  2003. // Geometries
  2004. for (index = 0; index < this.geometries.length; index++) {
  2005. var geometry = this.geometries[index];
  2006. if (geometry.delayLoadState === Constants.DELAYLOADSTATE_LOADING) {
  2007. return false;
  2008. }
  2009. }
  2010. // Post-processes
  2011. if (this.activeCameras && this.activeCameras.length > 0) {
  2012. for (var camera of this.activeCameras) {
  2013. if (!camera.isReady(true)) {
  2014. return false;
  2015. }
  2016. }
  2017. } else if (this.activeCamera) {
  2018. if (!this.activeCamera.isReady(true)) {
  2019. return false;
  2020. }
  2021. }
  2022. // Particles
  2023. for (var particleSystem of this.particleSystems) {
  2024. if (!particleSystem.isReady()) {
  2025. return false;
  2026. }
  2027. }
  2028. return true;
  2029. }
  2030. /** Resets all cached information relative to material (including effect and visibility) */
  2031. public resetCachedMaterial(): void {
  2032. this._cachedMaterial = null;
  2033. this._cachedEffect = null;
  2034. this._cachedVisibility = null;
  2035. }
  2036. /**
  2037. * Registers a function to be called before every frame render
  2038. * @param func defines the function to register
  2039. */
  2040. public registerBeforeRender(func: () => void): void {
  2041. this.onBeforeRenderObservable.add(func);
  2042. }
  2043. /**
  2044. * Unregisters a function called before every frame render
  2045. * @param func defines the function to unregister
  2046. */
  2047. public unregisterBeforeRender(func: () => void): void {
  2048. this.onBeforeRenderObservable.removeCallback(func);
  2049. }
  2050. /**
  2051. * Registers a function to be called after every frame render
  2052. * @param func defines the function to register
  2053. */
  2054. public registerAfterRender(func: () => void): void {
  2055. this.onAfterRenderObservable.add(func);
  2056. }
  2057. /**
  2058. * Unregisters a function called after every frame render
  2059. * @param func defines the function to unregister
  2060. */
  2061. public unregisterAfterRender(func: () => void): void {
  2062. this.onAfterRenderObservable.removeCallback(func);
  2063. }
  2064. private _executeOnceBeforeRender(func: () => void): void {
  2065. let execFunc = () => {
  2066. func();
  2067. setTimeout(() => {
  2068. this.unregisterBeforeRender(execFunc);
  2069. });
  2070. };
  2071. this.registerBeforeRender(execFunc);
  2072. }
  2073. /**
  2074. * The provided function will run before render once and will be disposed afterwards.
  2075. * A timeout delay can be provided so that the function will be executed in N ms.
  2076. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  2077. * @param func The function to be executed.
  2078. * @param timeout optional delay in ms
  2079. */
  2080. public executeOnceBeforeRender(func: () => void, timeout?: number): void {
  2081. if (timeout !== undefined) {
  2082. setTimeout(() => {
  2083. this._executeOnceBeforeRender(func);
  2084. }, timeout);
  2085. } else {
  2086. this._executeOnceBeforeRender(func);
  2087. }
  2088. }
  2089. /** @hidden */
  2090. public _addPendingData(data: any): void {
  2091. this._pendingData.push(data);
  2092. }
  2093. /** @hidden */
  2094. public _removePendingData(data: any): void {
  2095. var wasLoading = this.isLoading;
  2096. var index = this._pendingData.indexOf(data);
  2097. if (index !== -1) {
  2098. this._pendingData.splice(index, 1);
  2099. }
  2100. if (wasLoading && !this.isLoading) {
  2101. this.onDataLoadedObservable.notifyObservers(this);
  2102. }
  2103. }
  2104. /**
  2105. * Returns the number of items waiting to be loaded
  2106. * @returns the number of items waiting to be loaded
  2107. */
  2108. public getWaitingItemsCount(): number {
  2109. return this._pendingData.length;
  2110. }
  2111. /**
  2112. * Returns a boolean indicating if the scene is still loading data
  2113. */
  2114. public get isLoading(): boolean {
  2115. return this._pendingData.length > 0;
  2116. }
  2117. /**
  2118. * Registers a function to be executed when the scene is ready
  2119. * @param {Function} func - the function to be executed
  2120. */
  2121. public executeWhenReady(func: () => void): void {
  2122. this.onReadyObservable.add(func);
  2123. if (this._executeWhenReadyTimeoutId !== -1) {
  2124. return;
  2125. }
  2126. this._executeWhenReadyTimeoutId = setTimeout(() => {
  2127. this._checkIsReady();
  2128. }, 150);
  2129. }
  2130. /**
  2131. * Returns a promise that resolves when the scene is ready
  2132. * @returns A promise that resolves when the scene is ready
  2133. */
  2134. public whenReadyAsync(): Promise<void> {
  2135. return new Promise((resolve) => {
  2136. this.executeWhenReady(() => {
  2137. resolve();
  2138. });
  2139. });
  2140. }
  2141. /** @hidden */
  2142. public _checkIsReady() {
  2143. this._registerTransientComponents();
  2144. if (this.isReady()) {
  2145. this.onReadyObservable.notifyObservers(this);
  2146. this.onReadyObservable.clear();
  2147. this._executeWhenReadyTimeoutId = -1;
  2148. return;
  2149. }
  2150. this._executeWhenReadyTimeoutId = setTimeout(() => {
  2151. this._checkIsReady();
  2152. }, 150);
  2153. }
  2154. /**
  2155. * Gets all animatable attached to the scene
  2156. */
  2157. public get animatables(): Animatable[] {
  2158. return this._activeAnimatables;
  2159. }
  2160. /**
  2161. * Resets the last animation time frame.
  2162. * Useful to override when animations start running when loading a scene for the first time.
  2163. */
  2164. public resetLastAnimationTimeFrame(): void {
  2165. this._animationTimeLast = PrecisionDate.Now;
  2166. }
  2167. // Matrix
  2168. /** @hidden */
  2169. public _switchToAlternateCameraConfiguration(active: boolean): void {
  2170. this._useAlternateCameraConfiguration = active;
  2171. }
  2172. /**
  2173. * Gets the current view matrix
  2174. * @returns a Matrix
  2175. */
  2176. public getViewMatrix(): Matrix {
  2177. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  2178. }
  2179. /**
  2180. * Gets the current projection matrix
  2181. * @returns a Matrix
  2182. */
  2183. public getProjectionMatrix(): Matrix {
  2184. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  2185. }
  2186. /**
  2187. * Gets the current transform matrix
  2188. * @returns a Matrix made of View * Projection
  2189. */
  2190. public getTransformMatrix(): Matrix {
  2191. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  2192. }
  2193. /**
  2194. * Sets the current transform matrix
  2195. * @param view defines the View matrix to use
  2196. * @param projection defines the Projection matrix to use
  2197. */
  2198. public setTransformMatrix(view: Matrix, projection: Matrix): void {
  2199. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  2200. return;
  2201. }
  2202. this._viewUpdateFlag = view.updateFlag;
  2203. this._projectionUpdateFlag = projection.updateFlag;
  2204. this._viewMatrix = view;
  2205. this._projectionMatrix = projection;
  2206. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  2207. // Update frustum
  2208. if (!this._frustumPlanes) {
  2209. this._frustumPlanes = Frustum.GetPlanes(this._transformMatrix);
  2210. } else {
  2211. Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  2212. }
  2213. if (this.activeCamera && this.activeCamera._alternateCamera) {
  2214. let otherCamera = this.activeCamera._alternateCamera;
  2215. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), Tmp.Matrix[0]);
  2216. Frustum.GetRightPlaneToRef(Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  2217. }
  2218. if (this._sceneUbo.useUbo) {
  2219. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  2220. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  2221. this._sceneUbo.update();
  2222. }
  2223. }
  2224. /** @hidden */
  2225. public _setAlternateTransformMatrix(view: Matrix, projection: Matrix): void {
  2226. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  2227. return;
  2228. }
  2229. this._alternateViewUpdateFlag = view.updateFlag;
  2230. this._alternateProjectionUpdateFlag = projection.updateFlag;
  2231. this._alternateViewMatrix = view;
  2232. this._alternateProjectionMatrix = projection;
  2233. if (!this._alternateTransformMatrix) {
  2234. this._alternateTransformMatrix = Matrix.Zero();
  2235. }
  2236. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  2237. if (!this._alternateSceneUbo) {
  2238. this._createAlternateUbo();
  2239. }
  2240. if (this._alternateSceneUbo.useUbo) {
  2241. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  2242. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  2243. this._alternateSceneUbo.update();
  2244. }
  2245. }
  2246. /**
  2247. * Gets the uniform buffer used to store scene data
  2248. * @returns a UniformBuffer
  2249. */
  2250. public getSceneUniformBuffer(): UniformBuffer {
  2251. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  2252. }
  2253. /**
  2254. * Gets an unique (relatively to the current scene) Id
  2255. * @returns an unique number for the scene
  2256. */
  2257. public getUniqueId() {
  2258. var result = Scene._uniqueIdCounter;
  2259. Scene._uniqueIdCounter++;
  2260. return result;
  2261. }
  2262. /**
  2263. * Add a mesh to the list of scene's meshes
  2264. * @param newMesh defines the mesh to add
  2265. * @param recursive if all child meshes should also be added to the scene
  2266. */
  2267. public addMesh(newMesh: AbstractMesh, recursive = false) {
  2268. this.meshes.push(newMesh);
  2269. newMesh._resyncLightSources();
  2270. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  2271. if (recursive) {
  2272. newMesh.getChildMeshes().forEach((m) => {
  2273. this.addMesh(m);
  2274. });
  2275. }
  2276. }
  2277. /**
  2278. * Remove a mesh for the list of scene's meshes
  2279. * @param toRemove defines the mesh to remove
  2280. * @param recursive if all child meshes should also be removed from the scene
  2281. * @returns the index where the mesh was in the mesh list
  2282. */
  2283. public removeMesh(toRemove: AbstractMesh, recursive = false): number {
  2284. var index = this.meshes.indexOf(toRemove);
  2285. if (index !== -1) {
  2286. // Remove from the scene if mesh found
  2287. this.meshes[index] = this.meshes[this.meshes.length - 1];
  2288. this.meshes.pop();
  2289. }
  2290. this.onMeshRemovedObservable.notifyObservers(toRemove);
  2291. if (recursive) {
  2292. toRemove.getChildMeshes().forEach((m) => {
  2293. this.removeMesh(m);
  2294. });
  2295. }
  2296. return index;
  2297. }
  2298. /**
  2299. * Add a transform node to the list of scene's transform nodes
  2300. * @param newTransformNode defines the transform node to add
  2301. */
  2302. public addTransformNode(newTransformNode: TransformNode) {
  2303. newTransformNode._indexInSceneTransformNodesArray = this.transformNodes.length;
  2304. this.transformNodes.push(newTransformNode);
  2305. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  2306. }
  2307. /**
  2308. * Remove a transform node for the list of scene's transform nodes
  2309. * @param toRemove defines the transform node to remove
  2310. * @returns the index where the transform node was in the transform node list
  2311. */
  2312. public removeTransformNode(toRemove: TransformNode): number {
  2313. var index = toRemove._indexInSceneTransformNodesArray;
  2314. if (index !== -1) {
  2315. if (index !== this.transformNodes.length - 1) {
  2316. const lastNode = this.transformNodes[this.transformNodes.length - 1];
  2317. this.transformNodes[index] = lastNode;
  2318. lastNode._indexInSceneTransformNodesArray = index;
  2319. }
  2320. toRemove._indexInSceneTransformNodesArray = -1;
  2321. this.transformNodes.pop();
  2322. }
  2323. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  2324. return index;
  2325. }
  2326. /**
  2327. * Remove a skeleton for the list of scene's skeletons
  2328. * @param toRemove defines the skeleton to remove
  2329. * @returns the index where the skeleton was in the skeleton list
  2330. */
  2331. public removeSkeleton(toRemove: Skeleton): number {
  2332. var index = this.skeletons.indexOf(toRemove);
  2333. if (index !== -1) {
  2334. // Remove from the scene if found
  2335. this.skeletons.splice(index, 1);
  2336. this.onSkeletonRemovedObservable.notifyObservers(toRemove);
  2337. }
  2338. return index;
  2339. }
  2340. /**
  2341. * Remove a morph target for the list of scene's morph targets
  2342. * @param toRemove defines the morph target to remove
  2343. * @returns the index where the morph target was in the morph target list
  2344. */
  2345. public removeMorphTargetManager(toRemove: MorphTargetManager): number {
  2346. var index = this.morphTargetManagers.indexOf(toRemove);
  2347. if (index !== -1) {
  2348. // Remove from the scene if found
  2349. this.morphTargetManagers.splice(index, 1);
  2350. }
  2351. return index;
  2352. }
  2353. /**
  2354. * Remove a light for the list of scene's lights
  2355. * @param toRemove defines the light to remove
  2356. * @returns the index where the light was in the light list
  2357. */
  2358. public removeLight(toRemove: Light): number {
  2359. var index = this.lights.indexOf(toRemove);
  2360. if (index !== -1) {
  2361. // Remove from meshes
  2362. for (var mesh of this.meshes) {
  2363. mesh._removeLightSource(toRemove);
  2364. }
  2365. // Remove from the scene if mesh found
  2366. this.lights.splice(index, 1);
  2367. this.sortLightsByPriority();
  2368. }
  2369. this.onLightRemovedObservable.notifyObservers(toRemove);
  2370. return index;
  2371. }
  2372. /**
  2373. * Remove a camera for the list of scene's cameras
  2374. * @param toRemove defines the camera to remove
  2375. * @returns the index where the camera was in the camera list
  2376. */
  2377. public removeCamera(toRemove: Camera): number {
  2378. var index = this.cameras.indexOf(toRemove);
  2379. if (index !== -1) {
  2380. // Remove from the scene if mesh found
  2381. this.cameras.splice(index, 1);
  2382. }
  2383. // Remove from activeCameras
  2384. var index2 = this.activeCameras.indexOf(toRemove);
  2385. if (index2 !== -1) {
  2386. // Remove from the scene if mesh found
  2387. this.activeCameras.splice(index2, 1);
  2388. }
  2389. // Reset the activeCamera
  2390. if (this.activeCamera === toRemove) {
  2391. if (this.cameras.length > 0) {
  2392. this.activeCamera = this.cameras[0];
  2393. } else {
  2394. this.activeCamera = null;
  2395. }
  2396. }
  2397. this.onCameraRemovedObservable.notifyObservers(toRemove);
  2398. return index;
  2399. }
  2400. /**
  2401. * Remove a particle system for the list of scene's particle systems
  2402. * @param toRemove defines the particle system to remove
  2403. * @returns the index where the particle system was in the particle system list
  2404. */
  2405. public removeParticleSystem(toRemove: IParticleSystem): number {
  2406. var index = this.particleSystems.indexOf(toRemove);
  2407. if (index !== -1) {
  2408. this.particleSystems.splice(index, 1);
  2409. }
  2410. return index;
  2411. }
  2412. /**
  2413. * Remove a animation for the list of scene's animations
  2414. * @param toRemove defines the animation to remove
  2415. * @returns the index where the animation was in the animation list
  2416. */
  2417. public removeAnimation(toRemove: Animation): number {
  2418. var index = this.animations.indexOf(toRemove);
  2419. if (index !== -1) {
  2420. this.animations.splice(index, 1);
  2421. }
  2422. return index;
  2423. }
  2424. /**
  2425. * Removes the given animation group from this scene.
  2426. * @param toRemove The animation group to remove
  2427. * @returns The index of the removed animation group
  2428. */
  2429. public removeAnimationGroup(toRemove: AnimationGroup): number {
  2430. var index = this.animationGroups.indexOf(toRemove);
  2431. if (index !== -1) {
  2432. this.animationGroups.splice(index, 1);
  2433. }
  2434. return index;
  2435. }
  2436. /**
  2437. * Removes the given multi-material from this scene.
  2438. * @param toRemove The multi-material to remove
  2439. * @returns The index of the removed multi-material
  2440. */
  2441. public removeMultiMaterial(toRemove: MultiMaterial): number {
  2442. var index = this.multiMaterials.indexOf(toRemove);
  2443. if (index !== -1) {
  2444. this.multiMaterials.splice(index, 1);
  2445. }
  2446. return index;
  2447. }
  2448. /**
  2449. * Removes the given material from this scene.
  2450. * @param toRemove The material to remove
  2451. * @returns The index of the removed material
  2452. */
  2453. public removeMaterial(toRemove: Material): number {
  2454. var index = toRemove._indexInSceneMaterialArray;
  2455. if (index !== -1 && index < this.materials.length) {
  2456. if (index !== this.materials.length - 1) {
  2457. const lastMaterial = this.materials[this.materials.length - 1];
  2458. this.materials[index] = lastMaterial;
  2459. lastMaterial._indexInSceneMaterialArray = index;
  2460. }
  2461. toRemove._indexInSceneMaterialArray = -1;
  2462. this.materials.pop();
  2463. }
  2464. this.onMaterialRemovedObservable.notifyObservers(toRemove);
  2465. return index;
  2466. }
  2467. /**
  2468. * Removes the given action manager from this scene.
  2469. * @param toRemove The action manager to remove
  2470. * @returns The index of the removed action manager
  2471. */
  2472. public removeActionManager(toRemove: AbstractActionManager): number {
  2473. var index = this.actionManagers.indexOf(toRemove);
  2474. if (index !== -1) {
  2475. this.actionManagers.splice(index, 1);
  2476. }
  2477. return index;
  2478. }
  2479. /**
  2480. * Removes the given texture from this scene.
  2481. * @param toRemove The texture to remove
  2482. * @returns The index of the removed texture
  2483. */
  2484. public removeTexture(toRemove: BaseTexture): number {
  2485. var index = this.textures.indexOf(toRemove);
  2486. if (index !== -1) {
  2487. this.textures.splice(index, 1);
  2488. }
  2489. this.onTextureRemovedObservable.notifyObservers(toRemove);
  2490. return index;
  2491. }
  2492. /**
  2493. * Adds the given light to this scene
  2494. * @param newLight The light to add
  2495. */
  2496. public addLight(newLight: Light): void {
  2497. this.lights.push(newLight);
  2498. this.sortLightsByPriority();
  2499. // Add light to all meshes (To support if the light is removed and then readded)
  2500. for (var mesh of this.meshes) {
  2501. if (mesh._lightSources.indexOf(newLight) === -1) {
  2502. mesh._lightSources.push(newLight);
  2503. mesh._resyncLightSources();
  2504. }
  2505. }
  2506. this.onNewLightAddedObservable.notifyObservers(newLight);
  2507. }
  2508. /**
  2509. * Sorts the list list based on light priorities
  2510. */
  2511. public sortLightsByPriority(): void {
  2512. if (this.requireLightSorting) {
  2513. this.lights.sort(Light.CompareLightsPriority);
  2514. }
  2515. }
  2516. /**
  2517. * Adds the given camera to this scene
  2518. * @param newCamera The camera to add
  2519. */
  2520. public addCamera(newCamera: Camera): void {
  2521. this.cameras.push(newCamera);
  2522. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  2523. }
  2524. /**
  2525. * Adds the given skeleton to this scene
  2526. * @param newSkeleton The skeleton to add
  2527. */
  2528. public addSkeleton(newSkeleton: Skeleton): void {
  2529. this.skeletons.push(newSkeleton);
  2530. this.onNewSkeletonAddedObservable.notifyObservers(newSkeleton);
  2531. }
  2532. /**
  2533. * Adds the given particle system to this scene
  2534. * @param newParticleSystem The particle system to add
  2535. */
  2536. public addParticleSystem(newParticleSystem: IParticleSystem): void {
  2537. this.particleSystems.push(newParticleSystem);
  2538. }
  2539. /**
  2540. * Adds the given animation to this scene
  2541. * @param newAnimation The animation to add
  2542. */
  2543. public addAnimation(newAnimation: Animation): void {
  2544. this.animations.push(newAnimation);
  2545. }
  2546. /**
  2547. * Adds the given animation group to this scene.
  2548. * @param newAnimationGroup The animation group to add
  2549. */
  2550. public addAnimationGroup(newAnimationGroup: AnimationGroup): void {
  2551. this.animationGroups.push(newAnimationGroup);
  2552. }
  2553. /**
  2554. * Adds the given multi-material to this scene
  2555. * @param newMultiMaterial The multi-material to add
  2556. */
  2557. public addMultiMaterial(newMultiMaterial: MultiMaterial): void {
  2558. this.multiMaterials.push(newMultiMaterial);
  2559. }
  2560. /**
  2561. * Adds the given material to this scene
  2562. * @param newMaterial The material to add
  2563. */
  2564. public addMaterial(newMaterial: Material): void {
  2565. newMaterial._indexInSceneMaterialArray = this.materials.length;
  2566. this.materials.push(newMaterial);
  2567. this.onNewMaterialAddedObservable.notifyObservers(newMaterial);
  2568. }
  2569. /**
  2570. * Adds the given morph target to this scene
  2571. * @param newMorphTargetManager The morph target to add
  2572. */
  2573. public addMorphTargetManager(newMorphTargetManager: MorphTargetManager): void {
  2574. this.morphTargetManagers.push(newMorphTargetManager);
  2575. }
  2576. /**
  2577. * Adds the given geometry to this scene
  2578. * @param newGeometry The geometry to add
  2579. */
  2580. public addGeometry(newGeometry: Geometry): void {
  2581. if (this.geometriesByUniqueId) {
  2582. this.geometriesByUniqueId[newGeometry.uniqueId] = this.geometries.length;
  2583. }
  2584. this.geometries.push(newGeometry);
  2585. }
  2586. /**
  2587. * Adds the given action manager to this scene
  2588. * @param newActionManager The action manager to add
  2589. */
  2590. public addActionManager(newActionManager: AbstractActionManager): void {
  2591. this.actionManagers.push(newActionManager);
  2592. }
  2593. /**
  2594. * Adds the given texture to this scene.
  2595. * @param newTexture The texture to add
  2596. */
  2597. public addTexture(newTexture: BaseTexture): void {
  2598. this.textures.push(newTexture);
  2599. this.onNewTextureAddedObservable.notifyObservers(newTexture);
  2600. }
  2601. /**
  2602. * Switch active camera
  2603. * @param newCamera defines the new active camera
  2604. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  2605. */
  2606. public switchActiveCamera(newCamera: Camera, attachControl = true): void {
  2607. var canvas = this._engine.getRenderingCanvas();
  2608. if (!canvas) {
  2609. return;
  2610. }
  2611. if (this.activeCamera) {
  2612. this.activeCamera.detachControl(canvas);
  2613. }
  2614. this.activeCamera = newCamera;
  2615. if (attachControl) {
  2616. newCamera.attachControl(canvas);
  2617. }
  2618. }
  2619. /**
  2620. * sets the active camera of the scene using its ID
  2621. * @param id defines the camera's ID
  2622. * @return the new active camera or null if none found.
  2623. */
  2624. public setActiveCameraByID(id: string): Nullable<Camera> {
  2625. var camera = this.getCameraByID(id);
  2626. if (camera) {
  2627. this.activeCamera = camera;
  2628. return camera;
  2629. }
  2630. return null;
  2631. }
  2632. /**
  2633. * sets the active camera of the scene using its name
  2634. * @param name defines the camera's name
  2635. * @returns the new active camera or null if none found.
  2636. */
  2637. public setActiveCameraByName(name: string): Nullable<Camera> {
  2638. var camera = this.getCameraByName(name);
  2639. if (camera) {
  2640. this.activeCamera = camera;
  2641. return camera;
  2642. }
  2643. return null;
  2644. }
  2645. /**
  2646. * get an animation group using its name
  2647. * @param name defines the material's name
  2648. * @return the animation group or null if none found.
  2649. */
  2650. public getAnimationGroupByName(name: string): Nullable<AnimationGroup> {
  2651. for (var index = 0; index < this.animationGroups.length; index++) {
  2652. if (this.animationGroups[index].name === name) {
  2653. return this.animationGroups[index];
  2654. }
  2655. }
  2656. return null;
  2657. }
  2658. /**
  2659. * Get a material using its unique id
  2660. * @param uniqueId defines the material's unique id
  2661. * @return the material or null if none found.
  2662. */
  2663. public getMaterialByUniqueID(uniqueId: number): Nullable<Material> {
  2664. for (var index = 0; index < this.materials.length; index++) {
  2665. if (this.materials[index].uniqueId === uniqueId) {
  2666. return this.materials[index];
  2667. }
  2668. }
  2669. return null;
  2670. }
  2671. /**
  2672. * get a material using its id
  2673. * @param id defines the material's ID
  2674. * @return the material or null if none found.
  2675. */
  2676. public getMaterialByID(id: string): Nullable<Material> {
  2677. for (var index = 0; index < this.materials.length; index++) {
  2678. if (this.materials[index].id === id) {
  2679. return this.materials[index];
  2680. }
  2681. }
  2682. return null;
  2683. }
  2684. /**
  2685. * Gets a material using its name
  2686. * @param name defines the material's name
  2687. * @return the material or null if none found.
  2688. */
  2689. public getMaterialByName(name: string): Nullable<Material> {
  2690. for (var index = 0; index < this.materials.length; index++) {
  2691. if (this.materials[index].name === name) {
  2692. return this.materials[index];
  2693. }
  2694. }
  2695. return null;
  2696. }
  2697. /**
  2698. * Gets a camera using its id
  2699. * @param id defines the id to look for
  2700. * @returns the camera or null if not found
  2701. */
  2702. public getCameraByID(id: string): Nullable<Camera> {
  2703. for (var index = 0; index < this.cameras.length; index++) {
  2704. if (this.cameras[index].id === id) {
  2705. return this.cameras[index];
  2706. }
  2707. }
  2708. return null;
  2709. }
  2710. /**
  2711. * Gets a camera using its unique id
  2712. * @param uniqueId defines the unique id to look for
  2713. * @returns the camera or null if not found
  2714. */
  2715. public getCameraByUniqueID(uniqueId: number): Nullable<Camera> {
  2716. for (var index = 0; index < this.cameras.length; index++) {
  2717. if (this.cameras[index].uniqueId === uniqueId) {
  2718. return this.cameras[index];
  2719. }
  2720. }
  2721. return null;
  2722. }
  2723. /**
  2724. * Gets a camera using its name
  2725. * @param name defines the camera's name
  2726. * @return the camera or null if none found.
  2727. */
  2728. public getCameraByName(name: string): Nullable<Camera> {
  2729. for (var index = 0; index < this.cameras.length; index++) {
  2730. if (this.cameras[index].name === name) {
  2731. return this.cameras[index];
  2732. }
  2733. }
  2734. return null;
  2735. }
  2736. /**
  2737. * Gets a bone using its id
  2738. * @param id defines the bone's id
  2739. * @return the bone or null if not found
  2740. */
  2741. public getBoneByID(id: string): Nullable<Bone> {
  2742. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  2743. var skeleton = this.skeletons[skeletonIndex];
  2744. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  2745. if (skeleton.bones[boneIndex].id === id) {
  2746. return skeleton.bones[boneIndex];
  2747. }
  2748. }
  2749. }
  2750. return null;
  2751. }
  2752. /**
  2753. * Gets a bone using its id
  2754. * @param name defines the bone's name
  2755. * @return the bone or null if not found
  2756. */
  2757. public getBoneByName(name: string): Nullable<Bone> {
  2758. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  2759. var skeleton = this.skeletons[skeletonIndex];
  2760. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  2761. if (skeleton.bones[boneIndex].name === name) {
  2762. return skeleton.bones[boneIndex];
  2763. }
  2764. }
  2765. }
  2766. return null;
  2767. }
  2768. /**
  2769. * Gets a light node using its name
  2770. * @param name defines the the light's name
  2771. * @return the light or null if none found.
  2772. */
  2773. public getLightByName(name: string): Nullable<Light> {
  2774. for (var index = 0; index < this.lights.length; index++) {
  2775. if (this.lights[index].name === name) {
  2776. return this.lights[index];
  2777. }
  2778. }
  2779. return null;
  2780. }
  2781. /**
  2782. * Gets a light node using its id
  2783. * @param id defines the light's id
  2784. * @return the light or null if none found.
  2785. */
  2786. public getLightByID(id: string): Nullable<Light> {
  2787. for (var index = 0; index < this.lights.length; index++) {
  2788. if (this.lights[index].id === id) {
  2789. return this.lights[index];
  2790. }
  2791. }
  2792. return null;
  2793. }
  2794. /**
  2795. * Gets a light node using its scene-generated unique ID
  2796. * @param uniqueId defines the light's unique id
  2797. * @return the light or null if none found.
  2798. */
  2799. public getLightByUniqueID(uniqueId: number): Nullable<Light> {
  2800. for (var index = 0; index < this.lights.length; index++) {
  2801. if (this.lights[index].uniqueId === uniqueId) {
  2802. return this.lights[index];
  2803. }
  2804. }
  2805. return null;
  2806. }
  2807. /**
  2808. * Gets a particle system by id
  2809. * @param id defines the particle system id
  2810. * @return the corresponding system or null if none found
  2811. */
  2812. public getParticleSystemByID(id: string): Nullable<IParticleSystem> {
  2813. for (var index = 0; index < this.particleSystems.length; index++) {
  2814. if (this.particleSystems[index].id === id) {
  2815. return this.particleSystems[index];
  2816. }
  2817. }
  2818. return null;
  2819. }
  2820. /**
  2821. * Gets a geometry using its ID
  2822. * @param id defines the geometry's id
  2823. * @return the geometry or null if none found.
  2824. */
  2825. public getGeometryByID(id: string): Nullable<Geometry> {
  2826. for (var index = 0; index < this.geometries.length; index++) {
  2827. if (this.geometries[index].id === id) {
  2828. return this.geometries[index];
  2829. }
  2830. }
  2831. return null;
  2832. }
  2833. private _getGeometryByUniqueID(uniqueId: number): Nullable<Geometry> {
  2834. if (this.geometriesByUniqueId) {
  2835. const index = this.geometriesByUniqueId[uniqueId];
  2836. if (index !== undefined) {
  2837. return this.geometries[index];
  2838. }
  2839. }
  2840. else {
  2841. for (var index = 0; index < this.geometries.length; index++) {
  2842. if (this.geometries[index].uniqueId === uniqueId) {
  2843. return this.geometries[index];
  2844. }
  2845. }
  2846. }
  2847. return null;
  2848. }
  2849. /**
  2850. * Add a new geometry to this scene
  2851. * @param geometry defines the geometry to be added to the scene.
  2852. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  2853. * @return a boolean defining if the geometry was added or not
  2854. */
  2855. public pushGeometry(geometry: Geometry, force?: boolean): boolean {
  2856. if (!force && this._getGeometryByUniqueID(geometry.uniqueId)) {
  2857. return false;
  2858. }
  2859. this.addGeometry(geometry);
  2860. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  2861. return true;
  2862. }
  2863. /**
  2864. * Removes an existing geometry
  2865. * @param geometry defines the geometry to be removed from the scene
  2866. * @return a boolean defining if the geometry was removed or not
  2867. */
  2868. public removeGeometry(geometry: Geometry): boolean {
  2869. let index;
  2870. if (this.geometriesByUniqueId) {
  2871. index = this.geometriesByUniqueId[geometry.uniqueId];
  2872. if (index === undefined) {
  2873. return false;
  2874. }
  2875. }
  2876. else {
  2877. index = this.geometries.indexOf(geometry);
  2878. if (index < 0) {
  2879. return false;
  2880. }
  2881. }
  2882. if (index !== this.geometries.length - 1) {
  2883. const lastGeometry = this.geometries[this.geometries.length - 1];
  2884. this.geometries[index] = lastGeometry;
  2885. if (this.geometriesByUniqueId) {
  2886. this.geometriesByUniqueId[lastGeometry.uniqueId] = index;
  2887. this.geometriesByUniqueId[geometry.uniqueId] = undefined;
  2888. }
  2889. }
  2890. this.geometries.pop();
  2891. this.onGeometryRemovedObservable.notifyObservers(geometry);
  2892. return true;
  2893. }
  2894. /**
  2895. * Gets the list of geometries attached to the scene
  2896. * @returns an array of Geometry
  2897. */
  2898. public getGeometries(): Geometry[] {
  2899. return this.geometries;
  2900. }
  2901. /**
  2902. * Gets the first added mesh found of a given ID
  2903. * @param id defines the id to search for
  2904. * @return the mesh found or null if not found at all
  2905. */
  2906. public getMeshByID(id: string): Nullable<AbstractMesh> {
  2907. for (var index = 0; index < this.meshes.length; index++) {
  2908. if (this.meshes[index].id === id) {
  2909. return this.meshes[index];
  2910. }
  2911. }
  2912. return null;
  2913. }
  2914. /**
  2915. * Gets a list of meshes using their id
  2916. * @param id defines the id to search for
  2917. * @returns a list of meshes
  2918. */
  2919. public getMeshesByID(id: string): Array<AbstractMesh> {
  2920. return this.meshes.filter(function(m) {
  2921. return m.id === id;
  2922. });
  2923. }
  2924. /**
  2925. * Gets the first added transform node found of a given ID
  2926. * @param id defines the id to search for
  2927. * @return the found transform node or null if not found at all.
  2928. */
  2929. public getTransformNodeByID(id: string): Nullable<TransformNode> {
  2930. for (var index = 0; index < this.transformNodes.length; index++) {
  2931. if (this.transformNodes[index].id === id) {
  2932. return this.transformNodes[index];
  2933. }
  2934. }
  2935. return null;
  2936. }
  2937. /**
  2938. * Gets a transform node with its auto-generated unique id
  2939. * @param uniqueId efines the unique id to search for
  2940. * @return the found transform node or null if not found at all.
  2941. */
  2942. public getTransformNodeByUniqueID(uniqueId: number): Nullable<TransformNode> {
  2943. for (var index = 0; index < this.transformNodes.length; index++) {
  2944. if (this.transformNodes[index].uniqueId === uniqueId) {
  2945. return this.transformNodes[index];
  2946. }
  2947. }
  2948. return null;
  2949. }
  2950. /**
  2951. * Gets a list of transform nodes using their id
  2952. * @param id defines the id to search for
  2953. * @returns a list of transform nodes
  2954. */
  2955. public getTransformNodesByID(id: string): Array<TransformNode> {
  2956. return this.transformNodes.filter(function(m) {
  2957. return m.id === id;
  2958. });
  2959. }
  2960. /**
  2961. * Gets a mesh with its auto-generated unique id
  2962. * @param uniqueId defines the unique id to search for
  2963. * @return the found mesh or null if not found at all.
  2964. */
  2965. public getMeshByUniqueID(uniqueId: number): Nullable<AbstractMesh> {
  2966. for (var index = 0; index < this.meshes.length; index++) {
  2967. if (this.meshes[index].uniqueId === uniqueId) {
  2968. return this.meshes[index];
  2969. }
  2970. }
  2971. return null;
  2972. }
  2973. /**
  2974. * Gets a the last added mesh using a given id
  2975. * @param id defines the id to search for
  2976. * @return the found mesh or null if not found at all.
  2977. */
  2978. public getLastMeshByID(id: string): Nullable<AbstractMesh> {
  2979. for (var index = this.meshes.length - 1; index >= 0; index--) {
  2980. if (this.meshes[index].id === id) {
  2981. return this.meshes[index];
  2982. }
  2983. }
  2984. return null;
  2985. }
  2986. /**
  2987. * Gets a the last added node (Mesh, Camera, Light) using a given id
  2988. * @param id defines the id to search for
  2989. * @return the found node or null if not found at all
  2990. */
  2991. public getLastEntryByID(id: string): Nullable<Node> {
  2992. var index: number;
  2993. for (index = this.meshes.length - 1; index >= 0; index--) {
  2994. if (this.meshes[index].id === id) {
  2995. return this.meshes[index];
  2996. }
  2997. }
  2998. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  2999. if (this.transformNodes[index].id === id) {
  3000. return this.transformNodes[index];
  3001. }
  3002. }
  3003. for (index = this.cameras.length - 1; index >= 0; index--) {
  3004. if (this.cameras[index].id === id) {
  3005. return this.cameras[index];
  3006. }
  3007. }
  3008. for (index = this.lights.length - 1; index >= 0; index--) {
  3009. if (this.lights[index].id === id) {
  3010. return this.lights[index];
  3011. }
  3012. }
  3013. return null;
  3014. }
  3015. /**
  3016. * Gets a node (Mesh, Camera, Light) using a given id
  3017. * @param id defines the id to search for
  3018. * @return the found node or null if not found at all
  3019. */
  3020. public getNodeByID(id: string): Nullable<Node> {
  3021. const mesh = this.getMeshByID(id);
  3022. if (mesh) {
  3023. return mesh;
  3024. }
  3025. const transformNode = this.getTransformNodeByID(id);
  3026. if (transformNode) {
  3027. return transformNode;
  3028. }
  3029. const light = this.getLightByID(id);
  3030. if (light) {
  3031. return light;
  3032. }
  3033. const camera = this.getCameraByID(id);
  3034. if (camera) {
  3035. return camera;
  3036. }
  3037. const bone = this.getBoneByID(id);
  3038. if (bone) {
  3039. return bone;
  3040. }
  3041. return null;
  3042. }
  3043. /**
  3044. * Gets a node (Mesh, Camera, Light) using a given name
  3045. * @param name defines the name to search for
  3046. * @return the found node or null if not found at all.
  3047. */
  3048. public getNodeByName(name: string): Nullable<Node> {
  3049. const mesh = this.getMeshByName(name);
  3050. if (mesh) {
  3051. return mesh;
  3052. }
  3053. const transformNode = this.getTransformNodeByName(name);
  3054. if (transformNode) {
  3055. return transformNode;
  3056. }
  3057. const light = this.getLightByName(name);
  3058. if (light) {
  3059. return light;
  3060. }
  3061. const camera = this.getCameraByName(name);
  3062. if (camera) {
  3063. return camera;
  3064. }
  3065. const bone = this.getBoneByName(name);
  3066. if (bone) {
  3067. return bone;
  3068. }
  3069. return null;
  3070. }
  3071. /**
  3072. * Gets a mesh using a given name
  3073. * @param name defines the name to search for
  3074. * @return the found mesh or null if not found at all.
  3075. */
  3076. public getMeshByName(name: string): Nullable<AbstractMesh> {
  3077. for (var index = 0; index < this.meshes.length; index++) {
  3078. if (this.meshes[index].name === name) {
  3079. return this.meshes[index];
  3080. }
  3081. }
  3082. return null;
  3083. }
  3084. /**
  3085. * Gets a transform node using a given name
  3086. * @param name defines the name to search for
  3087. * @return the found transform node or null if not found at all.
  3088. */
  3089. public getTransformNodeByName(name: string): Nullable<TransformNode> {
  3090. for (var index = 0; index < this.transformNodes.length; index++) {
  3091. if (this.transformNodes[index].name === name) {
  3092. return this.transformNodes[index];
  3093. }
  3094. }
  3095. return null;
  3096. }
  3097. /**
  3098. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  3099. * @param id defines the id to search for
  3100. * @return the found skeleton or null if not found at all.
  3101. */
  3102. public getLastSkeletonByID(id: string): Nullable<Skeleton> {
  3103. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  3104. if (this.skeletons[index].id === id) {
  3105. return this.skeletons[index];
  3106. }
  3107. }
  3108. return null;
  3109. }
  3110. /**
  3111. * Gets a skeleton using a given auto generated unique id
  3112. * @param uniqueId defines the unique id to search for
  3113. * @return the found skeleton or null if not found at all.
  3114. */
  3115. public getSkeletonByUniqueId(uniqueId: number): Nullable<Skeleton> {
  3116. for (var index = 0; index < this.skeletons.length; index++) {
  3117. if (this.skeletons[index].uniqueId === uniqueId) {
  3118. return this.skeletons[index];
  3119. }
  3120. }
  3121. return null;
  3122. }
  3123. /**
  3124. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  3125. * @param id defines the id to search for
  3126. * @return the found skeleton or null if not found at all.
  3127. */
  3128. public getSkeletonById(id: string): Nullable<Skeleton> {
  3129. for (var index = 0; index < this.skeletons.length; index++) {
  3130. if (this.skeletons[index].id === id) {
  3131. return this.skeletons[index];
  3132. }
  3133. }
  3134. return null;
  3135. }
  3136. /**
  3137. * Gets a skeleton using a given name
  3138. * @param name defines the name to search for
  3139. * @return the found skeleton or null if not found at all.
  3140. */
  3141. public getSkeletonByName(name: string): Nullable<Skeleton> {
  3142. for (var index = 0; index < this.skeletons.length; index++) {
  3143. if (this.skeletons[index].name === name) {
  3144. return this.skeletons[index];
  3145. }
  3146. }
  3147. return null;
  3148. }
  3149. /**
  3150. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  3151. * @param id defines the id to search for
  3152. * @return the found morph target manager or null if not found at all.
  3153. */
  3154. public getMorphTargetManagerById(id: number): Nullable<MorphTargetManager> {
  3155. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  3156. if (this.morphTargetManagers[index].uniqueId === id) {
  3157. return this.morphTargetManagers[index];
  3158. }
  3159. }
  3160. return null;
  3161. }
  3162. /**
  3163. * Gets a morph target using a given id (if many are found, this function will pick the first one)
  3164. * @param id defines the id to search for
  3165. * @return the found morph target or null if not found at all.
  3166. */
  3167. public getMorphTargetById(id: string): Nullable<MorphTarget> {
  3168. for (let managerIndex = 0; managerIndex < this.morphTargetManagers.length; ++managerIndex) {
  3169. const morphTargetManager = this.morphTargetManagers[managerIndex];
  3170. for (let index = 0; index < morphTargetManager.numTargets; ++index) {
  3171. const target = morphTargetManager.getTarget(index);
  3172. if (target.id === id) {
  3173. return target;
  3174. }
  3175. }
  3176. }
  3177. return null;
  3178. }
  3179. /**
  3180. * Gets a boolean indicating if the given mesh is active
  3181. * @param mesh defines the mesh to look for
  3182. * @returns true if the mesh is in the active list
  3183. */
  3184. public isActiveMesh(mesh: AbstractMesh): boolean {
  3185. return (this._activeMeshes.indexOf(mesh) !== -1);
  3186. }
  3187. /**
  3188. * Return a unique id as a string which can serve as an identifier for the scene
  3189. */
  3190. public get uid(): string {
  3191. if (!this._uid) {
  3192. this._uid = Tools.RandomId();
  3193. }
  3194. return this._uid;
  3195. }
  3196. /**
  3197. * Add an externaly attached data from its key.
  3198. * This method call will fail and return false, if such key already exists.
  3199. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  3200. * @param key the unique key that identifies the data
  3201. * @param data the data object to associate to the key for this Engine instance
  3202. * @return true if no such key were already present and the data was added successfully, false otherwise
  3203. */
  3204. public addExternalData<T>(key: string, data: T): boolean {
  3205. if (!this._externalData) {
  3206. this._externalData = new StringDictionary<Object>();
  3207. }
  3208. return this._externalData.add(key, data);
  3209. }
  3210. /**
  3211. * Get an externaly attached data from its key
  3212. * @param key the unique key that identifies the data
  3213. * @return the associated data, if present (can be null), or undefined if not present
  3214. */
  3215. public getExternalData<T>(key: string): Nullable<T> {
  3216. if (!this._externalData) {
  3217. return null;
  3218. }
  3219. return <T>this._externalData.get(key);
  3220. }
  3221. /**
  3222. * Get an externaly attached data from its key, create it using a factory if it's not already present
  3223. * @param key the unique key that identifies the data
  3224. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  3225. * @return the associated data, can be null if the factory returned null.
  3226. */
  3227. public getOrAddExternalDataWithFactory<T>(key: string, factory: (k: string) => T): T {
  3228. if (!this._externalData) {
  3229. this._externalData = new StringDictionary<Object>();
  3230. }
  3231. return <T>this._externalData.getOrAddWithFactory(key, factory);
  3232. }
  3233. /**
  3234. * Remove an externaly attached data from the Engine instance
  3235. * @param key the unique key that identifies the data
  3236. * @return true if the data was successfully removed, false if it doesn't exist
  3237. */
  3238. public removeExternalData(key: string): boolean {
  3239. return this._externalData.remove(key);
  3240. }
  3241. private _evaluateSubMesh(subMesh: SubMesh, mesh: AbstractMesh): void {
  3242. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  3243. for (let step of this._evaluateSubMeshStage) {
  3244. step.action(mesh, subMesh);
  3245. }
  3246. const material = subMesh.getMaterial();
  3247. if (material !== null && material !== undefined) {
  3248. // Render targets
  3249. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  3250. if (this._processedMaterials.indexOf(material) === -1) {
  3251. this._processedMaterials.push(material);
  3252. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  3253. }
  3254. }
  3255. // Dispatch
  3256. this._activeIndices.addCount(subMesh.indexCount, false);
  3257. this._renderingManager.dispatch(subMesh, mesh, material);
  3258. }
  3259. }
  3260. }
  3261. /**
  3262. * Clear the processed materials smart array preventing retention point in material dispose.
  3263. */
  3264. public freeProcessedMaterials(): void {
  3265. this._processedMaterials.dispose();
  3266. }
  3267. private _preventFreeActiveMeshesAndRenderingGroups = false;
  3268. /** Gets or sets a boolean blocking all the calls to freeActiveMeshes and freeRenderingGroups
  3269. * It can be used in order to prevent going through methods freeRenderingGroups and freeActiveMeshes several times to improve performance
  3270. * when disposing several meshes in a row or a hierarchy of meshes.
  3271. * When used, it is the responsability of the user to blockfreeActiveMeshesAndRenderingGroups back to false.
  3272. */
  3273. public get blockfreeActiveMeshesAndRenderingGroups(): boolean {
  3274. return this._preventFreeActiveMeshesAndRenderingGroups;
  3275. }
  3276. public set blockfreeActiveMeshesAndRenderingGroups(value: boolean) {
  3277. if (this._preventFreeActiveMeshesAndRenderingGroups === value) {
  3278. return;
  3279. }
  3280. if (value) {
  3281. this.freeActiveMeshes();
  3282. this.freeRenderingGroups();
  3283. }
  3284. this._preventFreeActiveMeshesAndRenderingGroups = value;
  3285. }
  3286. /**
  3287. * Clear the active meshes smart array preventing retention point in mesh dispose.
  3288. */
  3289. public freeActiveMeshes(): void {
  3290. if (this.blockfreeActiveMeshesAndRenderingGroups) {
  3291. return;
  3292. }
  3293. this._activeMeshes.dispose();
  3294. if (this.activeCamera && this.activeCamera._activeMeshes) {
  3295. this.activeCamera._activeMeshes.dispose();
  3296. }
  3297. if (this.activeCameras) {
  3298. for (let i = 0; i < this.activeCameras.length; i++) {
  3299. let activeCamera = this.activeCameras[i];
  3300. if (activeCamera && activeCamera._activeMeshes) {
  3301. activeCamera._activeMeshes.dispose();
  3302. }
  3303. }
  3304. }
  3305. }
  3306. /**
  3307. * Clear the info related to rendering groups preventing retention points during dispose.
  3308. */
  3309. public freeRenderingGroups(): void {
  3310. if (this.blockfreeActiveMeshesAndRenderingGroups) {
  3311. return;
  3312. }
  3313. if (this._renderingManager) {
  3314. this._renderingManager.freeRenderingGroups();
  3315. }
  3316. if (this.textures) {
  3317. for (let i = 0; i < this.textures.length; i++) {
  3318. let texture = this.textures[i];
  3319. if (texture && (<RenderTargetTexture>texture).renderList) {
  3320. (<RenderTargetTexture>texture).freeRenderingGroups();
  3321. }
  3322. }
  3323. }
  3324. }
  3325. /** @hidden */
  3326. public _isInIntermediateRendering(): boolean {
  3327. return this._intermediateRendering;
  3328. }
  3329. /**
  3330. * Lambda returning the list of potentially active meshes.
  3331. */
  3332. public getActiveMeshCandidates: () => ISmartArrayLike<AbstractMesh>;
  3333. /**
  3334. * Lambda returning the list of potentially active sub meshes.
  3335. */
  3336. public getActiveSubMeshCandidates: (mesh: AbstractMesh) => ISmartArrayLike<SubMesh>;
  3337. /**
  3338. * Lambda returning the list of potentially intersecting sub meshes.
  3339. */
  3340. public getIntersectingSubMeshCandidates: (mesh: AbstractMesh, localRay: Ray) => ISmartArrayLike<SubMesh>;
  3341. /**
  3342. * Lambda returning the list of potentially colliding sub meshes.
  3343. */
  3344. public getCollidingSubMeshCandidates: (mesh: AbstractMesh, collider: Collider) => ISmartArrayLike<SubMesh>;
  3345. private _activeMeshesFrozen = false;
  3346. /**
  3347. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  3348. * @returns the current scene
  3349. */
  3350. public freezeActiveMeshes(): Scene {
  3351. if (!this.activeCamera) {
  3352. return this;
  3353. }
  3354. if (!this._frustumPlanes) {
  3355. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  3356. }
  3357. this._evaluateActiveMeshes();
  3358. this._activeMeshesFrozen = true;
  3359. return this;
  3360. }
  3361. /**
  3362. * Use this function to restart evaluating active meshes on every frame
  3363. * @returns the current scene
  3364. */
  3365. public unfreezeActiveMeshes(): Scene {
  3366. this._activeMeshesFrozen = false;
  3367. return this;
  3368. }
  3369. private _evaluateActiveMeshes(): void {
  3370. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  3371. return;
  3372. }
  3373. if (!this.activeCamera) {
  3374. return;
  3375. }
  3376. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  3377. this.activeCamera._activeMeshes.reset();
  3378. this._activeMeshes.reset();
  3379. this._renderingManager.reset();
  3380. this._processedMaterials.reset();
  3381. this._activeParticleSystems.reset();
  3382. this._activeSkeletons.reset();
  3383. this._softwareSkinnedMeshes.reset();
  3384. for (let step of this._beforeEvaluateActiveMeshStage) {
  3385. step.action();
  3386. }
  3387. // Determine mesh candidates
  3388. const meshes = this.getActiveMeshCandidates();
  3389. // Check each mesh
  3390. const len = meshes.length;
  3391. for (let i = 0; i < len; i++) {
  3392. const mesh = meshes.data[i];
  3393. if (mesh.isBlocked) {
  3394. continue;
  3395. }
  3396. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  3397. if (!mesh.isReady() || !mesh.isEnabled()) {
  3398. continue;
  3399. }
  3400. mesh.computeWorldMatrix();
  3401. // Intersections
  3402. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(Constants.ACTION_OnIntersectionEnterTrigger, Constants.ACTION_OnIntersectionExitTrigger)) {
  3403. this._meshesForIntersections.pushNoDuplicate(mesh);
  3404. }
  3405. // Switch to current LOD
  3406. const meshLOD = this.customLODSelector ? this.customLODSelector(mesh, this.activeCamera) : mesh.getLOD(this.activeCamera);
  3407. if (meshLOD === undefined || meshLOD === null) {
  3408. continue;
  3409. }
  3410. mesh._preActivate();
  3411. if (mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && (mesh.alwaysSelectAsActiveMesh || mesh.isInFrustum(this._frustumPlanes))) {
  3412. this._activeMeshes.push(mesh);
  3413. this.activeCamera._activeMeshes.push(mesh);
  3414. mesh._activate(this._renderId);
  3415. if (meshLOD !== mesh) {
  3416. meshLOD._activate(this._renderId);
  3417. }
  3418. this._activeMesh(mesh, meshLOD);
  3419. }
  3420. }
  3421. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  3422. // Particle systems
  3423. if (this.particlesEnabled) {
  3424. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  3425. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  3426. var particleSystem = this.particleSystems[particleIndex];
  3427. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  3428. continue;
  3429. }
  3430. let emitter = <any>particleSystem.emitter;
  3431. if (!emitter.position || emitter.isEnabled()) {
  3432. this._activeParticleSystems.push(particleSystem);
  3433. particleSystem.animate();
  3434. this._renderingManager.dispatchParticles(particleSystem);
  3435. }
  3436. }
  3437. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  3438. }
  3439. }
  3440. private _activeMesh(sourceMesh: AbstractMesh, mesh: AbstractMesh): void {
  3441. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  3442. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  3443. mesh.skeleton.prepare();
  3444. }
  3445. if (!mesh.computeBonesUsingShaders) {
  3446. this._softwareSkinnedMeshes.pushNoDuplicate(<Mesh>mesh);
  3447. }
  3448. }
  3449. for (let step of this._activeMeshStage) {
  3450. step.action(sourceMesh, mesh);
  3451. }
  3452. if (
  3453. mesh !== undefined && mesh !== null
  3454. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0
  3455. ) {
  3456. const subMeshes = this.getActiveSubMeshCandidates(mesh);
  3457. const len = subMeshes.length;
  3458. for (let i = 0; i < len; i++) {
  3459. const subMesh = subMeshes.data[i];
  3460. this._evaluateSubMesh(subMesh, mesh);
  3461. }
  3462. }
  3463. }
  3464. /**
  3465. * Update the transform matrix to update from the current active camera
  3466. * @param force defines a boolean used to force the update even if cache is up to date
  3467. */
  3468. public updateTransformMatrix(force?: boolean): void {
  3469. if (!this.activeCamera) {
  3470. return;
  3471. }
  3472. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  3473. }
  3474. /**
  3475. * 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)
  3476. * @param alternateCamera defines the camera to use
  3477. */
  3478. public updateAlternateTransformMatrix(alternateCamera: Camera): void {
  3479. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  3480. }
  3481. /** @hidden */
  3482. public _allowPostProcessClearColor = true;
  3483. private _renderForCamera(camera: Camera, rigParent?: Camera): void {
  3484. if (camera && camera._skipRendering) {
  3485. return;
  3486. }
  3487. var engine = this._engine;
  3488. // Use _activeCamera instead of activeCamera to avoid onActiveCameraChanged
  3489. this._activeCamera = camera;
  3490. if (!this.activeCamera) {
  3491. throw new Error("Active camera not set");
  3492. }
  3493. // Viewport
  3494. engine.setViewport(this.activeCamera.viewport);
  3495. // Camera
  3496. this.resetCachedMaterial();
  3497. this._renderId++;
  3498. this.updateTransformMatrix();
  3499. if (camera._alternateCamera) {
  3500. this.updateAlternateTransformMatrix(camera._alternateCamera);
  3501. this._alternateRendering = true;
  3502. }
  3503. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  3504. // Meshes
  3505. this._evaluateActiveMeshes();
  3506. // Software skinning
  3507. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  3508. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  3509. mesh.applySkeleton(<Skeleton>mesh.skeleton);
  3510. }
  3511. // Render targets
  3512. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  3513. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  3514. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  3515. }
  3516. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  3517. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  3518. }
  3519. // Collects render targets from external components.
  3520. for (let step of this._gatherActiveCameraRenderTargetsStage) {
  3521. step.action(this._renderTargets);
  3522. }
  3523. if (this.renderTargetsEnabled) {
  3524. this._intermediateRendering = true;
  3525. if (this._renderTargets.length > 0) {
  3526. Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  3527. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  3528. let renderTarget = this._renderTargets.data[renderIndex];
  3529. if (renderTarget._shouldRender()) {
  3530. this._renderId++;
  3531. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  3532. renderTarget.render((<boolean>hasSpecialRenderTargetCamera), this.dumpNextRenderTargets);
  3533. }
  3534. }
  3535. Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  3536. this._renderId++;
  3537. }
  3538. for (let step of this._cameraDrawRenderTargetStage) {
  3539. step.action(this.activeCamera);
  3540. }
  3541. this._intermediateRendering = false;
  3542. if (this.activeCamera.outputRenderTarget) {
  3543. var internalTexture = this.activeCamera.outputRenderTarget.getInternalTexture();
  3544. if (internalTexture) {
  3545. engine.bindFramebuffer(internalTexture);
  3546. } else {
  3547. Logger.Error("Camera contains invalid customDefaultRenderTarget");
  3548. }
  3549. } else {
  3550. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  3551. }
  3552. }
  3553. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  3554. // Prepare Frame
  3555. if (this.postProcessManager) {
  3556. this.postProcessManager._prepareFrame();
  3557. }
  3558. // Before Camera Draw
  3559. for (let step of this._beforeCameraDrawStage) {
  3560. step.action(this.activeCamera);
  3561. }
  3562. // Render
  3563. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  3564. this._renderingManager.render(null, null, true, true);
  3565. this.onAfterDrawPhaseObservable.notifyObservers(this);
  3566. // After Camera Draw
  3567. for (let step of this._afterCameraDrawStage) {
  3568. step.action(this.activeCamera);
  3569. }
  3570. // Finalize frame
  3571. if (this.postProcessManager) {
  3572. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  3573. }
  3574. // Reset some special arrays
  3575. this._renderTargets.reset();
  3576. this._alternateRendering = false;
  3577. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  3578. }
  3579. private _processSubCameras(camera: Camera): void {
  3580. if (camera.cameraRigMode === Camera.RIG_MODE_NONE) {
  3581. this._renderForCamera(camera);
  3582. return;
  3583. }
  3584. // rig cameras
  3585. for (var index = 0; index < camera._rigCameras.length; index++) {
  3586. this._renderForCamera(camera._rigCameras[index], camera);
  3587. }
  3588. // Use _activeCamera instead of activeCamera to avoid onActiveCameraChanged
  3589. this._activeCamera = camera;
  3590. this.setTransformMatrix(this._activeCamera.getViewMatrix(), this._activeCamera.getProjectionMatrix());
  3591. }
  3592. private _checkIntersections(): void {
  3593. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  3594. var sourceMesh = this._meshesForIntersections.data[index];
  3595. if (!sourceMesh.actionManager) {
  3596. continue;
  3597. }
  3598. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  3599. var action = sourceMesh.actionManager.actions[actionIndex];
  3600. if (action.trigger === Constants.ACTION_OnIntersectionEnterTrigger || action.trigger === Constants.ACTION_OnIntersectionExitTrigger) {
  3601. var parameters = action.getTriggerParameter();
  3602. var otherMesh = parameters instanceof AbstractMesh ? parameters : parameters.mesh;
  3603. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  3604. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  3605. if (areIntersecting && currentIntersectionInProgress === -1) {
  3606. if (action.trigger === Constants.ACTION_OnIntersectionEnterTrigger) {
  3607. action._executeCurrent(ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  3608. sourceMesh._intersectionsInProgress.push(otherMesh);
  3609. } else if (action.trigger === Constants.ACTION_OnIntersectionExitTrigger) {
  3610. sourceMesh._intersectionsInProgress.push(otherMesh);
  3611. }
  3612. } else if (!areIntersecting && currentIntersectionInProgress > -1) {
  3613. //They intersected, and now they don't.
  3614. //is this trigger an exit trigger? execute an event.
  3615. if (action.trigger === Constants.ACTION_OnIntersectionExitTrigger) {
  3616. action._executeCurrent(ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  3617. }
  3618. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  3619. if (!sourceMesh.actionManager.hasSpecificTrigger(Constants.ACTION_OnIntersectionExitTrigger, (parameter) => {
  3620. var parameterMesh = parameter instanceof AbstractMesh ? parameter : parameter.mesh;
  3621. return otherMesh === parameterMesh;
  3622. }) || action.trigger === Constants.ACTION_OnIntersectionExitTrigger) {
  3623. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  3624. }
  3625. }
  3626. }
  3627. }
  3628. }
  3629. }
  3630. /** @hidden */
  3631. public _advancePhysicsEngineStep(step: number) {
  3632. // Do nothing. Code will be replaced if physics engine component is referenced
  3633. }
  3634. /**
  3635. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  3636. */
  3637. public getDeterministicFrameTime: () => number = () => {
  3638. return 1000.0 / 60.0; // frame time in ms
  3639. }
  3640. /** @hidden */
  3641. public _animate(): void {
  3642. // Nothing to do as long as Animatable have not been imported.
  3643. }
  3644. /**
  3645. * Render the scene
  3646. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  3647. */
  3648. public render(updateCameras = true): void {
  3649. if (this.isDisposed) {
  3650. return;
  3651. }
  3652. this._frameId++;
  3653. // Register components that have been associated lately to the scene.
  3654. this._registerTransientComponents();
  3655. this._activeParticles.fetchNewFrame();
  3656. this._totalVertices.fetchNewFrame();
  3657. this._activeIndices.fetchNewFrame();
  3658. this._activeBones.fetchNewFrame();
  3659. this._meshesForIntersections.reset();
  3660. this.resetCachedMaterial();
  3661. this.onBeforeAnimationsObservable.notifyObservers(this);
  3662. // Actions
  3663. if (this.actionManager) {
  3664. this.actionManager.processTrigger(Constants.ACTION_OnEveryFrameTrigger);
  3665. }
  3666. if (this._engine.isDeterministicLockStep()) {
  3667. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  3668. var defaultFPS = (60.0 / 1000.0);
  3669. let defaultFrameTime = this.getDeterministicFrameTime();
  3670. let stepsTaken = 0;
  3671. var maxSubSteps = this._engine.getLockstepMaxSteps();
  3672. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  3673. internalSteps = Math.min(internalSteps, maxSubSteps);
  3674. do {
  3675. this.onBeforeStepObservable.notifyObservers(this);
  3676. // Animations
  3677. this._animationRatio = defaultFrameTime * defaultFPS;
  3678. this._animate();
  3679. this.onAfterAnimationsObservable.notifyObservers(this);
  3680. // Physics
  3681. this._advancePhysicsEngineStep(defaultFrameTime);
  3682. this.onAfterStepObservable.notifyObservers(this);
  3683. this._currentStepId++;
  3684. stepsTaken++;
  3685. deltaTime -= defaultFrameTime;
  3686. } while (deltaTime > 0 && stepsTaken < internalSteps);
  3687. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  3688. }
  3689. else {
  3690. // Animations
  3691. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  3692. this._animationRatio = deltaTime * (60.0 / 1000.0);
  3693. this._animate();
  3694. this.onAfterAnimationsObservable.notifyObservers(this);
  3695. // Physics
  3696. this._advancePhysicsEngineStep(deltaTime);
  3697. }
  3698. // Before camera update steps
  3699. for (let step of this._beforeCameraUpdateStage) {
  3700. step.action();
  3701. }
  3702. // Update Cameras
  3703. if (updateCameras) {
  3704. if (this.activeCameras.length > 0) {
  3705. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  3706. let camera = this.activeCameras[cameraIndex];
  3707. camera.update();
  3708. if (camera.cameraRigMode !== Camera.RIG_MODE_NONE) {
  3709. // rig cameras
  3710. for (var index = 0; index < camera._rigCameras.length; index++) {
  3711. camera._rigCameras[index].update();
  3712. }
  3713. }
  3714. }
  3715. } else if (this.activeCamera) {
  3716. this.activeCamera.update();
  3717. if (this.activeCamera.cameraRigMode !== Camera.RIG_MODE_NONE) {
  3718. // rig cameras
  3719. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  3720. this.activeCamera._rigCameras[index].update();
  3721. }
  3722. }
  3723. }
  3724. }
  3725. // Before render
  3726. this.onBeforeRenderObservable.notifyObservers(this);
  3727. // Customs render targets
  3728. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  3729. var engine = this.getEngine();
  3730. var currentActiveCamera = this.activeCamera;
  3731. if (this.renderTargetsEnabled) {
  3732. Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  3733. this._intermediateRendering = true;
  3734. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  3735. var renderTarget = this.customRenderTargets[customIndex];
  3736. if (renderTarget._shouldRender()) {
  3737. this._renderId++;
  3738. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  3739. if (!this.activeCamera) {
  3740. throw new Error("Active camera not set");
  3741. }
  3742. // Viewport
  3743. engine.setViewport(this.activeCamera.viewport);
  3744. // Camera
  3745. this.updateTransformMatrix();
  3746. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  3747. }
  3748. }
  3749. Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  3750. this._intermediateRendering = false;
  3751. this._renderId++;
  3752. }
  3753. // Restore back buffer
  3754. if (this.customRenderTargets.length > 0) {
  3755. engine.restoreDefaultFramebuffer();
  3756. }
  3757. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  3758. this.activeCamera = currentActiveCamera;
  3759. for (let step of this._beforeClearStage) {
  3760. step.action();
  3761. }
  3762. // Clear
  3763. if (this.autoClearDepthAndStencil || this.autoClear) {
  3764. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  3765. }
  3766. // Collects render targets from external components.
  3767. for (let step of this._gatherRenderTargetsStage) {
  3768. step.action(this._renderTargets);
  3769. }
  3770. // Multi-cameras?
  3771. if (this.activeCameras.length > 0) {
  3772. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  3773. if (cameraIndex > 0) {
  3774. this._engine.clear(null, false, true, true);
  3775. }
  3776. this._processSubCameras(this.activeCameras[cameraIndex]);
  3777. }
  3778. } else {
  3779. if (!this.activeCamera) {
  3780. throw new Error("No camera defined");
  3781. }
  3782. this._processSubCameras(this.activeCamera);
  3783. }
  3784. // Intersection checks
  3785. this._checkIntersections();
  3786. // Executes the after render stage actions.
  3787. for (let step of this._afterRenderStage) {
  3788. step.action();
  3789. }
  3790. // After render
  3791. if (this.afterRender) {
  3792. this.afterRender();
  3793. }
  3794. this.onAfterRenderObservable.notifyObservers(this);
  3795. // Cleaning
  3796. if (this._toBeDisposed.length) {
  3797. for (var index = 0; index < this._toBeDisposed.length; index++) {
  3798. var data = this._toBeDisposed[index];
  3799. if (data) {
  3800. data.dispose();
  3801. }
  3802. }
  3803. this._toBeDisposed = [];
  3804. }
  3805. if (this.dumpNextRenderTargets) {
  3806. this.dumpNextRenderTargets = false;
  3807. }
  3808. this._activeBones.addCount(0, true);
  3809. this._activeIndices.addCount(0, true);
  3810. this._activeParticles.addCount(0, true);
  3811. }
  3812. /**
  3813. * Freeze all materials
  3814. * A frozen material will not be updatable but should be faster to render
  3815. */
  3816. public freezeMaterials(): void {
  3817. for (var i = 0; i < this.materials.length; i++) {
  3818. this.materials[i].freeze();
  3819. }
  3820. }
  3821. /**
  3822. * Unfreeze all materials
  3823. * A frozen material will not be updatable but should be faster to render
  3824. */
  3825. public unfreezeMaterials(): void {
  3826. for (var i = 0; i < this.materials.length; i++) {
  3827. this.materials[i].unfreeze();
  3828. }
  3829. }
  3830. /**
  3831. * Releases all held ressources
  3832. */
  3833. public dispose(): void {
  3834. this.beforeRender = null;
  3835. this.afterRender = null;
  3836. this.skeletons = [];
  3837. this.morphTargetManagers = [];
  3838. this._transientComponents = [];
  3839. this._isReadyForMeshStage.clear();
  3840. this._beforeEvaluateActiveMeshStage.clear();
  3841. this._evaluateSubMeshStage.clear();
  3842. this._activeMeshStage.clear();
  3843. this._cameraDrawRenderTargetStage.clear();
  3844. this._beforeCameraDrawStage.clear();
  3845. this._beforeRenderTargetDrawStage.clear();
  3846. this._beforeRenderingGroupDrawStage.clear();
  3847. this._beforeRenderingMeshStage.clear();
  3848. this._afterRenderingMeshStage.clear();
  3849. this._afterRenderingGroupDrawStage.clear();
  3850. this._afterCameraDrawStage.clear();
  3851. this._afterRenderTargetDrawStage.clear();
  3852. this._afterRenderStage.clear();
  3853. this._beforeCameraUpdateStage.clear();
  3854. this._beforeClearStage.clear();
  3855. this._gatherRenderTargetsStage.clear();
  3856. this._gatherActiveCameraRenderTargetsStage.clear();
  3857. this._pointerMoveStage.clear();
  3858. this._pointerDownStage.clear();
  3859. this._pointerUpStage.clear();
  3860. for (let component of this._components) {
  3861. component.dispose();
  3862. }
  3863. this.importedMeshesFiles = new Array<string>();
  3864. this.stopAllAnimations();
  3865. this.resetCachedMaterial();
  3866. // Smart arrays
  3867. if (this.activeCamera) {
  3868. this.activeCamera._activeMeshes.dispose();
  3869. this.activeCamera = null;
  3870. }
  3871. this._activeMeshes.dispose();
  3872. this._renderingManager.dispose();
  3873. this._processedMaterials.dispose();
  3874. this._activeParticleSystems.dispose();
  3875. this._activeSkeletons.dispose();
  3876. this._softwareSkinnedMeshes.dispose();
  3877. this._renderTargets.dispose();
  3878. this._registeredForLateAnimationBindings.dispose();
  3879. this._meshesForIntersections.dispose();
  3880. this._toBeDisposed = [];
  3881. // Abort active requests
  3882. for (let request of this._activeRequests) {
  3883. request.abort();
  3884. }
  3885. // Events
  3886. this.onDisposeObservable.notifyObservers(this);
  3887. this.onDisposeObservable.clear();
  3888. this.onBeforeRenderObservable.clear();
  3889. this.onAfterRenderObservable.clear();
  3890. this.onBeforeRenderTargetsRenderObservable.clear();
  3891. this.onAfterRenderTargetsRenderObservable.clear();
  3892. this.onAfterStepObservable.clear();
  3893. this.onBeforeStepObservable.clear();
  3894. this.onBeforeActiveMeshesEvaluationObservable.clear();
  3895. this.onAfterActiveMeshesEvaluationObservable.clear();
  3896. this.onBeforeParticlesRenderingObservable.clear();
  3897. this.onAfterParticlesRenderingObservable.clear();
  3898. this.onBeforeDrawPhaseObservable.clear();
  3899. this.onAfterDrawPhaseObservable.clear();
  3900. this.onBeforeAnimationsObservable.clear();
  3901. this.onAfterAnimationsObservable.clear();
  3902. this.onDataLoadedObservable.clear();
  3903. this.onBeforeRenderingGroupObservable.clear();
  3904. this.onAfterRenderingGroupObservable.clear();
  3905. this.onMeshImportedObservable.clear();
  3906. this.onBeforeCameraRenderObservable.clear();
  3907. this.onAfterCameraRenderObservable.clear();
  3908. this.onReadyObservable.clear();
  3909. this.onNewCameraAddedObservable.clear();
  3910. this.onCameraRemovedObservable.clear();
  3911. this.onNewLightAddedObservable.clear();
  3912. this.onLightRemovedObservable.clear();
  3913. this.onNewGeometryAddedObservable.clear();
  3914. this.onGeometryRemovedObservable.clear();
  3915. this.onNewTransformNodeAddedObservable.clear();
  3916. this.onTransformNodeRemovedObservable.clear();
  3917. this.onNewMeshAddedObservable.clear();
  3918. this.onMeshRemovedObservable.clear();
  3919. this.onNewSkeletonAddedObservable.clear();
  3920. this.onSkeletonRemovedObservable.clear();
  3921. this.onNewMaterialAddedObservable.clear();
  3922. this.onMaterialRemovedObservable.clear();
  3923. this.onNewTextureAddedObservable.clear();
  3924. this.onTextureRemovedObservable.clear();
  3925. this.onPrePointerObservable.clear();
  3926. this.onPointerObservable.clear();
  3927. this.onPreKeyboardObservable.clear();
  3928. this.onKeyboardObservable.clear();
  3929. this.onActiveCameraChanged.clear();
  3930. this.detachControl();
  3931. // Detach cameras
  3932. var canvas = this._engine.getRenderingCanvas();
  3933. if (canvas) {
  3934. var index;
  3935. for (index = 0; index < this.cameras.length; index++) {
  3936. this.cameras[index].detachControl(canvas);
  3937. }
  3938. }
  3939. // Release animation groups
  3940. while (this.animationGroups.length) {
  3941. this.animationGroups[0].dispose();
  3942. }
  3943. // Release lights
  3944. while (this.lights.length) {
  3945. this.lights[0].dispose();
  3946. }
  3947. // Release meshes
  3948. while (this.meshes.length) {
  3949. this.meshes[0].dispose(true);
  3950. }
  3951. while (this.transformNodes.length) {
  3952. this.transformNodes[0].dispose(true);
  3953. }
  3954. // Release cameras
  3955. while (this.cameras.length) {
  3956. this.cameras[0].dispose();
  3957. }
  3958. // Release materials
  3959. if (this.defaultMaterial) {
  3960. this.defaultMaterial.dispose();
  3961. }
  3962. while (this.multiMaterials.length) {
  3963. this.multiMaterials[0].dispose();
  3964. }
  3965. while (this.materials.length) {
  3966. this.materials[0].dispose();
  3967. }
  3968. // Release particles
  3969. while (this.particleSystems.length) {
  3970. this.particleSystems[0].dispose();
  3971. }
  3972. // Release postProcesses
  3973. while (this.postProcesses.length) {
  3974. this.postProcesses[0].dispose();
  3975. }
  3976. // Release textures
  3977. while (this.textures.length) {
  3978. this.textures[0].dispose();
  3979. }
  3980. // Release UBO
  3981. this._sceneUbo.dispose();
  3982. if (this._alternateSceneUbo) {
  3983. this._alternateSceneUbo.dispose();
  3984. }
  3985. // Post-processes
  3986. this.postProcessManager.dispose();
  3987. // Remove from engine
  3988. index = this._engine.scenes.indexOf(this);
  3989. if (index > -1) {
  3990. this._engine.scenes.splice(index, 1);
  3991. }
  3992. this._engine.wipeCaches(true);
  3993. this._isDisposed = true;
  3994. }
  3995. /**
  3996. * Gets if the scene is already disposed
  3997. */
  3998. public get isDisposed(): boolean {
  3999. return this._isDisposed;
  4000. }
  4001. /**
  4002. * Call this function to reduce memory footprint of the scene.
  4003. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  4004. */
  4005. public clearCachedVertexData(): void {
  4006. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  4007. var mesh = this.meshes[meshIndex];
  4008. var geometry = (<Mesh>mesh).geometry;
  4009. if (geometry) {
  4010. geometry._indices = [];
  4011. for (var vbName in geometry._vertexBuffers) {
  4012. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  4013. continue;
  4014. }
  4015. geometry._vertexBuffers[vbName]._buffer._data = null;
  4016. }
  4017. }
  4018. }
  4019. }
  4020. /**
  4021. * This function will remove the local cached buffer data from texture.
  4022. * It will save memory but will prevent the texture from being rebuilt
  4023. */
  4024. public cleanCachedTextureBuffer(): void {
  4025. for (var baseTexture of this.textures) {
  4026. let buffer = (<Texture>baseTexture)._buffer;
  4027. if (buffer) {
  4028. (<Texture>baseTexture)._buffer = null;
  4029. }
  4030. }
  4031. }
  4032. /**
  4033. * Get the world extend vectors with an optional filter
  4034. *
  4035. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  4036. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  4037. */
  4038. public getWorldExtends(filterPredicate?: (mesh: AbstractMesh) => boolean): { min: Vector3; max: Vector3 } {
  4039. var min = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4040. var max = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4041. filterPredicate = filterPredicate || (() => true);
  4042. this.meshes.filter(filterPredicate).forEach((mesh) => {
  4043. mesh.computeWorldMatrix(true);
  4044. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  4045. return;
  4046. }
  4047. let boundingInfo = mesh.getBoundingInfo();
  4048. var minBox = boundingInfo.boundingBox.minimumWorld;
  4049. var maxBox = boundingInfo.boundingBox.maximumWorld;
  4050. Tools.CheckExtends(minBox, min, max);
  4051. Tools.CheckExtends(maxBox, min, max);
  4052. });
  4053. return {
  4054. min: min,
  4055. max: max
  4056. };
  4057. }
  4058. // Picking
  4059. /**
  4060. * Creates a ray that can be used to pick in the scene
  4061. * @param x defines the x coordinate of the origin (on-screen)
  4062. * @param y defines the y coordinate of the origin (on-screen)
  4063. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  4064. * @param camera defines the camera to use for the picking
  4065. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  4066. * @returns a Ray
  4067. */
  4068. public createPickingRay(x: number, y: number, world: Matrix, camera: Nullable<Camera>, cameraViewSpace = false): Ray {
  4069. throw _DevTools.WarnImport("Ray");
  4070. }
  4071. /**
  4072. * Creates a ray that can be used to pick in the scene
  4073. * @param x defines the x coordinate of the origin (on-screen)
  4074. * @param y defines the y coordinate of the origin (on-screen)
  4075. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  4076. * @param result defines the ray where to store the picking ray
  4077. * @param camera defines the camera to use for the picking
  4078. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  4079. * @returns the current scene
  4080. */
  4081. public createPickingRayToRef(x: number, y: number, world: Matrix, result: Ray, camera: Nullable<Camera>, cameraViewSpace = false): Scene {
  4082. throw _DevTools.WarnImport("Ray");
  4083. }
  4084. /**
  4085. * Creates a ray that can be used to pick in the scene
  4086. * @param x defines the x coordinate of the origin (on-screen)
  4087. * @param y defines the y coordinate of the origin (on-screen)
  4088. * @param camera defines the camera to use for the picking
  4089. * @returns a Ray
  4090. */
  4091. public createPickingRayInCameraSpace(x: number, y: number, camera?: Camera): Ray {
  4092. throw _DevTools.WarnImport("Ray");
  4093. }
  4094. /**
  4095. * Creates a ray that can be used to pick in the scene
  4096. * @param x defines the x coordinate of the origin (on-screen)
  4097. * @param y defines the y coordinate of the origin (on-screen)
  4098. * @param result defines the ray where to store the picking ray
  4099. * @param camera defines the camera to use for the picking
  4100. * @returns the current scene
  4101. */
  4102. public createPickingRayInCameraSpaceToRef(x: number, y: number, result: Ray, camera?: Camera): Scene {
  4103. throw _DevTools.WarnImport("Ray");
  4104. }
  4105. /** Launch a ray to try to pick a mesh in the scene
  4106. * @param x position on screen
  4107. * @param y position on screen
  4108. * @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
  4109. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  4110. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  4111. * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected
  4112. * @returns a PickingInfo
  4113. */
  4114. public pick(x: number, y: number, predicate?: (mesh: AbstractMesh) => boolean,
  4115. fastCheck?: boolean, camera?: Nullable<Camera>,
  4116. trianglePredicate?: (p0: Vector3, p1: Vector3, p2: Vector3) => boolean
  4117. ): Nullable<PickingInfo> {
  4118. // Dummy info if picking as not been imported
  4119. const pi = new PickingInfo();
  4120. pi._pickingUnavailable = true;
  4121. return pi;
  4122. }
  4123. /** Use the given ray to pick a mesh in the scene
  4124. * @param ray The ray to use to pick meshes
  4125. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must have isPickable set to true
  4126. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  4127. * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected
  4128. * @returns a PickingInfo
  4129. */
  4130. public pickWithRay(ray: Ray, predicate?: (mesh: AbstractMesh) => boolean, fastCheck?: boolean,
  4131. trianglePredicate?: TrianglePickingPredicate): Nullable<PickingInfo> {
  4132. throw _DevTools.WarnImport("Ray");
  4133. }
  4134. /**
  4135. * Launch a ray to try to pick a mesh in the scene
  4136. * @param x X position on screen
  4137. * @param y Y position on screen
  4138. * @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
  4139. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  4140. * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected
  4141. * @returns an array of PickingInfo
  4142. */
  4143. public multiPick(x: number, y: number, predicate?: (mesh: AbstractMesh) => boolean, camera?: Camera,
  4144. trianglePredicate?: TrianglePickingPredicate): Nullable<PickingInfo[]> {
  4145. throw _DevTools.WarnImport("Ray");
  4146. }
  4147. /**
  4148. * Launch a ray to try to pick a mesh in the scene
  4149. * @param ray Ray to use
  4150. * @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
  4151. * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected
  4152. * @returns an array of PickingInfo
  4153. */
  4154. public multiPickWithRay(ray: Ray, predicate: (mesh: AbstractMesh) => boolean, trianglePredicate?: TrianglePickingPredicate): Nullable<PickingInfo[]> {
  4155. throw _DevTools.WarnImport("Ray");
  4156. }
  4157. /**
  4158. * Force the value of meshUnderPointer
  4159. * @param mesh defines the mesh to use
  4160. */
  4161. public setPointerOverMesh(mesh: Nullable<AbstractMesh>): void {
  4162. if (this._pointerOverMesh === mesh) {
  4163. return;
  4164. }
  4165. let actionManager: Nullable<AbstractActionManager>;
  4166. if (this._pointerOverMesh) {
  4167. actionManager = this._pointerOverMesh._getActionManagerForTrigger(Constants.ACTION_OnPointerOutTrigger);
  4168. if (actionManager) {
  4169. actionManager.processTrigger(Constants.ACTION_OnPointerOutTrigger, ActionEvent.CreateNew(this._pointerOverMesh));
  4170. }
  4171. }
  4172. this._pointerOverMesh = mesh;
  4173. if (this._pointerOverMesh) {
  4174. actionManager = this._pointerOverMesh._getActionManagerForTrigger(Constants.ACTION_OnPointerOverTrigger);
  4175. if (actionManager) {
  4176. actionManager.processTrigger(Constants.ACTION_OnPointerOverTrigger, ActionEvent.CreateNew(this._pointerOverMesh));
  4177. }
  4178. }
  4179. }
  4180. /**
  4181. * Gets the mesh under the pointer
  4182. * @returns a Mesh or null if no mesh is under the pointer
  4183. */
  4184. public getPointerOverMesh(): Nullable<AbstractMesh> {
  4185. return this._pointerOverMesh;
  4186. }
  4187. // Misc.
  4188. /** @hidden */
  4189. public _rebuildGeometries(): void {
  4190. for (var geometry of this.geometries) {
  4191. geometry._rebuild();
  4192. }
  4193. for (var mesh of this.meshes) {
  4194. mesh._rebuild();
  4195. }
  4196. if (this.postProcessManager) {
  4197. this.postProcessManager._rebuild();
  4198. }
  4199. for (let component of this._components) {
  4200. component.rebuild();
  4201. }
  4202. for (var system of this.particleSystems) {
  4203. system.rebuild();
  4204. }
  4205. }
  4206. /** @hidden */
  4207. public _rebuildTextures(): void {
  4208. for (var texture of this.textures) {
  4209. texture._rebuild();
  4210. }
  4211. this.markAllMaterialsAsDirty(Constants.MATERIAL_TextureDirtyFlag);
  4212. }
  4213. // Tags
  4214. private _getByTags(list: any[], tagsQuery: string, forEach?: (item: any) => void): any[] {
  4215. if (tagsQuery === undefined) {
  4216. // returns the complete list (could be done with Tags.MatchesQuery but no need to have a for-loop here)
  4217. return list;
  4218. }
  4219. var listByTags = [];
  4220. forEach = forEach || ((item: any) => { return; });
  4221. for (var i in list) {
  4222. var item = list[i];
  4223. if (Tags && Tags.MatchesQuery(item, tagsQuery)) {
  4224. listByTags.push(item);
  4225. forEach(item);
  4226. }
  4227. }
  4228. return listByTags;
  4229. }
  4230. /**
  4231. * Get a list of meshes by tags
  4232. * @param tagsQuery defines the tags query to use
  4233. * @param forEach defines a predicate used to filter results
  4234. * @returns an array of Mesh
  4235. */
  4236. public getMeshesByTags(tagsQuery: string, forEach?: (mesh: AbstractMesh) => void): Mesh[] {
  4237. return this._getByTags(this.meshes, tagsQuery, forEach);
  4238. }
  4239. /**
  4240. * Get a list of cameras by tags
  4241. * @param tagsQuery defines the tags query to use
  4242. * @param forEach defines a predicate used to filter results
  4243. * @returns an array of Camera
  4244. */
  4245. public getCamerasByTags(tagsQuery: string, forEach?: (camera: Camera) => void): Camera[] {
  4246. return this._getByTags(this.cameras, tagsQuery, forEach);
  4247. }
  4248. /**
  4249. * Get a list of lights by tags
  4250. * @param tagsQuery defines the tags query to use
  4251. * @param forEach defines a predicate used to filter results
  4252. * @returns an array of Light
  4253. */
  4254. public getLightsByTags(tagsQuery: string, forEach?: (light: Light) => void): Light[] {
  4255. return this._getByTags(this.lights, tagsQuery, forEach);
  4256. }
  4257. /**
  4258. * Get a list of materials by tags
  4259. * @param tagsQuery defines the tags query to use
  4260. * @param forEach defines a predicate used to filter results
  4261. * @returns an array of Material
  4262. */
  4263. public getMaterialByTags(tagsQuery: string, forEach?: (material: Material) => void): Material[] {
  4264. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  4265. }
  4266. /**
  4267. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  4268. * This allowed control for front to back rendering or reversly depending of the special needs.
  4269. *
  4270. * @param renderingGroupId The rendering group id corresponding to its index
  4271. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  4272. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  4273. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  4274. */
  4275. public setRenderingOrder(renderingGroupId: number,
  4276. opaqueSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null,
  4277. alphaTestSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null,
  4278. transparentSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null): void {
  4279. this._renderingManager.setRenderingOrder(renderingGroupId,
  4280. opaqueSortCompareFn,
  4281. alphaTestSortCompareFn,
  4282. transparentSortCompareFn);
  4283. }
  4284. /**
  4285. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  4286. *
  4287. * @param renderingGroupId The rendering group id corresponding to its index
  4288. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  4289. * @param depth Automatically clears depth between groups if true and autoClear is true.
  4290. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  4291. */
  4292. public setRenderingAutoClearDepthStencil(renderingGroupId: number, autoClearDepthStencil: boolean,
  4293. depth = true,
  4294. stencil = true): void {
  4295. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  4296. }
  4297. /**
  4298. * Gets the current auto clear configuration for one rendering group of the rendering
  4299. * manager.
  4300. * @param index the rendering group index to get the information for
  4301. * @returns The auto clear setup for the requested rendering group
  4302. */
  4303. public getAutoClearDepthStencilSetup(index: number): IRenderingManagerAutoClearSetup {
  4304. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  4305. }
  4306. private _blockMaterialDirtyMechanism = false;
  4307. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  4308. public get blockMaterialDirtyMechanism(): boolean {
  4309. return this._blockMaterialDirtyMechanism;
  4310. }
  4311. public set blockMaterialDirtyMechanism(value: boolean) {
  4312. if (this._blockMaterialDirtyMechanism === value) {
  4313. return;
  4314. }
  4315. this._blockMaterialDirtyMechanism = value;
  4316. if (!value) { // Do a complete update
  4317. this.markAllMaterialsAsDirty(Constants.MATERIAL_AllDirtyFlag);
  4318. }
  4319. }
  4320. /**
  4321. * Will flag all materials as dirty to trigger new shader compilation
  4322. * @param flag defines the flag used to specify which material part must be marked as dirty
  4323. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  4324. */
  4325. public markAllMaterialsAsDirty(flag: number, predicate?: (mat: Material) => boolean): void {
  4326. if (this._blockMaterialDirtyMechanism) {
  4327. return;
  4328. }
  4329. for (var material of this.materials) {
  4330. if (predicate && !predicate(material)) {
  4331. continue;
  4332. }
  4333. material.markAsDirty(flag);
  4334. }
  4335. }
  4336. /** @hidden */
  4337. public _loadFile(url: string, onSuccess: (data: string | ArrayBuffer, responseURL?: string) => void, onProgress?: (data: any) => void, useOfflineSupport?: boolean, useArrayBuffer?: boolean, onError?: (request?: WebRequest, exception?: any) => void): IFileRequest {
  4338. let request = Tools.LoadFile(url, onSuccess, onProgress, useOfflineSupport ? this.offlineProvider : undefined, useArrayBuffer, onError);
  4339. this._activeRequests.push(request);
  4340. request.onCompleteObservable.add((request) => {
  4341. this._activeRequests.splice(this._activeRequests.indexOf(request), 1);
  4342. });
  4343. return request;
  4344. }
  4345. /** @hidden */
  4346. public _loadFileAsync(url: string, useOfflineSupport?: boolean, useArrayBuffer?: boolean): Promise<string | ArrayBuffer> {
  4347. return new Promise((resolve, reject) => {
  4348. this._loadFile(url, (data) => {
  4349. resolve(data);
  4350. }, undefined, useOfflineSupport, useArrayBuffer, (request, exception) => {
  4351. reject(exception);
  4352. });
  4353. });
  4354. }
  4355. }