Skip to content

Game.Simulation.TrainLaneSpeedIterator

Assembly: Assembly-CSharp.dll
Namespace: Game.Simulation

Type: struct

Base: System.ValueType

Summary:
TrainLaneSpeedIterator is a low-level iterator/utility used by the train/rail simulation to walk along lane curves (track lanes), inspect lane objects, overlapping lanes and signals, and compute a safe maximum target speed for a train controller given the current situation (signals, reservations, obstacles, braking distances). It tracks blocker entities and blocker types (temporary, continuing, signal, etc.) and accumulates traveled distance and relevant positions while traversing connected lane segments. This struct is intended to be used inside simulation systems or jobs that evaluate train movement and braking behavior.


Fields

  • public ComponentLookup<Transform> m_TransformData
    Component lookup for Transform components (positions/rotations) of objects encountered while iterating lanes.

  • public ComponentLookup<Moving> m_MovingData
    Lookup for Moving components to read velocities of objects on lanes.

  • public ComponentLookup<Car> m_CarData
    Lookup for Car components to determine priorities and attributes of cars when checking objects.

  • public ComponentLookup<Train> m_TrainData
    Lookup for Train components for train objects (to determine flags like reversed).

  • public ComponentLookup<Curve> m_CurveData
    Lookup for Curve components describing lane bezier curves & lengths.

  • public ComponentLookup<Game.Net.TrackLane> m_TrackLaneData
    Lookup for TrackLane data that contains lane flags and properties (e.g., exclusive flag).

  • public ComponentLookup<Controller> m_ControllerData
    Lookup for Controller components used to resolve lane objects' controllers.

  • public ComponentLookup<LaneReservation> m_LaneReservationData
    Lookup for lane reservations used to test blocking/priority/reservation offsets.

  • public ComponentLookup<LaneSignal> m_LaneSignalData
    Lookup for lane signals (Stop/Yield/SafeStop and blockers).

  • public ComponentLookup<Creature> m_CreatureData
    Lookup to identify pedestrians/creatures on lanes.

  • public ComponentLookup<PrefabRef> m_PrefabRefData
    Lookup from entity to its prefab reference, used to fetch prefab-specific data.

  • public ComponentLookup<ObjectGeometryData> m_PrefabObjectGeometryData
    Lookup for object geometry of prefabs (used for pedestrian/object extents).

  • public ComponentLookup<CarData> m_PrefabCarData
    Lookup for CarData prefab values (braking, etc.) used when calculating braking against moving cars.

  • public ComponentLookup<TrainData> m_PrefabTrainData
    Lookup for TrainData prefab values (braking, attach offsets, bogie offsets) used for braking calculations.

  • public BufferLookup<LaneOverlap> m_LaneOverlapData
    Buffer lookup of lane overlap records (parallel/crossing/merge overlaps with other lanes).

  • public BufferLookup<LaneObject> m_LaneObjectData
    Buffer lookup of lane objects (tracked objects on a lane) used to identify physical blockers.

  • public Entity m_Controller
    The controller entity for which we are computing speeds (the train controller that owns the evaluated train).

  • public int m_Priority
    Priority ranking of the controller/vehicle used to resolve conflicts with lane reservations and merges.

  • public float m_TimeStep
    Simulation time step used for dynamic braking/speed calculations.

  • public float m_SafeTimeStep
    A safer (usually larger) timestep used for more conservative braking computations.

  • public float m_CurrentSpeed
    Current speed of the evaluated train (used to compute stopping/braking behavior).

  • public TrainData m_PrefabTrain
    TrainData describing the train prefab being evaluated (braking, offsets, track type).

  • public ObjectGeometryData m_PrefabObjectGeometry
    Geometry data for the controller's prefab (used for collision spacing).

  • public Bounds1 m_SpeedRange
    Allowed speed range (min/max) for clamping computed speeds.

  • public float3 m_RearPosition
    World-space position of the rear of the train (used to limit detection distance).

  • public bool m_PushBlockers
    If true, temporary blockers may be pushed; affects pedestrian handling and safe speed computation.

  • public float m_MaxSpeed
    Current computed maximum allowed speed while iterating. This is updated downward when blockers/conditions are found.

  • public float3 m_CurrentPosition
    Current world-space position that corresponds to the iterator's end point along the traversed curve.

  • public float m_Distance
    Accumulated traveled "distance" along the traversal used to compute braking distance.

  • public Entity m_Blocker
    Entity identified as the current reason for speed limiting (could be a lane object, signal blocker, reservation owner).

  • public BlockerType m_BlockerType
    Enum indicating type of blockage (None, Temporary, Continuing, Crossing, Signal, Limit, etc.).

  • private Entity m_Lane
    Currently processed lane entity (private internal state).

  • private Curve m_Curve
    Current lane's Curve component cached for faster access.

  • private float2 m_CurveOffset
    Current curve offset (start/end offsets on the curve segment) cached.

  • private float3 m_PrevPosition
    Previous sampled position used to compute segment lengths and relative geometry.

  • private float m_PrevDistance
    Previously recorded accumulated distance for geometry comparisons.

