Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Resolved Why slow access to NativeArray results and ColliderHit in multithreading scenario?

Discussion in 'C# Job System' started by JustTiredOfEverything, Apr 3, 2023.

  1. JustTiredOfEverything

    JustTiredOfEverything

    Joined:
    Aug 4, 2022
    Posts:
    78
    I've been working on a project that involves managing multiple combatants in a scene, and I wanted to take advantage of multithreading to improve the performance. However, I've run into an issue where accessing the NativeArray results and ColliderHit objects after the job is complete seems to be slow, which seems to offset any benefits I would gain from using Jobs.

    In my CombatantManager class, I'm using the OverlapSphereCommand.ScheduleBatch() method to perform a batched overlap sphere query for each combatant. After that, I loop through the NativeArray<ColliderHit> results to check for collisions and update the combatants' lists of nearby combatants.

    Here's the code I'm using:

    Code (CSharp):
    1.  
    2. using System.Collections.Generic;
    3. using Unity.Collections;
    4. using Unity.Jobs;
    5. using UnityEngine;
    6. using UnityEngine.Jobs;
    7. public class CombatantManager : MonoBehaviour {
    8.     public static CombatantManager instance;
    9.  
    10.     public Dictionary<Collider, Combatant> combatantsInScene = new Dictionary<Collider, Combatant> ();
    11.     private void Awake () {
    12.         if (instance == null) {
    13.             instance = this;
    14.         } else {
    15.             Destroy (gameObject);
    16.             return;
    17.         }
    18.     }
    19.  
    20.     private void Update () {
    21.         UpdateCombatantDistances ();
    22.     }
    23.  
    24.     public void RegisterCombatant (Combatant combatant) {
    25.         combatantsInScene.Add (combatant.collider, combatant);
    26.     }
    27.  
    28.     public void UnregisterCombatant (Combatant combatant) {
    29.         combatantsInScene.Remove (combatant.collider, out combatant);
    30.     }
    31.  
    32.     public void UpdateCombatantDistances () {
    33.         int combatantCount = combatantsInScene.Count;
    34.         int maxHits = 1000;
    35.  
    36.         var commands = new NativeArray<OverlapSphereCommand> (combatantCount, Allocator.TempJob);
    37.         var results = new NativeArray<ColliderHit> (combatantCount * maxHits, Allocator.TempJob);
    38.  
    39.         int index = 0;
    40.         foreach (var combatant in combatantsInScene) {
    41.             QueryParameters qParam = new QueryParameters {
    42.                 layerMask = combatant.Value.combatantDetectionLayerMask,
    43.             };
    44.             commands[index] = new OverlapSphereCommand (combatant.Value.position, combatant.Value.detectionRadius, qParam);
    45.             index++;
    46.         }
    47.         int numCombatants = combatantsInScene.Count;
    48.         int minCommandsPerJob = Mathf.Max (1, numCombatants / SystemInfo.processorCount);
    49.         JobHandle handle = OverlapSphereCommand.ScheduleBatch (commands, results, minCommandsPerJob, maxHits);
    50.         handle.Complete ();
    51.  
    52.         index = 0;
    53.         foreach (var combatant in combatantsInScene) {
    54.             List<Combatant> combatantsInRange = new List<Combatant> ();
    55.  
    56.             for (int i = index * maxHits; i < (index + 1) * maxHits; i++) {
    57.                 Collider col = results[i].collider;
    58.                 if (col) {
    59.                     combatantsInScene.TryGetValue (col, out Combatant com);
    60.                     if (com) {
    61.                         combatantsInRange.Add (com);
    62.                     }
    63.                 }
    64.             }
    65.  
    66.             combatant.Value.UpdateCombatantsInRange (combatantsInRange);
    67.             index++;
    68.         }
    69.  
    70.         commands.Dispose ();
    71.         results.Dispose ();
    72.     }
    73. }
    74.  
    The problem is that iterating through the results array and also accessing the ColliderHit objects after the job has completed are both taking a significant amount of time. This is causing the performance of the whole system to suffer, and the multithreading benefits I was hoping to achieve are being negated.

    I was wondering if anyone else has encountered this issue or has any suggestions for improving the performance of this part of the code. Is there a more efficient way to access the results and ColliderHit objects?

    Any help or suggestions would be greatly appreciated. Thank you!
     
    Last edited: Apr 3, 2023
  2. Per-Morten

    Per-Morten

    Joined:
    Aug 23, 2019
    Posts:
    119
    I'm happy to provide some help, but I have some questions first:
    Have you profiled the code (using Profiler.BeginSample/EndSample for instance) and made sure that it's the for loops at the end of the code that is slow, just so that you're not attacking the wrong parts of the code? :)

    Also, how many combatants in general do you usually have in the scene, and how many of them do you expect to be in range of each other? Depending on this number, it might be that you're better off with some spatial partitioning algorithm to find everything in range rather than some sphere casting.

    I also notice that in your loop, you go from index * maxHits to (index + 1) * maxHits, and check that the collider isn't null for each iteration. In the documentation of OverlapSphereCommand it says that after the first hit with a collider == null (or collider instance id of 0) all hits will be invalid. So from my understanding you can break out of your inner index loop if you find a result with a collider == null.

    I think ColliderHit is also a struct that can be used in Jobs and burst, so if you can make your code burstable, then you'll probably get some performance benefits there.
     
    JustTiredOfEverything likes this.
  3. JustTiredOfEverything

    JustTiredOfEverything

    Joined:
    Aug 4, 2022
    Posts:
    78
    I did but I think my brain was off. I was attacking the wrong parts of the code, as you suggested. It turns out there were other issues with my code that were much bigger concerns performance wise and addressing those seemed to help.


    At the time there were about 100-200 combatants onscreen before performance dipped below 60 frames in a build. Couldnt tell you how many were expected to be within range of each other but the answer is certainly 'a lot' or 'over 50-100' if the max was 200. I actually decided to forgo overlap sphere and went with a spatial partition, as you suggested. I made a grid that keeps track of combatants per cell and I only pull from cells within range of a combatant to do the checks. This process also happens within a Burst Compiled job. This allows me to get up to 500-1000 combatants on screen fighting each other before it dips below 60 frames in a build.
     
    Last edited: Apr 14, 2023
  4. JustTiredOfEverything

    JustTiredOfEverything

    Joined:
    Aug 4, 2022
    Posts:
    78
    So this thread is pretty much solved. Here's my CombatantManager now, now renamed to CombatantSpatialPartition, and is significantly longer than before, but provides much faster performance:

    Code (CSharp):
    1. using System.Collections.Generic;
    2. using System.Linq;
    3. using Unity.Burst;
    4. using Unity.Collections;
    5. using Unity.Jobs;
    6. using Unity.Mathematics;
    7.  
    8. #if UNITY_EDITOR
    9. using UnityEditor;
    10. #endif
    11.  
    12. using UnityEngine;
    13.  
    14. public class CombatantSpatialPartition : MonoBehaviour {
    15.     public static CombatantSpatialPartition Instance;
    16.     public int gridSize = 10;
    17.     public float cellSize = 10f;
    18.     public List<Combatant> combatantsInScene;
    19.     public List<CombatantInfo>[] grid;
    20.  
    21.     float3 gridPosition;
    22.     public static int FloorToInt (float f) => f >= 0 ? (int) f : ((int) f == f ? (int) f : (int) f - 1);
    23.     public static int CeilToInt (float f) => f < 0 ? (int) f : ((int) f + ((f - (int) f != 0) ? 1 : 0));
    24.     public static int count;
    25.  
    26.     void Awake () {
    27.         if (Instance != null) {
    28.             Destroy (gameObject);
    29.         }
    30.         Instance = this;
    31.         combatantsInScene = new List<Combatant> ();
    32.         // Initialize the grids dictionary for each team
    33.         grid = new List<CombatantInfo>[gridSize * gridSize * 2];
    34.         for (int i = 0; i < gridSize * gridSize * 2; i++) {
    35.             grid[i] = new List<CombatantInfo> ();
    36.         }
    37.     }
    38.  
    39.     void Update () {
    40.         gridPosition = transform.position;
    41.         ManageCombatants ();
    42.     }
    43.  
    44.     bool equals (int2 x, int2 y) {
    45.         return x.x == y.x && x.y == y.y;
    46.     }
    47.  
    48.     public void AddCombatant (CombatantInfo combatantInfo) {
    49.         int2 cell = WorldToGrid (combatantInfo.position);
    50.         int linearIndex = combatantInfo.teamID * (gridSize * gridSize) + cell.x * gridSize + cell.y;
    51.         grid[linearIndex].Add (combatantInfo);
    52.         count++;
    53.     }
    54.  
    55.     public void UpdateCombatant (CombatantInfo combatantInfo, float3 oldPosition) {
    56.         int2 oldCell = WorldToGrid (oldPosition);
    57.         RemoveCombatant (combatantInfo, oldCell);
    58.         AddCombatant (combatantInfo);
    59.     }
    60.  
    61.     public void RemoveCombatant (CombatantInfo combatantInfo, int2 cell) {
    62.         int linearIndex = combatantInfo.teamID * (gridSize * gridSize) + cell.x * gridSize + cell.y;
    63.         grid[linearIndex].Remove (combatantInfo);
    64.         count--;
    65.     }
    66.  
    67.     public void RemoveCombatantDeep (CombatantInfo combatantInfo) {
    68.         for (int x = 0; x < gridSize; x++) {
    69.             for (int y = 0; y < gridSize; y++) {
    70.                 int linearIndex = combatantInfo.teamID * (gridSize * gridSize) + x * gridSize + y;
    71.                 if (grid[linearIndex].Contains (combatantInfo)) {
    72.                     grid[linearIndex].Remove (combatantInfo);
    73.                     count--;
    74.                 }
    75.             }
    76.         }
    77.     }
    78.  
    79.     public void ManageCombatants () {
    80.         int count = combatantsInScene.Count;
    81.  
    82.         // Perform a single sphere cast using SpherecastCommand and wait for it to complete
    83.         // Set up the command and result buffers
    84.         var results = new NativeArray<RaycastHit> (combatantsInScene.Count, Allocator.TempJob);
    85.         var commands = new NativeArray<SpherecastCommand> (combatantsInScene.Count, Allocator.TempJob);
    86.  
    87.  
    88.         for (int i = 0; i < count; i++) {
    89.             Combatant combatant = combatantsInScene[i];
    90.             CombatantInfo info = combatant.GetInfo ();
    91.             //combatant.nearbyCombatants = ManageNearbyCells (info);
    92.             NativeList<int2> nearbyCells = new NativeList<int2> (Allocator.TempJob);
    93.  
    94.             GetNearbyCellsJob job = new GetNearbyCellsJob {
    95.                 combatantInfo = info,
    96.                 gridSize = gridSize,
    97.                 cellSize = cellSize,
    98.                 gridPosition = gridPosition,
    99.                 nearbyCells = nearbyCells
    100.             };
    101.  
    102.             JobHandle jobHandle = job.Schedule ();
    103.             jobHandle.Complete ();
    104.  
    105.             List<int2> nearbyCellsList = new List<int2> ();
    106.             for (int j = 0; j < nearbyCells.Length; j++) {
    107.                 nearbyCellsList.Add (nearbyCells[j]);
    108.             }
    109.             nearbyCells.Dispose ();
    110.             combatant.nearbyCells = nearbyCellsList;
    111.  
    112.  
    113.  
    114.  
    115.              if (!combatant.seekingEnemy) {
    116.                 continue;
    117.             }
    118.             // Set the data of the first command
    119.             Vector3 origin = combatant.position;
    120.             Vector3 direction = (combatant.closestEnemyPosition - (Vector3) combatant.position).normalized;
    121.             float radius = combatant.spherecastRadius;
    122.             QueryParameters queryParameters = new QueryParameters {
    123.                 layerMask =combatant.detectionMask,
    124.             };
    125.  
    126.             commands[i] = new SpherecastCommand (origin, radius, direction, queryParameters, Vector3.Distance (combatant.position, combatant.closestEnemyPosition)) {
    127.                 queryParameters = queryParameters,
    128.             };
    129.         }
    130.  
    131.         // Schedule the batch of sphere casts
    132.         var sphereCastHandle = SpherecastCommand.ScheduleBatch (commands, results, count / SystemInfo.processorCount, default (JobHandle));
    133.  
    134.         // Wait for the batch processing job to complete
    135.         sphereCastHandle.Complete ();
    136.  
    137.         for (int i = 0; i < count; i++) {
    138.             combatantsInScene[i].lastSphereCastHit = results[i];
    139.         }
    140.  
    141.         // Dispose the buffers
    142.         results.Dispose ();
    143.         commands.Dispose ();
    144.     }
    145.  
    146.     public float3 GridToWorld (int2 gridPosition) {
    147.         float3 min = this.gridPosition - new float3 (gridSize * cellSize, 0, gridSize * cellSize) * 0.5f;
    148.         return new float3 (min.x + gridPosition.x * cellSize + cellSize / 2, 0, min.z + gridPosition.y * cellSize + cellSize / 2);
    149.     }
    150.  
    151.     public int2 WorldToGrid (float3 pos) {
    152.         float3 min = gridPosition - new float3 (gridSize * cellSize, 0, gridSize * cellSize) * 0.5f;
    153.         int2 gridCoordinates = new int2 (
    154.             Mathf.FloorToInt ((pos.x - min.x) / cellSize),
    155.             Mathf.FloorToInt ((pos.z - min.z) / cellSize)
    156.         );
    157.  
    158.         // Clamp the grid coordinates within the grid bounds
    159.         gridCoordinates.x = Mathf.Clamp (gridCoordinates.x, 0, gridSize - 1);
    160.         gridCoordinates.y = Mathf.Clamp (gridCoordinates.y, 0, gridSize - 1);
    161.  
    162.         return gridCoordinates;
    163.     }
    164.  
    165.     [BurstCompile]
    166.     public struct GetNearbyCellsJob : IJob {
    167.         [ReadOnly] public CombatantInfo combatantInfo;
    168.         [ReadOnly] public int gridSize;
    169.         [ReadOnly] public float cellSize;
    170.         [ReadOnly] public float3 gridPosition;
    171.         [WriteOnly] public NativeList<int2> nearbyCells;
    172.  
    173.         public void Execute () {
    174.             CombatantInfo combatant = combatantInfo;
    175.             float radius = combatant.combatantCheckRadius;
    176.             float3 pos = combatant.position;
    177.             int2 centerCell = WorldToGrid (pos);
    178.  
    179.             int combatantTeamID = combatant.teamID;
    180.             int enemyTeamID = combatantTeamID == 0 ? 1 : 0;
    181.             int cellsToCheck = CeilToInt (radius / cellSize);
    182.             int2 minCell = new int2 (math.max (0, centerCell.x - cellsToCheck), math.max (0, centerCell.y - cellsToCheck));
    183.             int2 maxCell = new int2 (math.min (gridSize - 1, centerCell.x + cellsToCheck), math.min (gridSize - 1, centerCell.y + cellsToCheck));
    184.             int totalCells = (maxCell.x - minCell.x + 1) * (maxCell.y - minCell.y + 1);
    185.             for (int i = 0; i < totalCells; i++) {
    186.                 int x = minCell.x + (i % (maxCell.x - minCell.x + 1));
    187.                 int z = minCell.y + (i / (maxCell.x - minCell.x + 1));
    188.                 int2 cell = new int2 (x, z);
    189.  
    190.                 // Check if the cell is within the grid boundaries
    191.                 if (x >= 0 && x < gridSize && z >= 0 && z < gridSize) {
    192.                     // Calculate the cell's center position in world coordinates
    193.                     float3 cellCenter = GridToWorld (cell);
    194.                     // Check if the cell is within the combatant's radius
    195.                     if (math.distance (pos, cellCenter) <= radius + math.sqrt (2 * cellSize * cellSize) / 2) {
    196.                         int linearIndex = enemyTeamID * (gridSize * gridSize) + x * gridSize + z;
    197.                         nearbyCells.Add (cell);
    198.                     }
    199.                 }
    200.             }
    201.         }
    202.  
    203.         public float3 GridToWorld (int2 gridPosition) {
    204.             float3 min = this.gridPosition - new float3 (gridSize * cellSize, 0, gridSize * cellSize) * 0.5f;
    205.             return new float3 (min.x + gridPosition.x * cellSize + cellSize / 2, 0, min.z + gridPosition.y * cellSize + cellSize / 2);
    206.         }
    207.  
    208.         public int2 WorldToGrid (float3 pos) {
    209.             float3 min = gridPosition - new float3 (gridSize * cellSize, 0, gridSize * cellSize) * 0.5f;
    210.             int2 gridCoordinates = new int2 (
    211.                 Mathf.FloorToInt ((pos.x - min.x) / cellSize),
    212.                 Mathf.FloorToInt ((pos.z - min.z) / cellSize)
    213.             );
    214.  
    215.             // Clamp the grid coordinates within the grid bounds
    216.             gridCoordinates.x = Mathf.Clamp (gridCoordinates.x, 0, gridSize - 1);
    217.             gridCoordinates.y = Mathf.Clamp (gridCoordinates.y, 0, gridSize - 1);
    218.  
    219.             return gridCoordinates;
    220.         }
    221.     }
    222.  
    223.     void OnDrawGizmos () {
    224.         if (!Application.isPlaying) {
    225.             return;
    226.         }
    227.         Vector3 min = transform.position - new Vector3 (gridSize * cellSize, 0, gridSize * cellSize) * 0.5f;
    228.         for (int x = 0; x < gridSize; x++) {
    229.             for (int z = 0; z < gridSize; z++) {
    230.                 int2 cellCoord = new int2 (x, z);
    231.                 Vector3 cellCenter = new Vector3 (min.x + x * cellSize + cellSize / 2, 0, min.z + z * cellSize + cellSize / 2);
    232.  
    233.                 int combatantCount = 0;
    234.                 if (grid != null) {
    235.                     for (int i = 0; i < 2; i++) {
    236.                         int linearIndex = i * (gridSize * gridSize) + x * gridSize + z;
    237.                         foreach (var teamGrids in grid[linearIndex]) {
    238.                             combatantCount++;
    239.                         }
    240.                     }
    241.                 }
    242.                 // Fill cell with color based on combatant count
    243.                 Gizmos.color = combatantCount > 0 ? Color.green : Color.white;
    244.                 Gizmos.DrawWireCube (cellCenter, new Vector3 (cellSize, 0.1f, cellSize));
    245.                 // Draw combatant count label on cell
    246.  
    247.                 GUIStyle style = new GUIStyle ();
    248.                 style.normal.textColor = Color.black;
    249.                 style.alignment = TextAnchor.MiddleCenter;
    250.                 style.fontSize = 14;
    251. #if UNITY_EDITOR
    252.                 Handles.Label (cellCenter, combatantCount.ToString (), style);
    253. #endif
    254.             }
    255.         }
    256.         Gizmos.color = Color.white;
    257.     }
    258. }
    Note: Some comments are artifacts from previous script versions
     
    Last edited: Apr 14, 2023