scene.ts 160 KB

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