Skip to content

Game.MeshSystem

Assembly:
{{ Usually contained in the main game assembly for prefabs (e.g. Game.dll). }}

Namespace: Game.Prefabs

Type: class

Base: GameSystemBase

Summary:
MeshSystem is an ECS system responsible for initializing and maintaining per-prefab mesh metadata used by the renderer and batching systems. It populates MeshData and related buffers (LOD meshes, procedural bones, lights, materials, flags and layers) from RenderPrefab properties, computes LOD and shadow LOD biases, and sets up material indices used by the ManagedBatchSystem. It also schedules jobs to remove batch groups/instances when prefabs are deleted. The system uses Unity Jobs (Burst-compiled) to parallelize initialization and interacts with BatchManagerSystem and ManagedBatchSystem for native batch data management.


Fields

  • private PrefabSystem m_PrefabSystem
    {{ Reference to the PrefabSystem used to resolve RenderPrefab instances and prefab entity mappings. }}

  • private BatchManagerSystem m_BatchManagerSystem
    {{ Reference to the BatchManagerSystem used to obtain native batch groups/instances/subbatches and to register job writers. }}

  • private ManagedBatchSystem m_ManagedBatchSystem
    {{ Reference to the managed batch system used for higher-level batch operations (for example RemoveMesh calls when prefabs are removed). }}

  • private EntityQuery m_PrefabQuery
    {{ EntityQuery used to find entities with MeshData + PrefabData and created/deleted flags; used as the main query in OnUpdate. }}

  • private Dictionary<ManagedBatchSystem.MaterialKey, int> m_MaterialIndex
    {{ Cache mapping of material keys (constructed from SurfaceAsset properties) to integer indices used by MeshMaterial entries. Prevents repeated expensive material property loads. }}

  • private ManagedBatchSystem.MaterialKey m_CachedMaterialKey
    {{ A single reusable MaterialKey instance used to reduce garbage allocations when computing material indices. }}

  • private TypeHandle __TypeHandle
    {{ Internal helper that stores the various Unity.Entities type/handle references (EntityTypeHandle, ComponentTypeHandle, BufferTypeHandles, BufferLookups, etc.) used during scheduling and job setup. }}

Properties

  • None.
    {{ MeshSystem does not expose properties; it provides a public GetMaterialIndex method and lifecycle overrides. }}

Constructors

  • public MeshSystem()
    {{ Default (preserved) constructor. Actual initialization of referenced subsystems and the entity query is performed in OnCreate(). The constructor is marked with [Preserve] in the source to avoid stripping. }}

Methods

  • protected override void OnCreate() : System.Void
    {{ Called when the system is created. It resolves and caches references to PrefabSystem, BatchManagerSystem and ManagedBatchSystem from the world, constructs the EntityQuery that selects MeshData + PrefabData entities (including Created/Deleted), initializes the material index dictionary, and registers RequireForUpdate for the prefab query. Use this to see how the system wires itself into other game systems. }}

  • public int GetMaterialIndex(SurfaceAsset surface)
    {{ Computes (and caches) an integer index for a given SurfaceAsset. This:

  • Loads SurfaceAsset properties (surface.LoadProperties(useVT: true)),
  • Initializes a ManagedBatchSystem.MaterialKey from the surface,
  • Looks up or inserts the key into m_MaterialIndex and returns a stable int index,
  • Clears/returns the temporary MaterialKey instance for reuse,
  • Calls surface.Unload() after use. This index is used to populate MeshMaterial entries for mesh materials. }}

  • protected override void OnUpdate() : System.Void
    {{ Core update method. Behavior overview:

  • Collects archetype chunks matching m_PrefabQuery,
  • Completes previous job dependencies,
  • Iterates chunks: for deleted-prefab entities, triggers ManagedBatchSystem.RemoveMesh(entity) and marks that batch removals are needed,
  • For live prefabs, reads RenderPrefab data and populates MeshData for each prefab entity: bounds, submesh counts, index counts, LOD bias, smoothing and shadow biases, default mesh layers, MeshFlags (Impostor, Decal, Animated, Skeleton, Tiling, Invert, Base, MinBounds, Default), tiling counts, min/ max bounds adjustments, and MeshMaterial indices using GetMaterialIndex,
  • Fills/initializes buffers: LodMesh, ProceduralBone (including computing source indices, hierarchy depths, object positions/rotations and sorting bones), ProceduralLight + LightAnimation buffer data (including signal group animations and curve-based animations),
  • Configures tunnel/pipeline/sub-pipeline layers and curve properties if relevant,
  • Schedules a Burst-compiled InitializeMeshJob (IJobParallelFor) to complete per-chunk bone initialization in parallel,
  • If deleted prefabs were found, schedules a RemoveBatchGroupsJob (IJobChunk) that removes related batch groups/instances from native batch structures, updates MeshBatch/FadeBatch buffers, and calls native batch group/instance/subbatch removals. This job registers as a writer against BatchManagerSystem native data and the dependency chain is managed via JobHandles. Notes:
  • Uses InternalCompilerInterface type-handle helpers to obtain proper handles for jobs,
  • Uses CompleteDependency() and explicit JobHandle combination to ensure correct ordering. }}

  • protected override void OnCreateForCompiler() : System.Void
    {{ Internal/compiler-oriented setup used to assign queries and type handles when generating system code. It calls __AssignQueries and __TypeHandle.__AssignHandles(ref state). Not typically used by mod code. }}

  • Several nested/private types (Burst compiled jobs and helpers):

  • RemoveBatchGroupsJob : IJobChunk
    {{ Job that runs over chunks with Deleted components to remove group/instance entries from the native batch collections (NativeBatchGroups/NativeBatchInstances/NativeSubBatches) and updates per-entity MeshBatch and FadeBatch buffers accordingly. Handles merged groups and unlink logic. Burst compiled. }}
  • InitializeMeshJob : IJobParallelFor
    {{ Job that processes chunk buffers of ProceduralBone to compute hierarchy depths, source indices, object positions and rotations and sorts bones to ensure correct ordering for runtime skinning. Uses a local BoneParentComparer and temporary NativeList for traversal. Burst compiled. }}
  • TypeHandle (nested struct)
    {{ Holds Unity.Entities type handles and buffer lookups used to build and schedule jobs and to access components/buffers in OnUpdate. }}

Usage Example

// Example: retrieve the MeshSystem from the world and get the material index for a SurfaceAsset
var meshSystem = base.World.GetOrCreateSystemManaged<Game.Prefabs.MeshSystem>();
int matIndex = meshSystem.GetMaterialIndex(surfaceAsset);

// Mesh data initialization is handled automatically by the system during its update,
// so modders typically only interact with GetMaterialIndex or rely on the MeshData
// populated by this system when creating/updating prefab entities.

Additional notes: - MeshSystem is tightly coupled to the game's batching and rendering pipeline. Modifications to meshes, surface assets, or prefab components that affect meshes (LOD, emissive lights, procedural animation, overlays, tunnels, decals, stacking, curve properties, etc.) must consider MeshSystem behavior. - The system uses Unity Jobs and Burst for parallelization. Ensure job dependencies are respected when interacting with native batch data (BatchManagerSystem).