Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity job system and multi dimensional arrays

Tags:

unity3d

I have a IJobParallelFor where each job creates an array of data

I have tried using NativeArray<float[]> but that doesn't work because it is a reference type and I have tried NativeArray<NativeArray<float>> but that doesn't work because

...However, a type that contains a variable array of blittable types is not itself blittable.

Source: MSDN blittable types

Is there any way to get around this without using a giant one dimensional array and calculating the index's by hand? This is not nice since you have to use [NativeDisableParallelForRestriction] to access the array outside each jobs range.

My job:

public struct DistanceJob : IJobParallelFor
{
    [NativeDisableParallelForRestriction] public NativeArray<float> distance;
    [ReadOnly] public NativeArray<Vector2> position;

    public void Execute(int i)
    {
        for (int j = 0; j < position.Length; j++)
            distance[i * position.Length + j] = Vector2.Distance(position[i], position[j]);
    }
}

I know there are other algorithms that are not n^2 to do this but this is just a toy example of a real problem.

like image 564
Imapler Avatar asked Sep 22 '18 19:09

Imapler


3 Answers

If I understand the question correctly, the Unity NativeMultiHashMap could help you. You can try something like:

public NativeMultiHashMap<float, NativeArray<float>> FooBar 
             = new NativeMultiHashMap<float, NativeArray<float>>();

At any point you can now use the key to add a value as a NativeArray.

like image 116
Raph_Wa Avatar answered Oct 29 '22 19:10

Raph_Wa


Based on Raph_Wa awnser i used a

NativeHashMap<int, NativeList<Vector3>> distance;

Then each job gets a list each

public void Execute(int i)
{
    NativeList<Vector3> a;
    distance.TryGet(i, out a);

    for (int j = 0; j < position.Length; j++)
        a[j] = Vector2.Distance(position[i], position[j]);

    distance.TryAdd(i, a);
}
like image 43
Imapler Avatar answered Oct 29 '22 20:10

Imapler


You can also, in addition, get your NativeArray pointer, store it in an IntPtr, and add it, instead of the array itself, to your array (it's a way of circumventing the nesting limitation of arrays). So, when using arrays in code, just convert them back to the array (I usually use the UnsafeUtility and UnsafeUtilityEx methods).

like image 39
DiaDeTedio Avatar answered Oct 29 '22 18:10

DiaDeTedio