Game.ManagedBatchSystem
Assembly: Assembly-CSharp
Namespace: Game.Rendering
Type: public class
Base: GameSystemBase
Summary:
ManagedBatchSystem is the central managed-side renderer helper that builds and maintains CustomBatch instances used by the game's rendering pipeline. It:
- Creates and caches Materials for surfaces and source materials.
- Tracks grouped batches and shared meshes (to allow mesh sharing/replacement).
- Integrates with the Virtual Texturing (VT) subsystem via a VTTextureRequester, collects VT requests submitted from jobs, and pushes them to the TextureStreamingSystem.
- Works with PrefabSystem, RenderingSystem, BatchMeshSystem, BatchManagerSystem and TextureStreamingSystem to initialize batch data, set material property blocks, set shader keywords and VT bindings, and maintain render flags (cast/receive shadows, motion vectors, enabled state).
This system is intended for modders to understand how materials/batches are generated and how to interact with VT & batch lifecycle (reset/reload/complete requests).
Fields
-
private PrefabSystem m_PrefabSystem
Reference to the PrefabSystem (used to get RenderPrefab / surface assets). -
private RenderingSystem m_RenderingSystem
Reference to the engine's RenderingSystem (used to check whether a shader is enabled). -
private BatchMeshSystem m_BatchMeshSystem
Used to get default meshes and configure mesh-specific parameters. -
private BatchManagerSystem m_BatchManagerSystem
Used to access and modify native batch groups, property data and to mark virtual texturing updates. -
private TextureStreamingSystem m_TextureStreamingSystem
Texture streaming / virtual texturing management & binding helper. -
private Dictionary<MaterialKey, Material> m_Materials
Cache of generated Materials keyed by MaterialKey (surface/material characteristics + keywords/textures). -
private Dictionary<GroupKey, Entity> m_Groups
Cache that ties GroupKey (mesh+layer+partition+batches) to the entity used as shared mesh. -
private Dictionary<MeshKey, Entity> m_Meshes
Map of MeshKey -> Entity for deduplicating shared meshes. -
private List<KeywordData> m_CachedKeywords
Temporary buffer used while building materials to track enabled/disabled shader keywords. -
private List<TextureData> m_CachedTextures
Temporary buffer used while building materials to track swapped textures. -
private MaterialKey m_CachedMaterialKey
A reusable MaterialKey instance for transient allocation reduction. -
private GroupKey m_CachedGroupKey
A reusable GroupKey instance for transient allocation reduction. -
private VTTextureRequester m_VTTextureRequester
Helper that accumulates VT texture requests from batches and exposes NativeList max-pixels and registrations. -
private JobHandle m_VTRequestDependencies
JobHandle representing writer dependencies for VT requests (jobs that filled VT request lists). -
private EntityQuery m_MeshSettingsQuery
Query used to read mesh settings (e.g., default base mesh / missing object mesh). -
private bool m_VTRequestsUpdated
Flag toggled when AddVTRequestWriter is called; used by CompleteVTRequests to decide whether to update VT state. -
private int m_TunnelLayer, m_MovingLayer, m_PipelineLayer, m_SubPipelineLayer, m_WaterwayLayer, m_OutlineLayer, m_MarkerLayer
Cached Unity layer indices used to assign batch layers. -
private int m_DecalLayerMask, m_AnimationTexture, m_UseStack1, m_ImpostorSize, m_ImpostorOffset, m_WorldspaceAlbedo, m_MaskMap
Shader property IDs cached via Shader.PropertyToID used when building materials and setting properties.
(There are additional small structs and nested types such as MaterialKey, GroupKey, MeshKey, KeywordData, TextureData used to represent keys & cached data.)
Properties
-
public int materialCount => m_Materials.Count
Number of cached generated materials. -
public int groupCount { get; private set; }
Count of groups currently tracked by the ManagedBatchSystem. -
public int batchCount { get; private set; }
Count of batches currently accounted for. -
public IReadOnlyDictionary<MaterialKey, Material> materials => m_Materials
Read-only access to the material cache (useful for debugging/inspection). -
public VTTextureRequester VTTextureRequester => m_VTTextureRequester
Exposes the VTTextureRequester so you can inspect registered textures and the NativeLists of texture max-pixels.
Constructors
public ManagedBatchSystem()
Default constructor. Actual initialization of system references, caches, property IDs and VT requester is done in OnCreate().
Methods
-
protected override void OnCreate()
: System.Void
Initializes references to PrefabSystem, RenderingSystem, BatchMeshSystem, BatchManagerSystem and TextureStreamingSystem. Allocates the material/group/mesh caches, creates VTTextureRequester and resolves shader property IDs and Unity layer indices. Called by the ECS world when the system is created. -
protected override void OnDestroy()
: System.Void
Cleans up cached materials (destroying created Unity Material instances), completes any outstanding VT request job handles, disposes VTTextureRequester, and performs base shutdown. Important to avoid leaking Unity objects. -
public void RemoveMesh(Entity oldMesh, Entity newMesh = default(Entity))
: System.Void
Called when a mesh entity changes. Removes mappings that referenced oldMesh, and if a suitable replacement newMesh is provided and matches an existing MeshKey it updates internal tables and asks BatchMeshSystem to replace the mesh. -
public void ResetSharedMeshes()
: System.Void
Iterates native batch groups and rebuilds the m_Meshes and m_Groups caches from scratch by reading group data and creating GroupKey entries as needed. Useful if mesh-sharing state must be recomputed. -
protected override void OnUpdate()
: System.Void
Main update that processes updated managed batch groups from the native BatchManager. For each updated group it: - Ensures a shared mesh mapping exists.
- Builds GroupKey and per-batch MaterialKey(s).
- Calls CreateBatch for newly created managed batches, sets defaults and batch properties, registers meshes with BatchMeshSystem and managedBatches, and tracks group/batch counts.
-
Merges or adds groups to internal dictionaries.
-
public void EnabledShadersUpdated()
: System.Void
Re-iterates native groups and batches and updates BatchRenderFlags.IsEnabled based on whether the loaded materials' shaders are enabled via RenderingSystem.IsShaderEnabled. Use when shader feature toggles change. -
public JobHandle GetVTRequestMaxPixels(out NativeList<float> maxPixels0, out NativeList<float> maxPixels1)
: JobHandle
Returns native lists used by VTTextureRequester that contain max-pixel demands for VT stacks (two indices) and returns the JobHandle dependency representing the producer job. Callers should add job dependencies appropriately. -
public void AddVTRequestWriter(JobHandle dependencies)
: System.Void
Called by a writer to provide a JobHandle dependency that produced VT requests. The system stores this JobHandle and marks VT requests as updated. The stored handle is completed later when Consume/CompleteVTRequests is called. -
public void ResetVT(int desiredMipBias, UnityEngine.Rendering.VirtualTexturing.FilterMode filterMode)
: System.Void
If the TextureStreamingSystem decides VT must be reset, this completes pending VT jobs, clears the VTTextureRequester, reinitializes the TextureStreamingSystem and notifies the BatchManagerSystem that VT changed. -
public void ReloadVT()
: System.Void
Completes outstanding VT request dependencies, clears the local VTTextureRequester state and reloads the TextureStreamingSystem, then notifies the BatchManagerSystem of VT changes. -
public void CompleteVTRequests()
: System.Void
If VT requests were updated by AddVTRequestWriter, completes the job handle, applies VT requests to VTTextureRequester, and updates the TextureStreamingSystem working set mip bias. Should be called from main thread at the appropriate time in the frame. -
private CustomBatch CreateBatch(int groupIndex, int batchIndex, Entity sharedMesh, ref GroupData groupData, ref BatchData batchData, out PropertyData lodFadeData)
: CustomBatch
The core routine that synthesizes a CustomBatch for a specific group/batch index. Responsibilities: - Determine whether this is a zone/net/object/lane/etc. and gather the appropriate surfaceAsset, MeshData, SharedMeshData and RenderPrefab components.
- Build and populate a MaterialKey using either a SurfaceAsset (preferred) or an existing Material template.
- Set up material property blocks (textures, vector/float properties), set shader keywords, and register VT requests via VTTextureRequester as needed.
- Decide batch flags (motion vectors, animated, emissive, infoview color, outline, etc.), shadow settings, render layer assignment.
- Either reuse or create Materials from m_Materials using CreateMaterial.
-
Return a CustomBatch instance ready to be added to ManagedBatches/BatchMeshSystem. This method touches many systems and must be called from the main thread (it interacts with Unity objects & the EntityManager).
-
public void SetupVT(RenderPrefab meshPrefab, Material material, int materialIndex)
: System.Void
Helper to bind material VT parameter blocks based on a mesh prefab's VTAtlassingInfos. Used when manually binding the VT param blocks for materials. -
private Material CreateMaterial(SurfaceAsset sourceSurface, Material sourceMaterial, MaterialKey materialKey)
: Material
Creates a Unity Material instance either from a SurfaceAsset template (preferred) or from the provided sourceMaterial. Applies float/int/vector/color defaults from SurfaceAsset, sets textures (TextureAsset.Load when appropriate), applies cached keyword changes (enable/disable), sets decal-layer-mask & renderQueue overrides and binds VT texture param blocks for stacks listed in materialKey.vtStacks. Returns the created Material (HideFlags.HideAndDontSave). -
private void EnableKeyword(MaterialKey materialKey, string keyword)
: System.Void
Adds a shader keyword to the transient MaterialKey and records the change in the m_CachedKeywords buffer so the created Material will enable it. -
private void DisableKeyword(MaterialKey materialKey, string keyword)
: System.Void
Analogous to EnableKeyword but remove a keyword and record the removal. -
private void SetTexture(MaterialKey materialKey, int nameID, Texture texture)
: System.Void
Ensures the materialKey stores the provided texture for the given property name ID and records the change in m_CachedTextures so the created Material receives the texture. -
public static Material GetTemplate(SurfaceAsset surfaceAsset)
: Material
Returns the template material for a SurfaceAsset or falls back to SurfaceAsset.kDefaultMaterial when none is present.
Notes: Many of these methods interact with NativeBatchGroups, ManagedBatches and the Unity ECS EntityManager. They perform allocations carefully (reuse MaterialKey / GroupKey objects) but still operate on the main thread and must be used in the context of the game's systems lifecycle. Virtual Texturing uses a job writer/reader pattern: producers write requests in jobs and call AddVTRequestWriter with a JobHandle; the managed system later completes that handle and consumes the requests.
Usage Example
// From another managed system or mod entry point:
var mbs = World.GetOrCreateSystemManaged<Game.Rendering.ManagedBatchSystem>();
// Ensure any VT requests produced by jobs are completed & applied this frame:
mbs.CompleteVTRequests();
// Query counts / inspect material cache (read-only):
int mats = mbs.materialCount;
var materialCache = mbs.materials;
// Trigger a VT full reset (forces TextureStreamingSystem reinitialization):
mbs.ResetVT(desiredMipBias: 0, filterMode: UnityEngine.Rendering.VirtualTexturing.FilterMode.Point);
// If you need to reload VT textures:
mbs.ReloadVT();
(When modifying runtime behavior, prefer calling public API methods such as ResetVT, ReloadVT, CompleteVTRequests, or EnabledShadersUpdated. Do not call internal CreateBatch directly from user code — it expects specific GroupData/BatchData layout from the BatchManagerSystem.)