Properties

  • None.
    This struct exposes only public fields to be initialized by the caller before use. There are no auto-properties in this type.

Constructors

  • public TrainLaneSpeedIterator()
    Default value-type constructor (implicit). Users should initialize the ComponentLookup/BufferLookup fields and public configuration fields (m_Controller, m_PrefabTrain, m_TimeStep, m_SafeTimeStep, m_SpeedRange, etc.) before calling iteration methods. No special runtime initialization is performed by the struct itself.

Methods

  • public bool IterateFirstLane(Entity lane, float4 curveOffset, bool exclusive, bool ignoreObstacles, bool skipCurrent, out bool needSignal)
    Start iteration at the first lane segment. It initializes internal distance/position state using provided curve offsets and checks the lane's drive speed, lane signals, lane reservations and lane objects (unless ignoreObstacles is true). It updates m_MaxSpeed and blocker info, advances m_CurrentPosition to the curveOffset.w position and increases m_Distance by the segment length. Returns true if the iterator has accumulated enough distance (relative to braking/signal distances) to stop iterating further or if m_MaxSpeed has already reached the minimum of m_SpeedRange. The out parameter needSignal indicates if the lane has a lane signal that should be considered by the calling code.

Notes: - curveOffset is a float4 of offsets used to sample two positions on this lane's bezier (typical use: start/back/front offsets). - exclusive toggles special behavior when lanes are exclusive and lane reservations apply. - skipCurrent prevents CheckCurrentLane when you do not want to test lane objects on the current lane (useful when starting inside your own lane objects).

  • public void IteratePrevLane(Entity lane, out bool needSignal)
    Check a previous/adjacent lane for lower speed limits without changing position/travel distance. It inspects lane signals and track properties and updates m_MaxSpeed if the previous lane enforces a lower speed. Sets needSignal if the lane has a signal component.

  • public bool IterateNextLane(Entity lane, float2 curveOffset, float minOffset, bool exclusive, bool ignoreObstacles, out bool needSignal)
    Advance to and process a next lane segment. Similar to IterateFirstLane but for subsequent segments. It determines the lane's allowed speed from TrackLane data and lane signals, computes a conservative speed (considering braking at current speed or max speed), then optionally checks lane objects and overlapping lanes. It advances m_CurrentPosition and m_Distance using the supplied curve offsets and returns true when the required braking distance was exceeded or m_MaxSpeed was clamped to minimum.

Parameters: - curveOffset: float2 offsets used to sample positions on the next lane's bezier; used to compute segment length. - minOffset: used to avoid interactions with objects before a certain offset on the lane. - yieldOverride interacts with lane signals/priority resolution.

  • public bool IterateTarget(Entity lane, bool ignoreObstacles)
    Final target lane evaluation: checks if the train's braking ability over the remaining m_Distance requires lowering m_MaxSpeed. If a reservation exists on the lane, it checks if the reservation belongs to the same controller (if not ignoring obstacles) and sets a continuing blocker if necessary. Returns true if m_MaxSpeed was lowered.

  • public bool IterateTarget()
    Overload that computes braking-based max speed for the accumulated m_Distance and updates m_MaxSpeed and clears blockers if speed is reduced. Returns true when m_MaxSpeed changed.

  • private void CheckCurrentLane(float distance, float2 minOffset, bool exclusive)
    Inspect lane objects on the current lane (m_Lane) and update m_MaxSpeed and blockers accordingly. If exclusive mode is enabled, objects are treated as continuing blockers (more conservative). In non-exclusive mode it uses object curve positions and GetObjectSpeed to determine safe passing gaps.

  • private void CheckOverlappingLanes(float origDistance, float origMinOffset, int yieldOverride, bool exclusive)
    Check overlapping/parallel/crossing lanes using the LaneOverlap buffer. This is one of the more complex parts: it handles merge starts/ends, priority deltas, lane reservations on overlapping lanes, lane object scanning on the other lane, pedestrian checks, and priority-based spacing adjustments. It uses m_Curve and the cached bezier to compute geometry for overlap detection and updates m_MaxSpeed and blockers using UpdateMaxSpeed or temporarily limiting speed when exclusive reservations are present.

  • private float GetObjectSpeed(Entity obj, float curveOffset)
    Returns the speed of a lane object projected along the tangent of the current lane curve at curveOffset. If the object has no Moving component, returns 0.

  • private void CheckPedestrian(Line3.Segment overlapLine, Entity obj, float targetOffset, float distanceOffset, bool giveSpace)
    Special-case handling for pedestrian/creature lane objects. Computes distance from the overlap segment to the pedestrian and determines if a pedestrian should be considered a blocker. Takes into account prefab geometry size, object facing, and whether the pedestrian is moving; computes an appropriate safe speed and sets m_Blocker as Temporary if it reduces m_MaxSpeed.

  • private void UpdateMaxSpeed(Entity obj, BlockerType blockerType, float objectSpeed, float laneOffset, float distanceFactor, float distanceOffset)
    Generic routine to compute the conservative speed limit based on another object (car, train, or static object). It uses prefab-specific braking parameters and distances, geometry offsets and relative positions to compute a braking distance required to avoid collision and converts that into a target speed for m_PrefabTrain. If the computed max speed is less than current m_MaxSpeed, it updates m_MaxSpeed and records the blocker and blockerType.

