scene.ts 158 KB

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