Game.Rendering.TerrainMaterialSystem
Assembly: Game
Namespace: Game.Rendering
Type: class
Base: GameSystemBase, IDefaultSerializable, ISerializable, IPostDeserialize
Summary:
TerrainMaterialSystem is responsible for generating and updating terrain splatmaps (both local and world), providing terrain-related shader properties and textures, creating a noise texture used by terrain shaders, and tracking terrain material prefabs used by terraforming. It uses a CommandBuffer to render splatmap updates into RenderTextures, exposes a public splatmap texture for materials, and updates global shader state required by terrain rendering (including support for water & snow textures). It also serializes/deserializes a list of terrain material prefab references.
Nested types
- ShaderID (class)
Contains many shader property IDs used by the system (examples): - _HeightMapArray, _WaterTexture, _NoiseTex
- _HeightMapArrayOffsetScale, _HeightScaleOffset, _SplatHeightVariance
- _SplatRockLimit, _SplatGrassLimit, _WorldAdjust, _NoiseOffset
- _Splatmap, _VTScaleOffset, _PlayableScaleOffset, _InvVTBorder
- colossal_ prefixed IDs (colossal_Splatmap, colossal_WorldSplatmap, colossal_Terrain textures, etc.)
These are static readonly ints generated via Shader.PropertyToID and used throughout the class to bind textures and vectors to shaders.
Fields
-
private ILog log
Logger instance ("TerrainTexturing") used for trace/debug logging. -
private static readonly float4 kClearViewport
Constant viewport value used to indicate a full/clear update (initialized to (0,0,1,1)). -
private const int m_SplatUpdateSize = 128
Constant indicating internal update subdivision size (used while iterating updates). -
private const int m_SplatRegularUpdateTick = 8
Constant tick interval used to control periodic updates. -
private float m_TerrainVTBorder = 1000f
Border size used when computing virtual texture scale/offset for playable area. -
private TerrainSystem m_TerrainSystem
Reference to the TerrainSystem (obtained from World). -
private WaterRenderSystem m_WaterRenderSystem
Reference to the WaterRenderSystem (for water texture binding). -
private PrefabSystem m_PrefabSystem
Reference to the PrefabSystem (used to resolve terraform prefab metadata). -
private SnowSystem m_SnowSystem
Reference to SnowSystem (provides snow height/backdrop textures). -
private Material m_SplatMaterial
Internal material used to render/update the splatmap (a copy of the configured splat material). -
private MaterialPropertyBlock m_Properties
Reusable MaterialPropertyBlock used when drawing into render targets. -
private Mesh m_BlitMesh
Simple full-screen triangle mesh used for blitting/drawing passes. -
private RenderTexture m_SplatMap
High-resolution (4096x4096) splatmap RenderTexture used by terrain materials. -
private RenderTexture m_SplatWorldMap
Lower-resolution (1024x1024) world splatmap RenderTexture used for backdrop/overview. -
private CommandBuffer m_CommandBuffer
Command buffer named "TerrainMaterialSystem" used to enqueue splatmap rendering commands. -
private Texture2D m_Noise
256x256 R8 noise texture (Perlin noise) used by splat material/shaders. -
private int m_UpdateIndex
Internal index used to iterate small sections of the splatmap for periodic updates. -
private int m_UpdateTick
Tick counter to throttle regular updates. -
private bool m_ForceUpdateWholeSplatmap
When set, forces a full splatmap/world update on next OnUpdate. -
private NativeList<Entity> m_MaterialPrefabs
Native list of Entity references to terrain material (terraforming) prefabs. Serialized for save/load.
Properties
-
private Material splatMaterial { get; set; }
Backing property for the splat material. The setter clones the provided Material (new Material(value)) to avoid modifying the shared asset. -
public Texture splatmap { get; }
Public accessor exposing the current splatmap RenderTexture (m_SplatMap). Used by terrain materials and other systems.
Constructors
public TerrainMaterialSystem()
Default constructor. The heavy initialization occurs in OnCreate().
Methods
-
protected override void OnCreate()
Initializes system references (TerrainSystem, WaterRenderSystem, SnowSystem, PrefabSystem), creates the CommandBuffer, loads the configured splat material and terrain textures from AssetDatabaseResources.Terrain, creates noise texture, allocates the splatmap and world splatmap RenderTextures (4096 and 1024), sets up the blit mesh used for rendering, and allocates the NativeList for material prefabs. -
public int GetOrAddMaterialIndex(Entity prefab)
Returns the index of a terraform/material prefab in m_MaterialPrefabs. If not present, adds it, logs the addition (with prefab name), retrieves TerrainMaterialProperties from the prefab (to ensure it exists) and returns the new index. Used to map prefab entities to a compact index for terrain material lookups. -
public void Serialize<TWriter>(TWriter writer) where TWriter : IWriter
Writes m_MaterialPrefabs to the provided writer for save serialization. -
public void Deserialize<TReader>(TReader reader) where TReader : IReader
Reads m_MaterialPrefabs from the provided reader for load deserialization. -
public void SetDefaults(Context context)
Clears the m_MaterialPrefabs list (called when resetting defaults). -
public void PatchReferences(ref PrefabReferences references)
After deserialization, patches each Entity in m_MaterialPrefabs using PrefabReferences.Check to ensure the references are valid in the current EntityManager. -
public void PostDeserialize(Context context)
Empty implementation, provided for IPostDeserialize. (No extra work required after patching in current code.) -
public void ForceUpdateWholeSplatmap()
Sets m_ForceUpdateWholeSplatmap to true to force a full splatmap/world splatmap rebuild on the next update. -
protected override void OnUpdate()
Main update loop: checks prerequisites (splat material and terrain cascade texture must exist). If heightmap slices changed or a forced update is set or periodic update tick reached, it enqueues DrawMesh commands into m_CommandBuffer to update portions or all of the splatmap. It also updates water surface areas to match the updated playable area. When changes were enqueued, the command buffer is executed with Graphics.ExecuteCommandBuffer. Uses profiling scopes and logs. -
protected override void OnDestroy()
Cleans up/destroys created resources: Destroy m_SplatMap and m_SplatWorldMap, dispose m_MaterialPrefabs, destroy m_Noise and m_BlitMesh. -
private void UpdateSplatmap(CommandBuffer cmd, float4 viewport, bool bWorldUpdate)
Internal method that constructs shader parameter vectors, sets MaterialPropertyBlock textures and vectors (heightmap cascade texture, water texture, noise, offsets, tiling, limits, etc.), and issues DrawMesh calls into the provided CommandBuffer to render the splatmap into m_SplatMap for the given viewport. If bWorldUpdate is true, it also renders into m_SplatWorldMap using adjusted parameters and world offsets. Uses RenderBuffer load/store actions to control whether parts are updated or fully replaced. -
public void UpdateMaterial(Material material)
Binds the generated splatmap and snow height backdrop texture to the provided material, sets VT/playable area scale and offset vectors on the material, and sets corresponding global shader textures/vectors (colossal_* shader properties) so other shaders can access the splatmap and parameters. -
private void CreateNoiseTexture()
Generates a 256x256 8-bit Perlin-noise texture (TextureFormat.R8) used by the splat shader. It computes Mathf.PerlinNoise samples and writes bytes into texture pixel data, then applies the texture.
Usage Example
[Preserve]
protected override void OnCreate()
{
base.OnCreate();
// Typical initialization is handled by the system: it sets up splat material,
// creates noise and splatmap RTs, and prepares the blit mesh.
// You can force a full splatmap rebuild from other code as:
var terrainMaterialSystem = World.GetOrCreateSystemManaged<TerrainMaterialSystem>();
terrainMaterialSystem.ForceUpdateWholeSplatmap();
}
Notes and tips for modders: - The system exposes the generated splatmap via the public splatmap property and also sets global shader textures (colossal_Splatmap and colossal_WorldSplatmap). Custom shaders that sample terrain splat information should use these global IDs (or ShaderID constants) to get consistent results. - When adding custom terrain materials or terraform prefabs, use GetOrAddMaterialIndex(Entity) to obtain a stable index used internally by the terrain material logic. - The splatmap is large (4096x4096) and kept in memory; avoid creating additional copies. Use UpdateMaterial to bind it to your materials. - The CommandBuffer is executed only when the system detects changes to minimize GPU work. Use ForceUpdateWholeSplatmap() to manually request a full rebuild (for example after loading modded terrain textures).