Usage Example

// Example usage sketch inside a simulation system (pseudo-code).
TrainLaneSpeedIterator it = new TrainLaneSpeedIterator();

// Initialize lookups (typically in OnCreate or OnUpdate of a SystemBase):
it.m_TransformData = GetComponentLookup<Transform>(true);
it.m_MovingData = GetComponentLookup<Moving>(true);
it.m_CarData = GetComponentLookup<Car>(true);
it.m_TrainData = GetComponentLookup<Train>(true);
it.m_CurveData = GetComponentLookup<Curve>(true);
it.m_TrackLaneData = GetComponentLookup<Game.Net.TrackLane>(true);
it.m_ControllerData = GetComponentLookup<Controller>(true);
it.m_LaneReservationData = GetComponentLookup<LaneReservation>(true);
it.m_LaneSignalData = GetComponentLookup<LaneSignal>(true);
it.m_CreatureData = GetComponentLookup<Creature>(true);
it.m_PrefabRefData = GetComponentLookup<PrefabRef>(true);
it.m_PrefabObjectGeometryData = GetComponentLookup<ObjectGeometryData>(true);
it.m_PrefabCarData = GetComponentLookup<CarData>(true);
it.m_PrefabTrainData = GetComponentLookup<TrainData>(true);
it.m_LaneOverlapData = GetBufferLookup<LaneOverlap>(true);
it.m_LaneObjectData = GetBufferLookup<LaneObject>(true);

// Set runtime params for this controller/train:
it.m_Controller = controllerEntity;
it.m_PrefabTrain = prefabTrainData;
it.m_PrefabObjectGeometry = prefabObjectGeometry;
it.m_RearPosition = rearWorldPos;
it.m_TimeStep = deltaTime;
it.m_SafeTimeStep = safeDelta;
it.m_CurrentSpeed = currentSpeed;
it.m_SpeedRange = new Bounds1(minSpeed, maxSpeed);
it.m_MaxSpeed = it.m_SpeedRange.y; // start at max allowed

// Iterate lanes (high-level):
bool needSignal;
if (it.IterateFirstLane(startLane, firstCurveOffset, exclusive: false, ignoreObstacles: false, skipCurrent: false, out needSignal))
{
    // Either reached braking threshold or speed already constrained.
}
// For each next lane connected:
if (it.IterateNextLane(nextLane, nextCurveOffset, minOffset, exclusive: false, ignoreObstacles: false, out needSignal))
{
    // break iteration if returned true.
}
// At target:
it.IterateTarget(targetLane, ignoreObstacles: false);

// Result:
float safeSpeed = it.m_MaxSpeed;
Entity blocker = it.m_Blocker;
BlockerType type = it.m_BlockerType;

Notes: - This iterator is stateful and meant to be used per-evaluation. Callers must configure the lookups and parameter fields before iterating. - Many operations rely on correct, up-to-date ComponentLookup/BufferLookup access modes (read-only vs writable) and should be used inside simulation systems that respect Unity's Entities safety rules. - The functions make many physics/geometry and prefab-dependent assumptions (braking formulas in VehicleUtils, offsets in TrainData/ObjectGeometryData) so ensure correct prefab data is supplied.