Skip to content

Game.Tools.AreaToolSystem

Assembly:
Namespace: Game.Tools

Type: class

Base: ToolBaseSystem

Summary:
AreaToolSystem is the main tool system used by the Area (polygon) editing and generation tools in Cities: Skylines 2. It provides functionality for creating, modifying and removing Areas (lots, districts, spaces, surfaces and map tiles), handles user input, snapping logic, raycasting, and jobified search/definition creation. The system coordinates multiple subsystems (area/net/object search systems, tool output barrier, audio manager) and schedules Burst-compiled jobs (SnapJob, RemoveMapTilesJob, CreateDefinitionsJob) to keep UI responsive while computing snapping, temporary area definitions and apply/clear operations. It exposes mode/state/tooltip enums for UI and supports editor vs gameplay mode differences (auto-parenting, lot grid snapping, etc.).
This class is intended for use by the in-game tool framework and can be referenced by mods that need to interact with or extend area editing behavior (e.g. custom area prefabs, tool actions, or hooking into apply/clear flows).


Fields

  • private ObjectToolSystem m_ObjectToolSystem
    This stores a reference to the ObjectToolSystem obtained from the World; used to switch back to the object tool or coordinate behavior when area editing is combined with object operations.

  • private Game.Areas.SearchSystem m_AreaSearchSystem
    Reference to the area search system used to retrieve existing area geometry for snapping and queries. SnapJob and CreateDefinitionsJob use search trees provided by this system.

  • private Game.Net.SearchSystem m_NetSearchSystem
    Reference to network search system used when snapping to network geometry (roads, rails, etc.).

  • private Game.Objects.SearchSystem m_ObjectSearchSystem
    Reference to object search system used when snapping to objects (buildings, props).

  • private ToolOutputBarrier m_ToolOutputBarrier
    Command buffer barrier used to emit creation/clear commands (CreationDefinition, ObjectDefinition, OwnerDefinition, etc.) produced by CreateDefinitionsJob and other jobs.

  • private AudioManager m_AudioManager
    Reference to audio manager to play UI sounds for actions like drop point, remove point, finish area, fail place.

  • private IProxyAction m_AddAreaNode (and many more IProxyAction fields)
    Proxy actions fetched from InputManager for mapping UI/keyboard/controller actions to tool actions (Add Area Node, Insert Area Node, Merge Area Node, Move Area Node, etc.). These are used for apply/secondary/cancel overrides.

  • private bool m_ApplyBlocked
    Flag used to temporarily block apply actions (used when canceling modifications etc.).

  • private EntityQuery m_DefinitionQuery
    Query identifying previously created temporary definition entities that the tool uses to show preview definitions.

  • private ControlPoint m_LastRaycastPoint
    Last raycast result (ControlPoint) used to detect changes and avoid unnecessary updates.

  • private NativeList<ControlPoint> m_ControlPoints
    Native list storing the current control points (the points that define the polygon being created or the currently selected control point).

  • private NativeList<ControlPoint> m_MoveStartPositions
    Native list storing the original positions used when entering Modify/Remove states (to support cancel/undo semantics).

  • private NativeValue<Tooltip> m_Tooltip
    Native value storing the currently computed Tooltip enum for the UI.

  • private Mode m_LastMode
    Stores the last actual mode to detect mode changes.

  • private State m_State
    Current internal state of the tool (Default, Create, Modify, Remove).

  • private AreaPrefab m_Prefab
    Currently selected area prefab object (nullable). Setting this influences available snapping, whether generation mode is allowed, etc.

  • private bool m_ControlPointsMoved
    Flag indicating control points have moved since selection (used to decide apply behavior).

  • private bool m_AllowCreateArea
    Computed flag indicating whether creation of areas is allowed given current prefab and mode.

  • private bool m_ForceCancel
    Used to force a cancel for only a single frame (internal control).

  • private TypeHandle __TypeHandle
    Struct holding ComponentLookup/BufferLookup/TypeHandle references used by jobs and scheduled work.

(Above are key/representative fields — the class contains many more fields for queries, actions, and Component/Buffer lookups used by the jobs.)

