Skip to content

Game.Simulation.ElectricityFlowJob

Assembly:
Assembly-CSharp.dll

Namespace:
Game.Simulation

Type:
struct

Base:
Unity.Jobs.IJob

Summary:
ElectricityFlowJob is a Burst-compiled IJob that runs the multi-stage electricity flow solver used by the simulation. It drives a maximum-flow style solver across several phases (Initial, Producer, PostProducer, Battery, PostBattery, Trade, PostTrade, Complete) to compute how power is produced, stored, traded and delivered. The job operates on low-level Native* containers (NativeArray, NativeList, NativeQueue, NativeReference) and directly mutates nodes, edges and connection state used by the electrical flow system. It is intended to be scheduled as a Unity job; the caller is responsible for allocating and disposing all Native containers and ensuring thread-safety of accesses.


Fields

  • private const int kConnectedNodeLabel = -1
    Identifier value used for labeling connected nodes during the connected-phase.

  • private const int kShortageNodeLabel = -2
    Identifier value used for labeling shortage nodes.

  • private const int kBeforeBottleneckNodeLabel = -3
    Identifier value used for nodes classified as before a bottleneck.

  • private const int kBeyondBottleneckNodeLabel = -4
    Identifier value used for nodes classified as beyond a bottleneck.

  • public const int kConnectedEdgeLabel = -1
    Identifier value used for labeling connected edges.

  • public const int kBottleneckEdgeLabel = -2
    Identifier value used for labeling bottleneck edges.

  • public const int kBeyondBottleneckEdgeLabel = -3
    Identifier value used for labeling edges beyond a bottleneck.

  • public NativeReference<State> m_State
    NativeReference wrapping the solver State (phase, step counters, error flag). Shared between frames so the solver can continue across multiple job runs.

  • public NativeArray<Game.Simulation.Flow.Node> m_Nodes
    Array of flow nodes representing the electrical network nodes. The job reads and writes node cut-element ids and other node data.

  • public NativeArray<Game.Simulation.Flow.Edge> m_Edges
    Array of flow edges representing network connections and capacities. The job updates edge directions, residuals and cut-element ids.

  • [ReadOnly] public NativeArray<Connection> m_Connections
    Read-only array of Connection structs that relate nodes and edges. Used to traverse the network.

  • [ReadOnly] public NativeReference<NodeIndices> m_NodeIndices
    Reference to NodeIndices (source and sink indices and related metadata). Read-only for the job.

  • [ReadOnly] public NativeArray<int> m_ChargeNodes
    Indices of nodes that can charge (batteries). Read-only list of node indices to process in the battery phases.

  • [ReadOnly] public NativeArray<int> m_DischargeNodes
    Indices of nodes that can discharge (batteries). Read-only.

  • [ReadOnly] public NativeArray<int> m_TradeNodes
    Indices of nodes that can perform trade (import/export) operations. Read-only.

  • public NativeReference<MaxFlowSolverState> m_SolverState
    Persistent solver state used to save/load the MaxFlowSolver progress between job invocations.

  • public NativeList<LayerState> m_LayerStates
    Persistent list of layer states used by the MaxFlowSolver to continue across frames.

  • public NativeList<CutElement> m_LayerElements
    Persistent list of cut elements allocated by the solver.

  • public NativeList<CutElementRef> m_LayerElementRefs
    Persistent list of references into layer elements (used by the solver).

  • public NativeQueue<int> m_LabelQueue
    Queue used for BFS/labeling algorithms (shortages, connected components, bottlenecks).

  • public int m_LayerHeight
    The layer height parameter required by the MaxFlowSolver (max number of layers).

  • public int m_FrameCount
    Number of frames (or a multiplier) used to scale how many solver steps are allowed per Execute call.

  • public bool m_FinalFrame
    When true, the job will run until completion (not restricted by per-frame step caps) and will finalize solver state at the end.

Properties

  • (None)
    This struct does not expose C# properties; it uses public Native* fields instead.

Constructors

  • (None)
    No explicit constructor is defined. Use the compiler-generated default struct initializer and then populate the required Native fields before scheduling the job.

Methods

  • public void Execute()
    Entry point for the IJob. Manages the overall state machine: checks for error state, calculates step budget based on m_FrameCount and previous step counts, and iteratively executes phases until either the solver finishes or the step budget is exhausted. If m_FinalFrame is set, Execute will continue until completion and then call Finalize.

  • private void Finalize(ref State state)
    Resets state to the initial phase and stores the last total step count. Called when the solver completes (typically on final frame).

  • private void ExecutePhase(ref State state, int maxSteps)
    Dispatches execution to the appropriate phase handler depending on state.m_Phase. Phases include Initial, Producer, PostProducer, Battery, PostBattery, Trade, PostTrade.

  • private void InitialPhase(ref State state)
    Prepares for a new max-flow phase by resetting solver state and advancing to the Producer phase.

  • private void ResetSolverState()
    Clears m_SolverState and empties the persistent layer lists (m_LayerStates, m_LayerElements, m_LayerElementRefs). Used between phases to start a fresh max-flow computation.

  • private void MaxFlowPhase(ref State state, int maxSteps, Phase phaseAfterCompletion)
    Core routine that initializes a MaxFlowSolver instance, either resets or loads saved solver state, and iteratively calls SolveNextLayer() until the solver reports completion or the max step budget is reached. It saves solver state back into persistent containers so the computation can resume on a later frame. It allocates temporary NativeList and an active queue array; these are disposed before return. On completion, state.m_Phase is advanced to phaseAfterCompletion.

  • private void PostProducerPhase(ref State state)
    After producer-phase max-flow, this runs labeling to detect shortages, enables discharge connections where shortages exist, enables charge connections where shortages do not exist, resets solver state, and advances to the Battery phase.

  • private void LabelShortages(ref State state)
    Starts labeling shortages by inspecting connections from the sink and enqueuing connected subgraphs that have incoming capacity and residual capacity.

  • private void LabelShortageSubGraph(ref State state, int initialNodeIndex)
    Performs BFS from a given initial node to label all nodes reachable via incoming edges that have residual capacity. Marks nodes with the shortage label and updates step counter.

  • private void EnableDischargeConnectionsIfShortage()
    For each discharge node, inspects its connections and enables (sets edge direction to Forward) connections that lead into a shortage-labeled subgraph.

  • private void EnableChargeConnectionsIfNoShortage()
    For each charge node, inspects connections and enables (sets edge direction to Forward) those that lead to areas not labeled as shortage.

  • private void PostBatteryPhase(ref State state)
    After battery-phase max-flow, disables charge/discharge connections, labels shortages again, enables trade connections, resets solver state, and advances to the Trade phase.

  • private void DisableConnections(NativeArray<int> nodes)
    Helper that sets m_Direction = FlowDirection.None for all edges connected to the given node indices.

  • private void EnableTradeConnections()
    For each trade node, sets edge directions toward source or sink depending on whether the node is marked as in-shortage or not. Uses NodeIndices to identify source/sink.

  • private void PostTradePhase(ref State state)
    Finalizes trade connections, labels connected nodes and bottlenecks, and moves the state to Complete.

  • private void SetTradeConnectionsEnabled(bool import, bool export)
    Enables or disables import/export directions for trade nodes by setting edge directions toward source/sink according to flags.

  • private void LabelConnected(ref State state)
    Labels nodes and edges that are connected to the source (connected component) and, where possible, explores outgoing capacity to mark subgraphs.

  • private void LabelConnectedSubGraph(ref State state, int initialNodeIndex)
    BFS that labels a connected subgraph reachable from an initial node via outgoing-capacity edges. Marks edges/nodes as connected.

  • private void LabelBottlenecks(ref State state)
    Starts bottleneck detection from the sink, marking the sink and scanning incoming edges to identify subgraphs with incoming residuals that indicate bottlenecks.

  • private void LabelBottleneckSubGraph(ref State state, int initialNodeIndex)
    Complex BFS used to classify nodes/edges around detected bottlenecks. It computes residual sums, partitions nodes into before/after bottleneck groups and assigns cut-element ids accordingly. This routine updates many edge/node cut-element ids and contains several assertions validating solver invariants.

Usage Example

// NOTE: This is an illustrative example. The job requires properly allocated
// NativeArray/NativeReference/NativeList containers populated with the
// simulation's nodes/edges/connections and solver persistent state.
//
// Prepare required native containers (allocated elsewhere):
// - m_Nodes, m_Edges, m_Connections, m_NodeIndices, m_ChargeNodes/m_DischargeNodes/m_TradeNodes
// - m_State (NativeReference<State>), m_SolverState, m_LayerStates, m_LayerElements, m_LayerElementRefs
// - m_LabelQueue
//
// Then create and schedule the job:

var job = new ElectricityFlowJob {
    m_State = myStateRef,
    m_Nodes = myNodesArray,
    m_Edges = myEdgesArray,
    m_Connections = myConnectionsArray,
    m_NodeIndices = myNodeIndicesRef,
    m_ChargeNodes = myChargeNodes,
    m_DischargeNodes = myDischargeNodes,
    m_TradeNodes = myTradeNodes,
    m_SolverState = mySolverStateRef,
    m_LayerStates = myLayerStatesList,
    m_LayerElements = myLayerElementsList,
    m_LayerElementRefs = myLayerElementRefsList,
    m_LabelQueue = myLabelQueue,
    m_LayerHeight = layerHeight,
    m_FrameCount = framesPerUpdate,
    m_FinalFrame = false // or true to force completion this run
};

// Schedule and optionally complete immediately:
var handle = job.Schedule();
handle.Complete();

Notes: - ElectricityFlowJob uses BurstCompile and low-level UnsafeList/Native containers; ensure containers are allocated with appropriate Allocator (and proper lifetime). - The job mutates node and edge cut-element identifiers and edge directions — callers should not access these containers concurrently without synchronization. - Frequent assertions are present in the implementation to validate solver invariants; these can fail in edit-time or development builds if the network state is inconsistent. - To resume a solver across multiple frames, keep m_SolverState, m_LayerStates, m_LayerElements and m_LayerElementRefs alive between job invocations.