Game.Rendering.Viewer
Assembly: Assembly-CSharp (game)
Namespace: Game.Rendering
Type: class
Base: System.Object
Summary:
Represents a rendering "viewer" tied to a Unity Camera used by the game to determine visibility, perform raycast sampling from the camera, compute viewer-related distances (closest/farthest/average/focus), manage frustum/bounds calculations and to adjust HDRP culling near plane for shadow/rendering purposes. This class is used by the rendering and simulation systems to query surfaces under the camera, maintain focus distance smoothing, and provide frustum/bounds for culling and LOD decisions. It integrates with the game's RaycastSystem, HDCamera (HDRP), and WaterSystem (sea level).
Fields
-
private ViewerDistances m_ViewerDistances
Stores measured distances relative to the viewer (closestSurface, farthestSurface, averageSurface, focus, maxDistanceToSeaLevel). Used by UpdateRaycast and other systems to adapt rendering/culling. -
private float m_TargetFocusDistance
Target focus distance computed from raycast results (used to smoothly drive camera focus). -
private float m_FocusDistanceVelocity
Velocity used by SmoothDamp for focus smoothing. -
private const int kCenterSampleCount = 4
Constant used to indicate the number of "center" samples (the first few raycast samples treated specially). -
private static int[] kSamplePattern32
Static array of 64 ints (32 pairs) forming a jitter/sample pattern used by Raycast to sample around the viewport. Values are used to compute viewport offsets for additional raycasts.
Properties
-
public ViewerDistances viewerDistances => m_ViewerDistances
Read-only accessor exposing the current ViewerDistances struct (closest/farthest/average/focus/maxDistanceToSeaLevel). Useful for other systems that need the viewer's measured surface distances. -
public float visibilityDistance => camera.farClipPlane
Convenience property returning the camera's far clip plane (used as maximum raycast distance). -
public float nearClipPlane => camera.nearClipPlane
Convenience property returning the camera's near clip plane. -
public float3 position => camera.transform.position
Viewer position in world space (from the camera's transform). -
public float3 forward => camera.transform.forward
Camera forward vector. -
public float3 right => camera.transform.right
Camera right vector. -
public Camera camera { get; private set; }
Backed property referencing the Unity Camera instance associated with this Viewer. It has a private setter (assigned in the constructor). -
public LegacyFrustumPlanes frustumPlanes => CalculateFrustumPlanes(camera)
Computes frustum planes from the camera's projection and world-to-camera matrices. Used for culling calculations. -
public Bounds bounds => UpdateBounds()
Computes and returns a Bounds that encloses the camera near point and the four far plane corners — useful for coarse spatial queries and scene bounds relative to the viewer. -
public bool shadowsAdjustStartDistance { get; set; } = true
If true, UpdatePushNearCullingPlane attempts to adjust HDRP culling near plane to improve shadow correctness/precision. -
public float pushCullingNearPlaneMultiplier { get; set; } = 0.9f
Multiplier used when computing an override near plane for culling from measured viewer distances. -
public float pushCullingNearPlaneValue { get; set; } = 100f
Value subtracted from measured closestSurface before applying the multiplier; used to compute culling override. -
public bool shadowsAdjustFarDistance { get; set; } = true
Flag present but not used in this class's methods; likely reserved for controlling far distance adjustments externally.
Constructors
public Viewer(Camera camera)
Creates a Viewer bound to the supplied Unity Camera. Stores the camera reference for further operations. Ensure the camera is valid and active in the scene; many methods read camera properties and call camera.ViewportPointToRay().
Methods
-
public bool TryGetLODParameters(out LODParameters lodParameters)
Attempts to retrieve Unity LODParameters by calling camera.TryGetCullingParameters. Returns true on success with the lodParameters filled. On failure returns false and sets lodParameters to default. Useful when you need LOD culling information for the camera. -
protected Bounds UpdateBounds()
Computes a Bounds that encloses the near plane point and the four far plane frustum corner positions in world space, based on camera transform, fieldOfView, aspect, near and far clip planes. Returns a Bounds suitable for coarse intersection queries or debug. Uses Unity.Mathematics to compute corner directions. -
private static LegacyFrustumPlanes ExtractProjectionPlanes(float4x4 worldToProjectionMatrix)
Extracts frustum plane equations (left/right/top/bottom/near/far) from a combined world-to-projection matrix. Normalizes each plane and fills a LegacyFrustumPlanes instance. This is the low-level plane-extraction routine. -
private static LegacyFrustumPlanes CalculateFrustumPlanes(Camera camera)
Convenience wrapper that multiplies camera.projectionMatrix by camera.worldToCameraMatrix and passes the result to ExtractProjectionPlanes. -
public void UpdateRaycast(RaycastSystem raycast, float deltaTime)
Reads current raycast results for this Viewer from the provided RaycastSystem (via raycast.GetResult(this)), computes distances: - Sets m_ViewerDistances.ground from the first result,
- Uses the next few results as "center" samples (kCenterSampleCount) to set focus,
- Uses remaining hits to compute closestSurface, farthestSurface and averageSurface,
-
Smoothly damps focus towards m_TargetFocusDistance using MathUtils.SmoothDamp. Also updates camera.focusDistance, calls UpdatePushNearCullingPlane() and UpdateDistanceToSeaLevel(). deltaTime is used for the smoothing function. Note: accesses NativeArray
; ensure the RaycastSystem produces results prior to calling UpdateRaycast. -
private void UpdateDistanceToSeaLevel()
Casts 4 viewport corner rays (viewport (0,0),(1,0),(0,1),(1,1)) downward and measures intersection distances against a horizontal plane at WaterSystem.SeaLevel. Computes and stores the maximum distance to sea level in m_ViewerDistances.maxDistanceToSeaLevel. Useful to know how far to sea (or water) the camera is looking. -
private void UpdatePushNearCullingPlane()
Gets an HDCamera for the associated Camera (HDCamera.GetOrCreate(camera)). If available and shadowsAdjustStartDistance is true, computes an override near plane for culling only based on the measured closest surface, using pushCullingNearPlaneValue and pushCullingNearPlaneMultiplier and clamps it between nearClipPlane and visibilityDistance * 0.1f. Sets HDCamera.overrideNearPlaneForCullingOnly to that value (or 0 when not adjusting). This is HDRP-specific and used to improve near-plane culling for shadows or rendering precision. -
public void Raycast(RaycastSystem raycast)
Populates a set of RaycastInput entries for the RaycastSystem to sample geometry below/around the camera: - Adds an initial straight-down terrain/water ray from camera position to visibilityDistance,
- Iterates the kSamplePattern32 sample pattern and for each pair computes a viewport offset (x,y) in [0,1], builds rays via camera.ViewportPointToRay and adds Line3.Segment raycast inputs. The first few samples (i < 8) include more TypeMask flags (StaticObjects, MovingObjects, Net, etc.), later samples include only Terrain and Water. The constructed RaycastInput uses CollisionMask.OnGround | CollisionMask.Overground and Layer.All for net layer mask. These inputs are then added to the RaycastSystem (raycast.AddInput(this, input)) for processing.
Usage Example
// Create a Viewer and use RaycastSystem to sample the scene from the camera
Camera cam = Camera.main;
if (cam != null)
{
Viewer viewer = new Viewer(cam);
// Request raycasts for this viewer (this queues inputs to the game's RaycastSystem)
RaycastSystem raycastSystem = /* obtain reference to the game's RaycastSystem */;
viewer.Raycast(raycastSystem);
// Later, after raycasts are processed by the system, update computed distances
float deltaTime = Time.deltaTime;
viewer.UpdateRaycast(raycastSystem, deltaTime);
// Access measured distances
var vd = viewer.viewerDistances;
Debug.Log($"Closest: {vd.closestSurface}, Focus: {vd.focus}, MaxSeaDistance: {vd.maxDistanceToSeaLevel}");
}
Notes and Modding Tips:
- Viewer depends on several game/internal systems: RaycastSystem (for ray sampling), HDCamera (HDRP wrapper), WaterSystem (sea level), MathUtils.SmoothDamp, and types like ViewerDistances and RaycastResult. Ensure these systems are available and used correctly in the mod environment.
- UpdateRaycast reads a NativeArray