Properties

  • public override string toolID { get; }
    Returns "Area Tool". Used by UI/tool registry.

  • public override int uiModeIndex { get; }
    UI mode index for tool mode selection (maps to Mode values).

  • public Mode mode { get; set; }
    Currently selected tool mode (Edit or Generate). Note: actualMode can restrict to Edit when generation is not allowed.

  • public Mode actualMode { get; }
    Read-only property that returns the effective mode used (if generation isn't allowed, returns Edit regardless of mode).

  • public Entity recreate { get; set; }
    If set, area recreate flow is used (start create from an existing area).

  • public bool underground { get; set; }
    Whether the tool's raycast should prefer underground surfaces for object surface snapping.

  • public bool allowGenerate { get; private set; }
    Indicates whether generation mode is available for the current prefab / action mode.

  • public State state { get; }
    Read-only current tool State (Default/Create/Modify/Remove).

  • public Tooltip tooltip { get; }
    Current tooltip to display to the user (CreateArea, ModifyNode, etc.), computed every update in CreateDefinitionsJob.

  • public AreaPrefab prefab { get; set; }
    Selected AreaPrefab (managed property). Setting this updates allowGenerate and fires EventPrefabChanged on the tool system.

  • private protected override IEnumerable<IProxyAction> toolActions { get; }
    Enumeration of actions the tool exposes (Add/Insert/Merge/Move/Delete/Undo/Complete/Create/Delete/Discard/Combined actions). These are used to present UI action hints and bind behavior.

Constructors

  • public AreaToolSystem()
    Default constructor. The system is a managed SystemBase-derived tool system; real initialization is done in OnCreate. The constructor is kept for ECS/system instantiation but does not perform heavy initialization (that happens in OnCreate/OnStartRunning).

Methods

  • [Preserve] protected override void OnCreate()
    Initializes referenced systems (ObjectToolSystem, SearchSystems), creates queries, fetches input actions from InputManager, configures initial snap mask, and allocates persistent Native containers (m_ControlPoints, m_MoveStartPositions, m_Tooltip). Called once when the system is created.

  • [Preserve] protected override void OnDestroy()
    Disposes native containers and calls base.OnDestroy.

  • [Preserve] protected override void OnStartRunning()
    Reset runtime state when the system starts running: clears control points, resets last raycast points, mode/state/tooltips and flags.

  • [Preserve] protected override void OnStopRunning()
    Clears recreate and calls base.OnStopRunning.

  • private protected override void UpdateActions()
    Updates apply/secondary/cancel action enabled states and overrides using current tool state and control points. Uses ProxyAction.DeferStateUpdating to defer state changes during evaluation.

  • public NativeList<ControlPoint> GetControlPoints(out NativeList<ControlPoint> moveStartPositions, out JobHandle dependencies)
    Accessor for other systems to read current control points and move start positions plus dependency handle.

  • public override PrefabBase GetPrefab()
    Returns current PrefabBase (AreaPrefab) used by the tool.

  • public override bool TrySetPrefab(PrefabBase prefab)
    Try to set the tool's prefab. Accepts AreaPrefab types only and returns true on success.

  • public override void SetUnderground(bool underground) / ElevationUp() / ElevationDown() / ElevationScroll()
    Methods to control underground/elevation toggle used by UI bindings.

  • public override void InitializeRaycast()
    Set up ToolRaycastSystem flags, type masks and area type masks according to the currently selected prefab and snap options. Ensures the raycast includes sub-elements, water, static objects, placeholders (editor mode) and handles underground collision mask when ObjectSurface snap is used.

  • [Preserve] protected override JobHandle OnUpdate(JobHandle inputDeps)
    Main update loop of the system. Handles mode switches, action input handling (apply/cancel/secondary), sets up state transitions (Default/Create/Modify/Remove), triggers SnapControlPoints (schedules SnapJob) and UpdateDefinitions (schedules CreateDefinitionsJob / RemoveMapTilesJob and writes to m_ToolOutputBarrier), and manages apply/clear logic.

  • private JobHandle SnapControlPoints(JobHandle inputDeps, NativeArray<Entity> applyTempAreas)
    Schedules and configures the Burst-compiled SnapJob which computes snapping for the active control point(s). The job reads search trees (area, net, object), component lookups and writes updated control points / best snap positions. It adds the job handle as a reader to the corresponding search systems.

  • private JobHandle UpdateDefinitions(JobHandle inputDeps, NativeArray<Entity> applyTempAreas, NativeArray<Entity> applyTempBuildings)
    Destroys previous preview definitions and schedules CreateDefinitionsJob (and RemoveMapTilesJob for generation mode) to create preview definitions (CreationDefinition entities) describing what will be placed or cleared. CommandBuffer writes are done through ToolOutputBarrier.

  • private JobHandle Clear(JobHandle inputDeps)
    Helper to set apply mode to Clear and return without scheduling further work.

  • private JobHandle Cancel(JobHandle inputDeps, bool singleFrameOnly = false)
    Handles cancel logic for each state: transitions between Default/Create/Modify/Remove and schedules snap/definition updates as needed. Sets base.applyMode accordingly (Apply vs Clear) and plays UI sounds via AudioManager.

  • private JobHandle Apply(JobHandle inputDeps, bool singleFrameOnly = false)
    Handles apply logic for each state. For Create it validates min node distances, checks Temp Area completeness and either applies (generates CreationDefinitions to creation buffer) or clears previews. For Modify it may start a create subflow or finalize modifications. For Generate mode it may create grid map tiles. Plays UI sounds and uses m_ToolOutputBarrier for command emission.

  • private JobHandle Update(JobHandle inputDeps, bool fullUpdate)
    Updates control points using the latest raycast result (GetRaycastResult), triggers SnapControlPoints and UpdateDefinitions where required, and sets applyMode appropriately.

  • private static void GetAvailableSnapMask(AreaGeometryData prefabAreaData, bool editorMode, out Snap onMask, out Snap offMask)
    Static helper computing which Snap bits are available for a given Area type and whether the tool is in editor mode (includes AutoParent and LotGrid when in editor).

  • Various private helper methods used by CreateDefinitionsJob (GetControlPoints, Edit, Generate, GetSourceArea, CheckSubObjects, GetOwnerDefinition, UpdateOwnerObject, UpdateSubNets, UpdateSubAreas, HasEdgeStartOrEnd, FindParentMesh, FixControlPointPosition, AddControlPoints, FindControlPoint, FindParent).
    These helpers encapsulate the detailed geometry, ownership and creation-definition logic used when assembling CreationDefinition/ObjectDefinition/OwnerDefinition entities for the tool output.

  • Several nested Burst-compiled job structs:

  • SnapJob : IJob — performs spatial queries (area/net/object search trees) to compute snapping (snap positions, snap lines, best snap priority) for control points. Uses several iterators (ParentObjectIterator, AreaIterator2, AreaIterator, NetIterator, ObjectIterator) that implement INativeQuadTreeIterator to traverse quadtrees and gather snap candidates.
  • RemoveMapTilesJob : IJobChunk — used in Generate mode to convert existing MapTile areas to temporary CreationDefinition entities marked for deletion (so they get removed when generating new tiles).
  • CreateDefinitionsJob : IJob — composes CreationDefinition entities (and related OwnerDefinition/ObjectDefinition/NetCourse data) based on the current m_ControlPoints and state. Decides tooltips and whether a preview entity should be created as Delete/Recreate/Relocate/Upgrade etc. Handles sub-objects, sub-nets and owner object updates for the preview application step.

  • protected override void OnCreateForCompiler()
    Internal wiring used by source-gen / ECS compiler to assign queries and type handles.

(There are many more private helper methods and nested iterator structs in the class; above are the primary public/important internal methods and job entry points.)

Usage Example

// Example: hooking into the tool to set an area prefab and initialize behavior
[Preserve]
protected override void OnCreate()
{
    base.OnCreate();
    // Get the AreaToolSystem instance from the world (if you are inside another system
    // or use your mod to fetch the existing tool system)
    var areaTool = World.GetOrCreateSystemManaged<Game.Tools.AreaToolSystem>();
    // Set a prefab by trying to assign a PrefabBase that is an AreaPrefab.
    // This will update snapping masks and allowGenerate accordingly.
    areaTool.TrySetPrefab(myAreaPrefab);
    // Optionally switch to Generate mode if allowed
    areaTool.mode = Game.Tools.AreaToolSystem.Mode.Generate;
}

Notes / tips for modders: - The tool heavily relies on ECS ComponentLookup/BufferLookup and Native containers. If you need to call into or schedule similar jobs, mirror the pattern used for TypeHandle and internal lookups. - SnapJob and CreateDefinitionsJob are Burst-compiled and read many component lookups; when modifying or extending, ensure thread-safety and proper read-only annotations. - To create or remove preview items programmatically, you can inspect CreationDefinition / OwnerDefinition / ObjectDefinition components emitted by CreateDefinitionsJob (they are created through the ToolOutputBarrier command buffer). - Use the tool's public API (TrySetPrefab, GetControlPoints) and input proxy actions to integrate custom UI or tooling flows.