Skip to content

Instantly share code, notes, and snippets.

@TJHeuvel
Created November 8, 2022 20:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TJHeuvel/2c5de2268fa3d73d57759450e45919df to your computer and use it in GitHub Desktop.
Save TJHeuvel/2c5de2268fa3d73d57759450e45919df to your computer and use it in GitHub Desktop.
JobTest
using Unity.Burst;
using Unity.Collections;
using Unity.Mathematics;
using Unity.Jobs;
using UnityEngine;
[ExecuteAlways]
public class JobTest : MonoBehaviour
{
NativeArray<float3> allPositions;
void OnEnable()
{
allPositions = new NativeArray<float3>(30000, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
var rnd = new Unity.Mathematics.Random(123);
for (int i = 0; i < allPositions.Length; i++)
{
allPositions[i] = rnd.NextFloat3(new float3(100, 10, 100));
}
}
void OnDisable()
{
allPositions.Dispose();
}
void OnDrawGizmos()
{
NativeList<int> indices = new NativeList<int>(allPositions.Length, Allocator.TempJob);
NativeArray<float> distanceScores = new NativeArray<float>(allPositions.Length, //I am unsure how to make this an appropiate length, it should be the result of indices.
Allocator.TempJob);
var filterHandle = new FilterPointsBasedOnDistance()
{
allPositions = allPositions,
maxSqrPosition = 20 * 20,
targetPosition = transform.position
}.ScheduleAppend(indices, allPositions.Length, 32);
var scoreDistance = new ScorePoints()
{
indices = indices.AsDeferredJobArray(),
allPositions = allPositions,
distanceScores = distanceScores
};
var scoreHandle = scoreDistance.Schedule(indices, 32, filterHandle);
scoreHandle.Complete();
float minScore = float.MaxValue, maxScore = float.MinValue;
for (int i = 0; i < indices.Length; i++)
{
float score = distanceScores[i];
minScore = Mathf.Min(score, minScore);
maxScore = Mathf.Max(score, maxScore);
}
for (int i = 0; i < indices.Length; i++)
{
float score = distanceScores[i];
Gizmos.color = Color.Lerp(Color.red, Color.green, Mathf.InverseLerp(minScore, maxScore, score));
Gizmos.DrawSphere(allPositions[indices[i]], .5f);
}
distanceScores.Dispose();
indices.Dispose();
}
[BurstCompile]
struct FilterPointsBasedOnDistance : IJobParallelForFilter
{
[ReadOnly] public NativeArray<float3> allPositions;
[ReadOnly] public float3 targetPosition;
[ReadOnly] public float maxSqrPosition;
public bool Execute(int index) => math.distancesq(allPositions[index], targetPosition) < maxSqrPosition;
}
struct ScorePoints : IJobParallelForDefer
{
[ReadOnly] public NativeArray<int> indices;
[ReadOnly] public NativeArray<float3> allPositions;
[WriteOnly] public NativeArray<float> distanceScores;
public void Execute(int index)
{
distanceScores[index] = allPositions[indices[index]].x;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment